diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/FinalParametersCheck.java b/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/FinalParametersCheck.java
index 81556bc2..e907fda0 100644
--- a/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/FinalParametersCheck.java
+++ b/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/FinalParametersCheck.java
@@ -1,73 +1,73 @@
////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2002 Oliver Burn
//
// 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 com.puppycrawl.tools.checkstyle.checks;
import com.puppycrawl.tools.checkstyle.api.Check;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
/**
* Check that method/constructor parameters are final.
* The user can set the token set to METHOD_DEF, CONSTRUCTOR_DEF, or both
* (default), to control the scope of this check.
*
* @author lkuehne
*/
public class FinalParametersCheck extends Check
{
/** @see Check */
public int[] getDefaultTokens()
{
return new int[] {TokenTypes.METHOD_DEF, TokenTypes.CTOR_DEF};
}
/** @see Check */
public void visitToken(DetailAST aAST)
{
// don't flag interfaces
final DetailAST container = aAST.getParent().getParent();
- if (container.getType() != TokenTypes.CLASS_DEF) {
+ if (container.getType() == TokenTypes.INTERFACE_DEF) {
return;
}
// exit on fast lane if there is nothing to check here
if (!aAST.branchContains(TokenTypes.PARAMETER_DEF)) {
return;
}
// we can now be sure that there is at least one parameter
DetailAST parameters = aAST.findFirstToken(TokenTypes.PARAMETERS);
DetailAST child = (DetailAST) parameters.getFirstChild();
while (child != null) {
// childs are PARAMETER_DEF and COMMA
if (child.getType() == TokenTypes.PARAMETER_DEF
&& !child.branchContains(TokenTypes.FINAL))
{
DetailAST paramName = child.findFirstToken(TokenTypes.IDENT);
// TODO: i18n
log(child.getLineNo(), child.getColumnNo(),
"Parameter " + paramName.getText() + " should be final.");
}
child = (DetailAST) child.getNextSibling();
}
}
}
| true | true | public void visitToken(DetailAST aAST)
{
// don't flag interfaces
final DetailAST container = aAST.getParent().getParent();
if (container.getType() != TokenTypes.CLASS_DEF) {
return;
}
// exit on fast lane if there is nothing to check here
if (!aAST.branchContains(TokenTypes.PARAMETER_DEF)) {
return;
}
// we can now be sure that there is at least one parameter
DetailAST parameters = aAST.findFirstToken(TokenTypes.PARAMETERS);
DetailAST child = (DetailAST) parameters.getFirstChild();
while (child != null) {
// childs are PARAMETER_DEF and COMMA
if (child.getType() == TokenTypes.PARAMETER_DEF
&& !child.branchContains(TokenTypes.FINAL))
{
DetailAST paramName = child.findFirstToken(TokenTypes.IDENT);
// TODO: i18n
log(child.getLineNo(), child.getColumnNo(),
"Parameter " + paramName.getText() + " should be final.");
}
child = (DetailAST) child.getNextSibling();
}
}
| public void visitToken(DetailAST aAST)
{
// don't flag interfaces
final DetailAST container = aAST.getParent().getParent();
if (container.getType() == TokenTypes.INTERFACE_DEF) {
return;
}
// exit on fast lane if there is nothing to check here
if (!aAST.branchContains(TokenTypes.PARAMETER_DEF)) {
return;
}
// we can now be sure that there is at least one parameter
DetailAST parameters = aAST.findFirstToken(TokenTypes.PARAMETERS);
DetailAST child = (DetailAST) parameters.getFirstChild();
while (child != null) {
// childs are PARAMETER_DEF and COMMA
if (child.getType() == TokenTypes.PARAMETER_DEF
&& !child.branchContains(TokenTypes.FINAL))
{
DetailAST paramName = child.findFirstToken(TokenTypes.IDENT);
// TODO: i18n
log(child.getLineNo(), child.getColumnNo(),
"Parameter " + paramName.getText() + " should be final.");
}
child = (DetailAST) child.getNextSibling();
}
}
|
diff --git a/Teleport/src/iggy/Transport/Transport.java b/Teleport/src/iggy/Transport/Transport.java
index 038f0f8..70ce3f6 100644
--- a/Teleport/src/iggy/Transport/Transport.java
+++ b/Teleport/src/iggy/Transport/Transport.java
@@ -1,746 +1,748 @@
package iggy.Transport;
import iggy.Regions.Position;
import iggy.Regions.Regions;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Queue;
import java.util.Set;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.server.PluginEnableEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.java.JavaPlugin;
public class Transport extends JavaPlugin {
public static Transport plugin;
public final TransportPlayerListener playerListen = new TransportPlayerListener(this);
////////////////////////////////// Variables for compass jumping ////////////
public Map<Player, Date> lastJump = new HashMap<Player, Date>();
////////////////////////////////// Variables for warping ////////////////////
public Map<String,Location> cityTeleports = new HashMap<String,Location>();
public Map<Location,String> cityActivators = new HashMap<Location,String>();
public Map<String,List<String>> playerActivations = new HashMap<String,List<String>>();
public String tempCityWarpName = "";
public Location tempCityWarpLocation = null;
///////////////////////// Variables for flying ////////////////////////////////
Map<String, Integer> flightTimeRemaining = new HashMap<String, Integer>();
////////////////////////////// File data and IO variables /////////////////////
public final Logger logger = Logger.getLogger("Minecraft");
PluginDescriptionFile pdFile;
String pluginName;
String pluginTitle;
ChatColor deactivatedWarpColor = ChatColor.DARK_PURPLE;
ChatColor activatedWarpColor = ChatColor.LIGHT_PURPLE;
///////////////////////////////////////////////////////////////////////
//////////////////////////// Plugins functions ///////////////////////////
///////////////////////////////////////////////////////////////
/********************************* LOAD CITIES ********************************\
|
\******************************************************************************/
public void loadCities () {
cityTeleports.clear();
cityActivators.clear();
//Load all the city names
ConfigurationSection cityconfiguration = this.getConfig().getConfigurationSection("city");
Set <String> cities = null;
if (cityconfiguration == null) {
severe("The list of teleport citys is missing or corrupted: recreating list");
severe("If this is the first time runing this plugin do not worry about this error");
cities = new HashSet<String>();
}
else {
cities = cityconfiguration.getKeys(false);
}
if (cities == null) {
severe("Failed to read the Configuration File");
return;
}
// iterate through the cities and get their data
Iterator<String> it = cities.iterator();
while (it.hasNext()) {
String cityName = it.next();
/// possible version 2 ///
//String warp = this.getConfig().getString("city."+cityName+".warp");
//String activator = this.getConfig().getString("city."+cityName+".activator");
// LOAD TELEPORT
World warpWorld = this.getServer().getWorld(this.getConfig().getString("city."+cityName+".warp.world"));
if (warpWorld == null) {
severe("Failed to find the world for "+cityName+"'s warp on the server");
continue;
}
Double warpX = this.getConfig().getDouble("city."+cityName+".warp.x");
Double warpY = this.getConfig().getDouble("city."+cityName+".warp.y");
Double warpZ = this.getConfig().getDouble("city."+cityName+".warp.z");
float warpYaw = Float.parseFloat(this.getConfig().getString("city."+cityName+".warp.yaw"));
float warpPitch = 0;
//LOAD ACTIVATOR
World activatorWorld = this.getServer().getWorld(this.getConfig().getString("city."+cityName+".activator.world"));
if (activatorWorld == null){
severe("Failed to find the world for "+cityName+"'s activator on the server");
continue;
}
Double activatorX = this.getConfig().getDouble("city."+cityName+".activator.x");
Double activatorY = this.getConfig().getDouble("city."+cityName+".activator.y");
Double activatorZ = this.getConfig().getDouble("city."+cityName+".activator.z");
// Put both on the lists
cityTeleports.put(cityName, new Location(warpWorld,warpX,warpY,warpZ,warpYaw,warpPitch));
cityActivators.put(new Location(activatorWorld,activatorX,activatorY,activatorZ), cityName);
}
info("Loaded \033[0;32m" + String.valueOf(cities.size()) + "\033[0m Cities \033[0;35m"+cities.toString() + "\033[0m");
}
/********************************* SAVE CITIES ********************************\
|
\******************************************************************************/
public void saveCities() {
// clear the current listing of cities
this.getConfig().set("city","");
// add the new cities warp
Iterator<Entry<String, Location>> teleportIterator = cityTeleports.entrySet().iterator();
while (teleportIterator.hasNext()) {
Entry<String,Location> pairs = teleportIterator.next();
String cityName = pairs.getKey();
info("Saving warps for :"+cityName);
// Set warp
this.getConfig().set("city."+cityName+".warp.world", pairs.getValue().getWorld().getName());
this.getConfig().set("city."+cityName+".warp.x", pairs.getValue().getX());
this.getConfig().set("city."+cityName+".warp.y", pairs.getValue().getY());
this.getConfig().set("city."+cityName+".warp.z", pairs.getValue().getZ());
this.getConfig().set("city."+cityName+".warp.yaw", pairs.getValue().getYaw());
}
// add the new cities activators
Iterator<Entry<Location, String>> activatorIterator = this.cityActivators.entrySet().iterator();
while (activatorIterator.hasNext()) {
Entry<Location, String> pairs = activatorIterator.next();
String cityName = pairs.getValue();
info("Saving activators for :"+cityName);
// Set Activator
this.getConfig().set("city."+cityName+".activator.world", pairs.getKey().getWorld().getName());
this.getConfig().set("city."+cityName+".activator.x", pairs.getKey().getX());
this.getConfig().set("city."+cityName+".activator.y", pairs.getKey().getY());
this.getConfig().set("city."+cityName+".activator.z", pairs.getKey().getZ());
}
}
/********************************** ADD CITY **********************************\
| This function adds a city to the list of citys, warps, and activators |
\******************************************************************************/
public void addCity(String city, Location warp, Location activator) {
cityActivators.put(activator, city);
cityTeleports.put(city, warp);
saveCities();
this.saveConfig();
info(city+" was created");
}
/****************************** LOAD ACTIVATIONS ******************************\
|
\******************************************************************************/
public void loadActivations() {
playerActivations.clear();
Set <String> players = null;
ConfigurationSection playersconfiguration = this.getConfig().getConfigurationSection("player");
if (playersconfiguration == null) {
severe("The list of players and activations is missing or corrupted: recreating list");
severe("If this is the first time runing this plugin do not worry about this error");
players = new HashSet<String>();
}
else {
players = playersconfiguration.getKeys(false);
}
if (players == null) {
severe("Failed to read the Configuration File");
}
// iterate through the players
Iterator<String> playerIterator = players.iterator();
while (playerIterator.hasNext()){
String playerName = playerIterator.next();
List<String> activations = this.getConfig().getStringList("player."+playerName);
if (activations == null) {
severe("Failed to read the Configuration File for " + playerName);
}
playerActivations.put(playerName, activations);
}
info("Loaded \033[0;32m" + String.valueOf(players.size()) + "\033[0m Players \033[0;35m"+players.toString() + "\033[0m");
}
/****************************** SAVE ACTIVATIONS ******************************\
|
\******************************************************************************/
public void saveActivations() {
this.getConfig().set("player", "");
Iterator<Entry<String, List<String>>> it = playerActivations.entrySet().iterator();
if (it == null){
severe("Failed to save configuration file (playerActivations iterator is null)");
return;
}
while(it.hasNext()) {
Entry<String,List<String>> pairs = it.next();
String playerName = pairs.getKey();
info("Saving player activations for \033[0;32m"+playerName+"\033[0m");
this.getConfig().set("player."+playerName,pairs.getValue());
}
}
/******************************* ADD ACTIVATIONS ******************************\
| This adds the city to the player's activated cities list. If the player |
| already has the city activated then the function returns false and does |
| nothing, on success it returns true |
\******************************************************************************/
public Boolean addActivation (String player, String city) {
List<String> activations = playerActivations.get(player);
if (activations == null) {
activations = new ArrayList<String>();
}
if(activations.contains(city)){
return false;
}
activations.add(city);
playerActivations.put(player, activations);
saveActivations();
this.saveConfig();
info(player + " activated " + city);
return true;
}
Plugin regions;
Regions regionsapi;
/********************************** ON ENABLE *********************************\
|
\******************************************************************************/
@Override
public void onEnable() {
pdFile = this.getDescription();
pluginName = pdFile.getName();
pluginTitle = "[\033[0;36m"+pluginName+"\033[0m]";
Bukkit.getServer().getPluginManager().registerEvents(playerListen, this);
loadCities();
loadActivations();
regions = Bukkit.getServer().getPluginManager().getPlugin("Regions");
if (regions == null){
severe("Cannot Find Regions Plugin");
return;
}
regionsapi = (Regions) regions;
info ("Loaded Economy");
//set up all the block listeners to prevent distruction
//economy is required for buying new chunks
//dynmap is required for mapfunctions
if (!regions.isEnabled()) {
getServer().getPluginManager().registerEvents(new OurServerListener(), this);
if (!regions.isEnabled()) {
info("Waiting for Regions to be enabled");
}
}
else {
activateRegions();
}
startFlyerCounter();
info("version " + pdFile.getVersion() +" is enabled");
}
/********************************* ON DISABLE *********************************\
|
\******************************************************************************/
@Override
public void onDisable() {
saveCities();
saveActivations();
this.saveConfig();
info("version " + pdFile.getVersion() +" is disabled");
}
//////////////////////////////////////////////////////////////////////////////
/////////////////////////// WAIT FOR OTHER PLUGINS ///////////////////////////
//////////////////////////////////////////////////////////////////////////////
// listener class to wait for the other plugins to enable
private class OurServerListener implements Listener {
// warnings are suppressed becasue this is called using registerEvents when the
@SuppressWarnings("unused")
// this function runs whenever a plugin is enabled
@EventHandler (priority = EventPriority.MONITOR)
public void onPluginEnable(PluginEnableEvent event) {
Plugin p = event.getPlugin();
String name = p.getDescription().getName();
if(name.equals("Regions")) {
activateRegions();
}
}
}
// funtion to finish activating the plugin once the other plugins are enabled
public void activateRegions(){
//TODO: make these features not enabled if the plugin is not enabeled
info ("New warp creation activated");
}
//////////////////////////////////////////////////////////////////////////////
////////////////////////////////// COMMANDS //////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
Player player = null;
if (sender instanceof Player) {
player = (Player) sender;
}
/******************************* LIST ALL WARPS *******************************\
| This command lists all of the warps that the server has regestered |
\******************************************************************************/
if (commandLabel.equalsIgnoreCase("warplist")) {
String output = "";
String differentColor = new String();
String defaultColor = new String();
if (player == null) {
differentColor = "\033[0;35m";
defaultColor = "\033[0m";
}
else {
differentColor = deactivatedWarpColor.toString();
defaultColor = ChatColor.WHITE.toString();
}
for (Entry<String, Location> warpPlace : cityTeleports.entrySet()) {
if (player == null) {
output += differentColor + warpPlace.getKey() + defaultColor + ", ";
}
else {
- if ( playerActivations.get(player.getName()).contains(warpPlace.getKey()) ) {
+ List<String> playerWarps = playerActivations.get(player.getName());
+ if (playerWarps == null) playerWarps = new ArrayList<String>();
+ if ( playerWarps.contains(warpPlace.getKey()) ) {
output += activatedWarpColor + warpPlace.getKey() + defaultColor + ", ";
}
else {
output += differentColor + warpPlace.getKey() + defaultColor + ", ";
}
}
}
if (player == null) { info (output); }
else { player.sendMessage(output); }
}
/// past here only players can enter commands ///
if (player == null) {
info("This command can only be run by a player");
return false;
}
/******************************** LIST MY WARPS *******************************\
| This function will list all of the warps that you have activated, but not |
| the ones that you have not activated. |
\******************************************************************************/
if (commandLabel.equalsIgnoreCase("mywarps")) {
List<String> activations = playerActivations.get(player.getName());
if (activations == null) {
player.sendMessage("You have no "+ChatColor.AQUA+"warps" + ChatColor.WHITE);
return false;
}
String warpOutput = "Activated Warps: ";
for (String warpName : activations) {
warpOutput += activatedWarpColor + warpName + ", ";
}
player.sendMessage(warpOutput);
}
/********************************* CREATE WARP ********************************\
|
\******************************************************************************/
if (commandLabel.equalsIgnoreCase("createwarp")){
if (player.isOp() || (player.hasPermission("teleport.createwarp"))){
if (regions != null && regions.isEnabled()) {
ItemStack item = new ItemStack(Material.SIGN);
player.getInventory().addItem(item);
Position p = new Position(player.getLocation());
String name = regionsapi.chunkNames.get(p);
if (name == null) {
player.sendMessage("You cannot create a warp to the wild");
return false;
}
player.sendMessage("Creating a warp for "+name);
tempCityWarpName = name;
tempCityWarpLocation = player.getLocation();
}
else {
player.sendMessage("Create Regions broken, regions not enabled. Contact your server admin");
}
}
else {
player.sendMessage("Ask an admin to create this warp for you");
}
}
/************************************ WARP ************************************\
| The command teleports a player to the location they specified |
\******************************************************************************/
if (commandLabel.equalsIgnoreCase("warp")){
World currentWorld = player.getWorld();
if (!(currentWorld == getServer().getWorld("world") || currentWorld == getServer().getWorld("world_nether"))) {
player.sendMessage("You can only warp from the overworld and the nether");
return false;
}
if ( args.length == 1) {
List<String> matches = findMatch (args[0]);
// if there is only one match: warp there
if (matches.size() == 1) {
String match = matches.get(0);
if (playerActivations.get(player.getName()).contains(match)) {
//attempt to teleport the player
warp(player,match);
} else {
player.sendMessage("You have not activated the "+match+" warp");
}
}
// if there are no matches
else if (matches.size() == 0) {
player.sendMessage("Cannot find the " + deactivatedWarpColor + args[0] + ChatColor.WHITE +" warp");
}
// Otherwise there are many warps
else {
String warpOutput = "Found Multiple Warps: ";
for (String match : matches) {
if (playerActivations.get(player.getName()).contains(match)) {
warpOutput += activatedWarpColor + match;
}
else {
warpOutput += deactivatedWarpColor + match;
}
warpOutput += ChatColor.WHITE;
warpOutput += ", ";
}
player.sendMessage(warpOutput);
}
}
else {
player.sendMessage("correct usage is /warp <location>");
}
}
if (commandLabel.equalsIgnoreCase("spawn")){
player.sendMessage("This function is disabled until writable books get an API");
/*World currentWorld = player.getWorld();
if (!(currentWorld == getServer().getWorld("world") || currentWorld == getServer().getWorld("world_nether"))) {
player.sendMessage("You can only warp from the overworld and the nether");
return false;
}
warp(player,"spawn");*/
}
/****************************** REFRESH / RELOAD ******************************\
|
\*****************************************************************************
if (commandLabel.equalsIgnoreCase("refresh")||commandLabel.equalsIgnoreCase("re")) {
Location myLocation = player.getLocation();
Location otherworld = new Location(getServer().getWorld("shopworld"), 0, 64, 0);
player.teleport(otherworld);
player.teleport(myLocation);
}
*/
if (commandLabel.equalsIgnoreCase("fly")) {
ItemStack boots = player.getInventory().getBoots();
String errorMessage = "You are not wearing boots with featherfall";
if (boots == null) {
player.sendMessage(errorMessage);
return false;
}
if (boots.containsEnchantment(Enchantment.PROTECTION_FALL)) {
// durration is the number of minutes the player can fly for
int durration = 5;
// change the durration depending on what type of boots the player is wearing
if (boots.getType() == Material.DIAMOND_BOOTS) { durration = 30;}
else if (boots.getType() == Material.GOLD_BOOTS) { durration = 20;}
else if (boots.getType() == Material.IRON_BOOTS) { durration = 15;}
else if (boots.getType() == Material.LEATHER_BOOTS) { durration = 5;}
// Display
player.sendMessage("You can now fly for the next " + durration + " minutes");
player.setAllowFlight(true);
flightTimeRemaining.put(player.getName(), (durration*6) + 1);
// remove the boots from the game
player.getInventory().setBoots(new ItemStack(Material.AIR,0));
}
else {
player.sendMessage(errorMessage);
}
}
if (commandLabel.equalsIgnoreCase("forcewarp")) {
if (!player.isOp()) {
player.sendMessage("Stop trying to cheat");
return false;
}
if (!regions.isEnabled()) {
player.sendMessage("The regions plugin is not enabled, it must be enabled to forcewarp");
return false;
}
if (args.length != 1) {
player.sendMessage("You need to pick one region to force warp to");
return false;
}
String warpDestination = args[0];
if (!regionsapi.chunkOwners.containsKey(warpDestination)) {
player.sendMessage("Cannot find the plot "+warpDestination);
return false;
}
Location warpLocation = null;
for (Entry<Position, String> testLocation : regionsapi.chunkNames.entrySet()) {
if (testLocation.getValue().equals(warpDestination)) {
Position position = testLocation.getKey();
World world = Bukkit.getServer().getWorld(position._world);
warpLocation = new Location (world,position.getMinimumXCorner(), 257, position.getMinimumZCorner());
}
}
if (warpLocation == null) {
player.sendMessage("Cannot find a valid warp point in " + warpDestination);
return false;
}
player.teleport(warpLocation);
}
return false;
}
public List<String> findMatch (String cityname) {
List<String> matches = new ArrayList<String>();
//
for (Entry<String, Location> warpPlace : cityTeleports.entrySet()) {
int maxLength = cityname.length();
if (warpPlace.getKey().length() < maxLength) maxLength = warpPlace.getKey().length();
if (warpPlace.getKey().substring(0, maxLength).equals(cityname)) {
matches.add(warpPlace.getKey());
}
}
return matches;
}
// queue for teleporters
public Queue<Player> teleportingPlayerQueue = new LinkedList<Player>();
public Queue<Location> teleportingDestinationQueue = new LinkedList<Location>();
// hash table for waiting teleporters
public Map<Player,Location> teleportingPlayers = new HashMap<Player,Location>();
public Map<Player,Date> lastWarpTime = new HashMap<Player,Date>();
//
public void warp (Player player, String cityname){
Date nowdate = new Date();
Date thendate = lastWarpTime.get(player);
// prevent rapid jumping or quick jumping
long nowtime = nowdate.getTime();
long thentime = 0;
if (thendate != null) {
thentime = thendate.getTime();
}
if ((nowtime - thentime) < 6000) {
int secondsRemaining = (int) (6-(nowtime - thentime)/1000);
String s = "";
if (secondsRemaining != 1) {
s = "s";
}
player.sendMessage("You must wait " + ChatColor.AQUA + secondsRemaining + ChatColor.WHITE + " second"+s+" to "+ChatColor.AQUA+"teleport" + ChatColor.WHITE);
return;
}
else {
player.sendMessage(ChatColor.AQUA + "Now warping to " + activatedWarpColor + cityname + ChatColor.WHITE);
}
lastWarpTime.put(player, nowdate);
Location teleportLocation;
if (cityname.equals("spawn")) {
teleportLocation = player.getBedSpawnLocation();
//player.get
}
else {
teleportLocation = cityTeleports.get(cityname);
}
teleportingPlayerQueue.offer(player);
teleportingDestinationQueue.offer(teleportLocation);
teleportingPlayers.put(player, player.getLocation());
// need to continue this function later
//trick the client to displaying a warp animation by creating a portal under the player
player.sendBlockChange(player.getLocation(), Material.PORTAL, (byte) 0);
getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() {
public void run() {
Player player = teleportingPlayerQueue.poll();
Location location = teleportingDestinationQueue.poll();
if (teleportingPlayers.containsKey(player)) {
teleportingPlayers.remove(player);
//location.getWorld().strikeLightningEffect(location);
Block block = player.getWorld().getBlockAt(player.getLocation());
player.sendBlockChange(player.getLocation(), block.getType(), block.getData());
// Move the player to another world so they have to reload the chunks or 'simulate the world for a bit'
Location otherworld = new Location(getServer().getWorld("shopworld"), 0, 64, 0);
player.teleport(otherworld);
// Teleport the player to the real location
player.teleport(location);
}
}
}, 120L);
}
////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
public void startFlyerCounter() {
getServer().getScheduler().scheduleSyncRepeatingTask(this, new Runnable() {
public void run() {
for (Entry<String, Integer> entry : flightTimeRemaining.entrySet()) {
Player player = getServer().getPlayer(entry.getKey());
Integer timeLeft = entry.getValue();
timeLeft--;
if ((timeLeft % 6) == 0 && timeLeft != 0) {
Integer minutesLeft = timeLeft/6;
player.sendMessage("" + minutesLeft + " minutes remaining in flight");
}
if (timeLeft <= 5 && timeLeft > 0) {
player.sendMessage(""+(timeLeft*10)+" seconds remaining in flight");
}
if (timeLeft == 0) {
player.sendMessage("Flight Time Up");
player.setAllowFlight(false);
flightTimeRemaining.remove(entry.getKey());
}
else {
player.setAllowFlight(true);
flightTimeRemaining.put(entry.getKey(), timeLeft);
}
}
}
}, 0L, 200L);
}
//////////////////////////////////////////////////////////////////////////////
/////////////////////////////// DISPLAY HELPERS //////////////////////////////
//////////////////////////////////////////////////////////////////////////////
public void info(String input) {
this.logger.info(" "+pluginTitle + " " +input);
}
public void severe (String input) {
this.logger.severe(pluginTitle+" \033[31m"+input+"\033[0m");
}
}
| true | true | public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
Player player = null;
if (sender instanceof Player) {
player = (Player) sender;
}
/******************************* LIST ALL WARPS *******************************\
| This command lists all of the warps that the server has regestered |
\******************************************************************************/
if (commandLabel.equalsIgnoreCase("warplist")) {
String output = "";
String differentColor = new String();
String defaultColor = new String();
if (player == null) {
differentColor = "\033[0;35m";
defaultColor = "\033[0m";
}
else {
differentColor = deactivatedWarpColor.toString();
defaultColor = ChatColor.WHITE.toString();
}
for (Entry<String, Location> warpPlace : cityTeleports.entrySet()) {
if (player == null) {
output += differentColor + warpPlace.getKey() + defaultColor + ", ";
}
else {
if ( playerActivations.get(player.getName()).contains(warpPlace.getKey()) ) {
output += activatedWarpColor + warpPlace.getKey() + defaultColor + ", ";
}
else {
output += differentColor + warpPlace.getKey() + defaultColor + ", ";
}
}
}
if (player == null) { info (output); }
else { player.sendMessage(output); }
}
/// past here only players can enter commands ///
if (player == null) {
info("This command can only be run by a player");
return false;
}
/******************************** LIST MY WARPS *******************************\
| This function will list all of the warps that you have activated, but not |
| the ones that you have not activated. |
\******************************************************************************/
if (commandLabel.equalsIgnoreCase("mywarps")) {
List<String> activations = playerActivations.get(player.getName());
if (activations == null) {
player.sendMessage("You have no "+ChatColor.AQUA+"warps" + ChatColor.WHITE);
return false;
}
String warpOutput = "Activated Warps: ";
for (String warpName : activations) {
warpOutput += activatedWarpColor + warpName + ", ";
}
player.sendMessage(warpOutput);
}
/********************************* CREATE WARP ********************************\
|
\******************************************************************************/
if (commandLabel.equalsIgnoreCase("createwarp")){
if (player.isOp() || (player.hasPermission("teleport.createwarp"))){
if (regions != null && regions.isEnabled()) {
ItemStack item = new ItemStack(Material.SIGN);
player.getInventory().addItem(item);
Position p = new Position(player.getLocation());
String name = regionsapi.chunkNames.get(p);
if (name == null) {
player.sendMessage("You cannot create a warp to the wild");
return false;
}
player.sendMessage("Creating a warp for "+name);
tempCityWarpName = name;
tempCityWarpLocation = player.getLocation();
}
else {
player.sendMessage("Create Regions broken, regions not enabled. Contact your server admin");
}
}
else {
player.sendMessage("Ask an admin to create this warp for you");
}
}
/************************************ WARP ************************************\
| The command teleports a player to the location they specified |
\******************************************************************************/
if (commandLabel.equalsIgnoreCase("warp")){
World currentWorld = player.getWorld();
if (!(currentWorld == getServer().getWorld("world") || currentWorld == getServer().getWorld("world_nether"))) {
player.sendMessage("You can only warp from the overworld and the nether");
return false;
}
if ( args.length == 1) {
List<String> matches = findMatch (args[0]);
// if there is only one match: warp there
if (matches.size() == 1) {
String match = matches.get(0);
if (playerActivations.get(player.getName()).contains(match)) {
//attempt to teleport the player
warp(player,match);
} else {
player.sendMessage("You have not activated the "+match+" warp");
}
}
// if there are no matches
else if (matches.size() == 0) {
player.sendMessage("Cannot find the " + deactivatedWarpColor + args[0] + ChatColor.WHITE +" warp");
}
// Otherwise there are many warps
else {
String warpOutput = "Found Multiple Warps: ";
for (String match : matches) {
if (playerActivations.get(player.getName()).contains(match)) {
warpOutput += activatedWarpColor + match;
}
else {
warpOutput += deactivatedWarpColor + match;
}
warpOutput += ChatColor.WHITE;
warpOutput += ", ";
}
player.sendMessage(warpOutput);
}
}
else {
player.sendMessage("correct usage is /warp <location>");
}
}
if (commandLabel.equalsIgnoreCase("spawn")){
player.sendMessage("This function is disabled until writable books get an API");
/*World currentWorld = player.getWorld();
if (!(currentWorld == getServer().getWorld("world") || currentWorld == getServer().getWorld("world_nether"))) {
player.sendMessage("You can only warp from the overworld and the nether");
return false;
}
warp(player,"spawn");*/
}
/****************************** REFRESH / RELOAD ******************************\
|
\*****************************************************************************
if (commandLabel.equalsIgnoreCase("refresh")||commandLabel.equalsIgnoreCase("re")) {
Location myLocation = player.getLocation();
Location otherworld = new Location(getServer().getWorld("shopworld"), 0, 64, 0);
player.teleport(otherworld);
player.teleport(myLocation);
}
*/
if (commandLabel.equalsIgnoreCase("fly")) {
ItemStack boots = player.getInventory().getBoots();
String errorMessage = "You are not wearing boots with featherfall";
if (boots == null) {
player.sendMessage(errorMessage);
return false;
}
if (boots.containsEnchantment(Enchantment.PROTECTION_FALL)) {
// durration is the number of minutes the player can fly for
int durration = 5;
// change the durration depending on what type of boots the player is wearing
if (boots.getType() == Material.DIAMOND_BOOTS) { durration = 30;}
else if (boots.getType() == Material.GOLD_BOOTS) { durration = 20;}
else if (boots.getType() == Material.IRON_BOOTS) { durration = 15;}
else if (boots.getType() == Material.LEATHER_BOOTS) { durration = 5;}
// Display
player.sendMessage("You can now fly for the next " + durration + " minutes");
player.setAllowFlight(true);
flightTimeRemaining.put(player.getName(), (durration*6) + 1);
// remove the boots from the game
player.getInventory().setBoots(new ItemStack(Material.AIR,0));
}
else {
player.sendMessage(errorMessage);
}
}
if (commandLabel.equalsIgnoreCase("forcewarp")) {
if (!player.isOp()) {
player.sendMessage("Stop trying to cheat");
return false;
}
if (!regions.isEnabled()) {
player.sendMessage("The regions plugin is not enabled, it must be enabled to forcewarp");
return false;
}
if (args.length != 1) {
player.sendMessage("You need to pick one region to force warp to");
return false;
}
String warpDestination = args[0];
if (!regionsapi.chunkOwners.containsKey(warpDestination)) {
player.sendMessage("Cannot find the plot "+warpDestination);
return false;
}
Location warpLocation = null;
for (Entry<Position, String> testLocation : regionsapi.chunkNames.entrySet()) {
if (testLocation.getValue().equals(warpDestination)) {
Position position = testLocation.getKey();
World world = Bukkit.getServer().getWorld(position._world);
warpLocation = new Location (world,position.getMinimumXCorner(), 257, position.getMinimumZCorner());
}
}
if (warpLocation == null) {
player.sendMessage("Cannot find a valid warp point in " + warpDestination);
return false;
}
player.teleport(warpLocation);
}
return false;
}
| public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
Player player = null;
if (sender instanceof Player) {
player = (Player) sender;
}
/******************************* LIST ALL WARPS *******************************\
| This command lists all of the warps that the server has regestered |
\******************************************************************************/
if (commandLabel.equalsIgnoreCase("warplist")) {
String output = "";
String differentColor = new String();
String defaultColor = new String();
if (player == null) {
differentColor = "\033[0;35m";
defaultColor = "\033[0m";
}
else {
differentColor = deactivatedWarpColor.toString();
defaultColor = ChatColor.WHITE.toString();
}
for (Entry<String, Location> warpPlace : cityTeleports.entrySet()) {
if (player == null) {
output += differentColor + warpPlace.getKey() + defaultColor + ", ";
}
else {
List<String> playerWarps = playerActivations.get(player.getName());
if (playerWarps == null) playerWarps = new ArrayList<String>();
if ( playerWarps.contains(warpPlace.getKey()) ) {
output += activatedWarpColor + warpPlace.getKey() + defaultColor + ", ";
}
else {
output += differentColor + warpPlace.getKey() + defaultColor + ", ";
}
}
}
if (player == null) { info (output); }
else { player.sendMessage(output); }
}
/// past here only players can enter commands ///
if (player == null) {
info("This command can only be run by a player");
return false;
}
/******************************** LIST MY WARPS *******************************\
| This function will list all of the warps that you have activated, but not |
| the ones that you have not activated. |
\******************************************************************************/
if (commandLabel.equalsIgnoreCase("mywarps")) {
List<String> activations = playerActivations.get(player.getName());
if (activations == null) {
player.sendMessage("You have no "+ChatColor.AQUA+"warps" + ChatColor.WHITE);
return false;
}
String warpOutput = "Activated Warps: ";
for (String warpName : activations) {
warpOutput += activatedWarpColor + warpName + ", ";
}
player.sendMessage(warpOutput);
}
/********************************* CREATE WARP ********************************\
|
\******************************************************************************/
if (commandLabel.equalsIgnoreCase("createwarp")){
if (player.isOp() || (player.hasPermission("teleport.createwarp"))){
if (regions != null && regions.isEnabled()) {
ItemStack item = new ItemStack(Material.SIGN);
player.getInventory().addItem(item);
Position p = new Position(player.getLocation());
String name = regionsapi.chunkNames.get(p);
if (name == null) {
player.sendMessage("You cannot create a warp to the wild");
return false;
}
player.sendMessage("Creating a warp for "+name);
tempCityWarpName = name;
tempCityWarpLocation = player.getLocation();
}
else {
player.sendMessage("Create Regions broken, regions not enabled. Contact your server admin");
}
}
else {
player.sendMessage("Ask an admin to create this warp for you");
}
}
/************************************ WARP ************************************\
| The command teleports a player to the location they specified |
\******************************************************************************/
if (commandLabel.equalsIgnoreCase("warp")){
World currentWorld = player.getWorld();
if (!(currentWorld == getServer().getWorld("world") || currentWorld == getServer().getWorld("world_nether"))) {
player.sendMessage("You can only warp from the overworld and the nether");
return false;
}
if ( args.length == 1) {
List<String> matches = findMatch (args[0]);
// if there is only one match: warp there
if (matches.size() == 1) {
String match = matches.get(0);
if (playerActivations.get(player.getName()).contains(match)) {
//attempt to teleport the player
warp(player,match);
} else {
player.sendMessage("You have not activated the "+match+" warp");
}
}
// if there are no matches
else if (matches.size() == 0) {
player.sendMessage("Cannot find the " + deactivatedWarpColor + args[0] + ChatColor.WHITE +" warp");
}
// Otherwise there are many warps
else {
String warpOutput = "Found Multiple Warps: ";
for (String match : matches) {
if (playerActivations.get(player.getName()).contains(match)) {
warpOutput += activatedWarpColor + match;
}
else {
warpOutput += deactivatedWarpColor + match;
}
warpOutput += ChatColor.WHITE;
warpOutput += ", ";
}
player.sendMessage(warpOutput);
}
}
else {
player.sendMessage("correct usage is /warp <location>");
}
}
if (commandLabel.equalsIgnoreCase("spawn")){
player.sendMessage("This function is disabled until writable books get an API");
/*World currentWorld = player.getWorld();
if (!(currentWorld == getServer().getWorld("world") || currentWorld == getServer().getWorld("world_nether"))) {
player.sendMessage("You can only warp from the overworld and the nether");
return false;
}
warp(player,"spawn");*/
}
/****************************** REFRESH / RELOAD ******************************\
|
\*****************************************************************************
if (commandLabel.equalsIgnoreCase("refresh")||commandLabel.equalsIgnoreCase("re")) {
Location myLocation = player.getLocation();
Location otherworld = new Location(getServer().getWorld("shopworld"), 0, 64, 0);
player.teleport(otherworld);
player.teleport(myLocation);
}
*/
if (commandLabel.equalsIgnoreCase("fly")) {
ItemStack boots = player.getInventory().getBoots();
String errorMessage = "You are not wearing boots with featherfall";
if (boots == null) {
player.sendMessage(errorMessage);
return false;
}
if (boots.containsEnchantment(Enchantment.PROTECTION_FALL)) {
// durration is the number of minutes the player can fly for
int durration = 5;
// change the durration depending on what type of boots the player is wearing
if (boots.getType() == Material.DIAMOND_BOOTS) { durration = 30;}
else if (boots.getType() == Material.GOLD_BOOTS) { durration = 20;}
else if (boots.getType() == Material.IRON_BOOTS) { durration = 15;}
else if (boots.getType() == Material.LEATHER_BOOTS) { durration = 5;}
// Display
player.sendMessage("You can now fly for the next " + durration + " minutes");
player.setAllowFlight(true);
flightTimeRemaining.put(player.getName(), (durration*6) + 1);
// remove the boots from the game
player.getInventory().setBoots(new ItemStack(Material.AIR,0));
}
else {
player.sendMessage(errorMessage);
}
}
if (commandLabel.equalsIgnoreCase("forcewarp")) {
if (!player.isOp()) {
player.sendMessage("Stop trying to cheat");
return false;
}
if (!regions.isEnabled()) {
player.sendMessage("The regions plugin is not enabled, it must be enabled to forcewarp");
return false;
}
if (args.length != 1) {
player.sendMessage("You need to pick one region to force warp to");
return false;
}
String warpDestination = args[0];
if (!regionsapi.chunkOwners.containsKey(warpDestination)) {
player.sendMessage("Cannot find the plot "+warpDestination);
return false;
}
Location warpLocation = null;
for (Entry<Position, String> testLocation : regionsapi.chunkNames.entrySet()) {
if (testLocation.getValue().equals(warpDestination)) {
Position position = testLocation.getKey();
World world = Bukkit.getServer().getWorld(position._world);
warpLocation = new Location (world,position.getMinimumXCorner(), 257, position.getMinimumZCorner());
}
}
if (warpLocation == null) {
player.sendMessage("Cannot find a valid warp point in " + warpDestination);
return false;
}
player.teleport(warpLocation);
}
return false;
}
|
diff --git a/jamwiki-core/src/main/java/org/jamwiki/parser/jflex/OnlyIncludeTag.java b/jamwiki-core/src/main/java/org/jamwiki/parser/jflex/OnlyIncludeTag.java
index d26d382e..a002f2ed 100644
--- a/jamwiki-core/src/main/java/org/jamwiki/parser/jflex/OnlyIncludeTag.java
+++ b/jamwiki-core/src/main/java/org/jamwiki/parser/jflex/OnlyIncludeTag.java
@@ -1,48 +1,53 @@
/**
* Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, version 2.1, dated February 1999.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the latest version of the GNU Lesser General
* Public License as published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program (LICENSE.txt); if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package org.jamwiki.parser.jflex;
import org.jamwiki.parser.ParserException;
import org.jamwiki.utils.WikiLogger;
/**
* This class parses nowiki tags of the form <code><onlyinclude>content</onlyinclude></code>.
*/
public class OnlyIncludeTag implements JFlexParserTag {
private static final WikiLogger logger = WikiLogger.getLogger(OnlyIncludeTag.class.getName());
/**
* Parse a call to a Mediawiki onlyinclude tag of the form
* "<onlyinclude>text</onlyinclude>" and return the resulting output.
*/
public String parse(JFlexLexer lexer, String raw, Object... args) throws ParserException {
if (lexer.getMode() <= JFlexParser.MODE_MINIMAL) {
return raw;
}
+ if (lexer.getParserInput().getTemplateDepth() == 0) {
+ // onlyinclude only generates results during transclusion, otherwise the
+ // content is ignored.
+ return "";
+ }
String content = JFlexParserUtil.tagContent(raw);
// run the pre-processor against the onlyinclude content
JFlexParser parser = new JFlexParser(lexer.getParserInput());
String parsed = parser.parseFragment(lexer.getParserOutput(), content, JFlexParser.MODE_TEMPLATE);
// HACK - put the onlyinclude content in a temp param to be used by the
// TemplateTag.parseTemplateBody method. this is necessary because onlyinclude
// supersedes anything that might have been parsed before or after the onlyinclude
// tag.
lexer.getParserInput().getTempParams().put(TemplateTag.TEMPLATE_ONLYINCLUDE, parsed);
return parsed;
}
}
| true | true | public String parse(JFlexLexer lexer, String raw, Object... args) throws ParserException {
if (lexer.getMode() <= JFlexParser.MODE_MINIMAL) {
return raw;
}
String content = JFlexParserUtil.tagContent(raw);
// run the pre-processor against the onlyinclude content
JFlexParser parser = new JFlexParser(lexer.getParserInput());
String parsed = parser.parseFragment(lexer.getParserOutput(), content, JFlexParser.MODE_TEMPLATE);
// HACK - put the onlyinclude content in a temp param to be used by the
// TemplateTag.parseTemplateBody method. this is necessary because onlyinclude
// supersedes anything that might have been parsed before or after the onlyinclude
// tag.
lexer.getParserInput().getTempParams().put(TemplateTag.TEMPLATE_ONLYINCLUDE, parsed);
return parsed;
}
| public String parse(JFlexLexer lexer, String raw, Object... args) throws ParserException {
if (lexer.getMode() <= JFlexParser.MODE_MINIMAL) {
return raw;
}
if (lexer.getParserInput().getTemplateDepth() == 0) {
// onlyinclude only generates results during transclusion, otherwise the
// content is ignored.
return "";
}
String content = JFlexParserUtil.tagContent(raw);
// run the pre-processor against the onlyinclude content
JFlexParser parser = new JFlexParser(lexer.getParserInput());
String parsed = parser.parseFragment(lexer.getParserOutput(), content, JFlexParser.MODE_TEMPLATE);
// HACK - put the onlyinclude content in a temp param to be used by the
// TemplateTag.parseTemplateBody method. this is necessary because onlyinclude
// supersedes anything that might have been parsed before or after the onlyinclude
// tag.
lexer.getParserInput().getTempParams().put(TemplateTag.TEMPLATE_ONLYINCLUDE, parsed);
return parsed;
}
|
diff --git a/src/uk/org/ponder/rsf/renderer/html/BasicHTMLRenderSystem.java b/src/uk/org/ponder/rsf/renderer/html/BasicHTMLRenderSystem.java
index c94001a..ab21b5c 100644
--- a/src/uk/org/ponder/rsf/renderer/html/BasicHTMLRenderSystem.java
+++ b/src/uk/org/ponder/rsf/renderer/html/BasicHTMLRenderSystem.java
@@ -1,183 +1,186 @@
/*
* Created on Jul 27, 2005
*/
package uk.org.ponder.rsf.renderer.html;
import java.util.HashMap;
import java.util.Map;
import uk.org.ponder.rsf.components.UIBasicListMember;
import uk.org.ponder.rsf.components.UIComponent;
import uk.org.ponder.rsf.renderer.ComponentRenderer;
import uk.org.ponder.rsf.renderer.RenderSystem;
import uk.org.ponder.rsf.renderer.RenderSystemContext;
import uk.org.ponder.rsf.renderer.RenderUtil;
import uk.org.ponder.rsf.renderer.TagRenderContext;
import uk.org.ponder.rsf.renderer.decorator.DecoratorManager;
import uk.org.ponder.rsf.renderer.scr.NullRewriteSCR;
import uk.org.ponder.rsf.renderer.scr.StaticComponentRenderer;
import uk.org.ponder.rsf.renderer.scr.StaticRendererCollection;
import uk.org.ponder.rsf.request.FossilizedConverter;
import uk.org.ponder.rsf.request.SubmittedValueEntry;
import uk.org.ponder.rsf.template.XMLLump;
import uk.org.ponder.rsf.template.XMLLumpList;
import uk.org.ponder.util.Constants;
import uk.org.ponder.util.Logger;
import uk.org.ponder.util.UniversalRuntimeException;
/**
* The implementation of the standard XHTML rendering System. This class is due
* for basic refactoring since it contains logic that belongs in a) a "base
* System-independent" lookup bean, and b) in a number of individual
* ComponentRenderer objects.
*
* @author Antranig Basman ([email protected])
*
*/
public class BasicHTMLRenderSystem implements RenderSystem {
private StaticRendererCollection scrc;
private DecoratorManager decoratormanager;
private ComponentRenderer componentRenderer;
public void setComponentRenderer(ComponentRenderer componentRenderer) {
this.componentRenderer = componentRenderer;
}
public void setStaticRenderers(StaticRendererCollection scrc) {
this.scrc = scrc;
}
public void setDecoratorManager(DecoratorManager decoratormanager) {
this.decoratormanager = decoratormanager;
}
// two methods for the RenderSystemDecoder interface
public void normalizeRequestMap(Map requestparams) {
String key = RenderUtil.findCommandParams(requestparams);
if (key != null) {
String params = key.substring(FossilizedConverter.COMMAND_LINK_PARAMETERS
.length());
RenderUtil.unpackCommandLink(params, requestparams);
requestparams.remove(key);
}
}
public void fixupUIType(SubmittedValueEntry sve) {
if (sve.oldvalue instanceof Boolean) {
if (sve.newvalue == null)
sve.newvalue = Boolean.FALSE;
}
else if (sve.oldvalue instanceof String[]) {
if (sve.newvalue == null)
sve.newvalue = new String[] {};
}
else if (sve.oldvalue instanceof String) {
if (sve.newvalue instanceof String
&& Constants.NULL_STRING.equals(sve.newvalue)
|| sve.newvalue instanceof String[]
&& Constants.NULL_STRING.equals(((String[]) sve.newvalue)[0])) {
sve.newvalue = null;
}
}
}
public void renderDebugMessage(RenderSystemContext rsc, String string) {
rsc.pos.print("<span style=\"background-color:#FF466B;color:white;padding:1px;\">");
rsc.xmlw.write(string);
rsc.pos.print("</span><br/>");
}
// This method is almost entirely dialect-invariant - awaiting final
// factorisation of RenderSystem
public int renderComponent(RenderSystemContext rsc, UIComponent torendero, XMLLump lump) {
int lumpindex = lump.lumpindex;
XMLLump[] lumps = lump.parent.lumps;
int nextpos = -1;
XMLLump outerendopen = lump.open_end;
XMLLump outerclose = lump.close_tag;
nextpos = outerclose.lumpindex + 1;
XMLLumpList payloadlist = lump.downmap == null ? null
: lump.downmap.headsForID(XMLLump.PAYLOAD_COMPONENT);
XMLLump payload = payloadlist == null ? null
: payloadlist.lumpAt(0);
// if there is no peer component, it might still be a static resource holder
// that needs URLs rewriting.
// we assume there is no payload component here, since there is no producer
// ID that might govern selection. So we use "outer" indices.
if (torendero == null) {
if (lump.rsfID.startsWith(XMLLump.SCR_PREFIX)) {
String scrname = lump.rsfID.substring(XMLLump.SCR_PREFIX.length());
StaticComponentRenderer scr = scrc.getSCR(scrname);
if (scr == null) {
Logger.log
.info("Warning: unrecognised static component renderer reference with key "
+ scrname + " at lump " + lump.toString());
scr = NullRewriteSCR.instance;
}
int tagtype = RenderUtil.renderSCR(scr, lump, rsc.xmlw, rsc.collecteds);
nextpos = tagtype == ComponentRenderer.LEAF_TAG ? outerclose.lumpindex + 1
: outerendopen.lumpindex + 1;
}
else {
if (rsc.debugrender) {
renderDebugMessage(rsc, "Leaf component missing which was expected with template id " +
lump.rsfID + " at " + lump.toString());
}
}
}
else {
// else there IS a component and we are going to render it. First make
// sure we render any preamble.
XMLLump endopen = outerendopen;
XMLLump close = outerclose;
XMLLump uselump = lump;
if (payload != null) {
endopen = payload.open_end;
close = payload.close_tag;
uselump = payload;
RenderUtil.dumpTillLump(lumps, lumpindex, payload.lumpindex, rsc.pos);
lumpindex = payload.lumpindex;
}
HashMap attrcopy = new HashMap();
attrcopy.putAll(uselump.attributemap);
rsc.IDassigner.adjustForID(attrcopy, torendero);
decoratormanager.decorate(torendero.decorators, uselump.getTag(),
attrcopy);
TagRenderContext rendercontext = new TagRenderContext(attrcopy, uselump,
endopen, close, rsc.pos, rsc.xmlw, nextpos);
// ALWAYS dump the tag name, this can never be rewritten. (probably?!)
rsc.pos.write(uselump.parent.buffer, uselump.start, uselump.length);
if (torendero instanceof UIBasicListMember) {
torendero = RenderUtil.resolveListMember(rsc.view,
(UIBasicListMember) torendero);
}
try {
componentRenderer.renderComponent(torendero, rsc.view, rendercontext);
}
catch (Exception e) {
throw UniversalRuntimeException.accumulate(e,
"Error rendering component " + torendero.getClass()
+ " with full ID " + torendero.getFullID()
+ " at template location " + rendercontext.uselump);
}
// if there is a payload, dump the postamble.
if (payload != null) {
- RenderUtil.dumpTillLump(lumps, close.lumpindex + 1,
+ // the default case is initialised to tag close
+ if (rendercontext.nextpos == nextpos) {
+ RenderUtil.dumpTillLump(lumps, close.lumpindex + 1,
outerclose.lumpindex + 1, rsc.pos);
+ }
}
nextpos = rendercontext.nextpos;
}
return nextpos;
}
}
| false | true | public int renderComponent(RenderSystemContext rsc, UIComponent torendero, XMLLump lump) {
int lumpindex = lump.lumpindex;
XMLLump[] lumps = lump.parent.lumps;
int nextpos = -1;
XMLLump outerendopen = lump.open_end;
XMLLump outerclose = lump.close_tag;
nextpos = outerclose.lumpindex + 1;
XMLLumpList payloadlist = lump.downmap == null ? null
: lump.downmap.headsForID(XMLLump.PAYLOAD_COMPONENT);
XMLLump payload = payloadlist == null ? null
: payloadlist.lumpAt(0);
// if there is no peer component, it might still be a static resource holder
// that needs URLs rewriting.
// we assume there is no payload component here, since there is no producer
// ID that might govern selection. So we use "outer" indices.
if (torendero == null) {
if (lump.rsfID.startsWith(XMLLump.SCR_PREFIX)) {
String scrname = lump.rsfID.substring(XMLLump.SCR_PREFIX.length());
StaticComponentRenderer scr = scrc.getSCR(scrname);
if (scr == null) {
Logger.log
.info("Warning: unrecognised static component renderer reference with key "
+ scrname + " at lump " + lump.toString());
scr = NullRewriteSCR.instance;
}
int tagtype = RenderUtil.renderSCR(scr, lump, rsc.xmlw, rsc.collecteds);
nextpos = tagtype == ComponentRenderer.LEAF_TAG ? outerclose.lumpindex + 1
: outerendopen.lumpindex + 1;
}
else {
if (rsc.debugrender) {
renderDebugMessage(rsc, "Leaf component missing which was expected with template id " +
lump.rsfID + " at " + lump.toString());
}
}
}
else {
// else there IS a component and we are going to render it. First make
// sure we render any preamble.
XMLLump endopen = outerendopen;
XMLLump close = outerclose;
XMLLump uselump = lump;
if (payload != null) {
endopen = payload.open_end;
close = payload.close_tag;
uselump = payload;
RenderUtil.dumpTillLump(lumps, lumpindex, payload.lumpindex, rsc.pos);
lumpindex = payload.lumpindex;
}
HashMap attrcopy = new HashMap();
attrcopy.putAll(uselump.attributemap);
rsc.IDassigner.adjustForID(attrcopy, torendero);
decoratormanager.decorate(torendero.decorators, uselump.getTag(),
attrcopy);
TagRenderContext rendercontext = new TagRenderContext(attrcopy, uselump,
endopen, close, rsc.pos, rsc.xmlw, nextpos);
// ALWAYS dump the tag name, this can never be rewritten. (probably?!)
rsc.pos.write(uselump.parent.buffer, uselump.start, uselump.length);
if (torendero instanceof UIBasicListMember) {
torendero = RenderUtil.resolveListMember(rsc.view,
(UIBasicListMember) torendero);
}
try {
componentRenderer.renderComponent(torendero, rsc.view, rendercontext);
}
catch (Exception e) {
throw UniversalRuntimeException.accumulate(e,
"Error rendering component " + torendero.getClass()
+ " with full ID " + torendero.getFullID()
+ " at template location " + rendercontext.uselump);
}
// if there is a payload, dump the postamble.
if (payload != null) {
RenderUtil.dumpTillLump(lumps, close.lumpindex + 1,
outerclose.lumpindex + 1, rsc.pos);
}
nextpos = rendercontext.nextpos;
}
return nextpos;
}
| public int renderComponent(RenderSystemContext rsc, UIComponent torendero, XMLLump lump) {
int lumpindex = lump.lumpindex;
XMLLump[] lumps = lump.parent.lumps;
int nextpos = -1;
XMLLump outerendopen = lump.open_end;
XMLLump outerclose = lump.close_tag;
nextpos = outerclose.lumpindex + 1;
XMLLumpList payloadlist = lump.downmap == null ? null
: lump.downmap.headsForID(XMLLump.PAYLOAD_COMPONENT);
XMLLump payload = payloadlist == null ? null
: payloadlist.lumpAt(0);
// if there is no peer component, it might still be a static resource holder
// that needs URLs rewriting.
// we assume there is no payload component here, since there is no producer
// ID that might govern selection. So we use "outer" indices.
if (torendero == null) {
if (lump.rsfID.startsWith(XMLLump.SCR_PREFIX)) {
String scrname = lump.rsfID.substring(XMLLump.SCR_PREFIX.length());
StaticComponentRenderer scr = scrc.getSCR(scrname);
if (scr == null) {
Logger.log
.info("Warning: unrecognised static component renderer reference with key "
+ scrname + " at lump " + lump.toString());
scr = NullRewriteSCR.instance;
}
int tagtype = RenderUtil.renderSCR(scr, lump, rsc.xmlw, rsc.collecteds);
nextpos = tagtype == ComponentRenderer.LEAF_TAG ? outerclose.lumpindex + 1
: outerendopen.lumpindex + 1;
}
else {
if (rsc.debugrender) {
renderDebugMessage(rsc, "Leaf component missing which was expected with template id " +
lump.rsfID + " at " + lump.toString());
}
}
}
else {
// else there IS a component and we are going to render it. First make
// sure we render any preamble.
XMLLump endopen = outerendopen;
XMLLump close = outerclose;
XMLLump uselump = lump;
if (payload != null) {
endopen = payload.open_end;
close = payload.close_tag;
uselump = payload;
RenderUtil.dumpTillLump(lumps, lumpindex, payload.lumpindex, rsc.pos);
lumpindex = payload.lumpindex;
}
HashMap attrcopy = new HashMap();
attrcopy.putAll(uselump.attributemap);
rsc.IDassigner.adjustForID(attrcopy, torendero);
decoratormanager.decorate(torendero.decorators, uselump.getTag(),
attrcopy);
TagRenderContext rendercontext = new TagRenderContext(attrcopy, uselump,
endopen, close, rsc.pos, rsc.xmlw, nextpos);
// ALWAYS dump the tag name, this can never be rewritten. (probably?!)
rsc.pos.write(uselump.parent.buffer, uselump.start, uselump.length);
if (torendero instanceof UIBasicListMember) {
torendero = RenderUtil.resolveListMember(rsc.view,
(UIBasicListMember) torendero);
}
try {
componentRenderer.renderComponent(torendero, rsc.view, rendercontext);
}
catch (Exception e) {
throw UniversalRuntimeException.accumulate(e,
"Error rendering component " + torendero.getClass()
+ " with full ID " + torendero.getFullID()
+ " at template location " + rendercontext.uselump);
}
// if there is a payload, dump the postamble.
if (payload != null) {
// the default case is initialised to tag close
if (rendercontext.nextpos == nextpos) {
RenderUtil.dumpTillLump(lumps, close.lumpindex + 1,
outerclose.lumpindex + 1, rsc.pos);
}
}
nextpos = rendercontext.nextpos;
}
return nextpos;
}
|
diff --git a/realms/konakart-yanel-realm/res-types/overview/src/java/org/wyona/yanel/resources/konakart/overview/KonakartOverviewSOAPInfResource.java b/realms/konakart-yanel-realm/res-types/overview/src/java/org/wyona/yanel/resources/konakart/overview/KonakartOverviewSOAPInfResource.java
index 5a6689c..83a58b9 100644
--- a/realms/konakart-yanel-realm/res-types/overview/src/java/org/wyona/yanel/resources/konakart/overview/KonakartOverviewSOAPInfResource.java
+++ b/realms/konakart-yanel-realm/res-types/overview/src/java/org/wyona/yanel/resources/konakart/overview/KonakartOverviewSOAPInfResource.java
@@ -1,960 +1,960 @@
/*
* Copyright 2010 Wyona
*/
package org.wyona.yanel.resources.konakart.overview;
import org.wyona.yanel.core.api.attributes.AnnotatableV1;
import org.wyona.yanel.core.api.attributes.TrackableV1;
import org.wyona.yanel.core.attributes.tracking.TrackingInformationV1;
import org.wyona.yanel.impl.resources.BasicXMLResource;
import org.wyona.yanel.resources.konakart.shared.SharedResource;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import org.apache.log4j.Logger;
import com.konakart.appif.KKEngIf;
import com.konakart.appif.CustomerIf;
import com.konakart.appif.AddressIf;
import com.konakart.appif.BasketIf;
import com.konakart.appif.OrderIf;
import com.konakart.appif.OrderTotalIf;
import com.konakart.appif.ShippingQuoteIf;
import com.konakart.appif.OrderStatusHistoryIf;
import com.konakart.appif.OrderProductIf;
import com.konakart.appif.OrderTotalIf;
import com.konakart.app.OrderStatusHistory;
import com.konakart.app.OrderTotal;
import org.w3c.dom.Element;
import org.wyona.yanel.core.attributes.viewable.View;
import javax.servlet.http.HttpServletResponse;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.Arrays;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.math.BigDecimal;
import java.net.URLDecoder;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
import org.xml.sax.SAXException;
import org.xml.sax.InputSource;
/**
* Show overview before buying products and also the actual order process
*/
public class KonakartOverviewSOAPInfResource extends BasicXMLResource implements AnnotatableV1, TrackableV1 {
private static Logger log = Logger.getLogger(KonakartOverviewSOAPInfResource.class);
private static String KONAKART_NAMESPACE = "http://www.konakart.com/1.0";
private BranchListHandler handler; // Info: For parsing branches xml file.
private TrackingInformationV1 trackInfo;
/**
* @see org.wyona.yanel.impl.resources.BasicXMLResource#getContentXML(String)
*/
@Override
protected InputStream getContentXML(String viewId) throws Exception {
if (log.isDebugEnabled()) {
log.debug("requested viewId: " + viewId);
}
if (trackInfo != null) {
String[] annotations = getAnnotations();
if (annotations != null) {
for (int i = 0; i < annotations.length; i++) {
trackInfo.addTag(annotations[i]);
}
} else {
log.error("No annotations!");
}
trackInfo.setPageType("konakart-order-overview");
} else {
log.warn("Tracking information bean is null! Check life cycle of resource!");
}
SharedResource shared = new SharedResource();
KKEngIf kkEngine = shared.getKonakartEngineImpl();
KKEngIf kkEngineBranch = null; // Will be initialized later (if in multi-store mode)
//boolean multistore = false; // Will have to be checked after reading delivery address
String sessionId = shared.getSessionId(getEnvironment().getRequest().getSession(true));
int customerId = shared.getCustomerId(getEnvironment().getRequest().getSession(true));
int languageId = shared.getLanguageId(getContentLanguage());
OrderIf orderDefault = null; // Order object which will be filled with totals
// Build document
org.w3c.dom.Document doc = null;
try {
doc = org.wyona.commons.xml.XMLHelper.createDocument(KONAKART_NAMESPACE, "overview");
} catch (Exception e) {
throw new Exception(e.getMessage(), e);
}
// Root element
Element rootElement = doc.getDocumentElement();
// We'll need these later
BasketIf[] items = null;
ShippingQuoteIf shipping = null;
// Get customer
CustomerIf customer = shared.getCustomer(sessionId, customerId);
if(customer == null) {
Element exception = (Element) rootElement.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "not-logged-in-yet"));
java.io.ByteArrayOutputStream baout = new java.io.ByteArrayOutputStream();
org.wyona.commons.xml.XMLHelper.writeDocument(doc, baout);
return new java.io.ByteArrayInputStream(baout.toByteArray());
}
Element mailElem = (Element) rootElement.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "email"));
mailElem.appendChild(doc.createTextNode("" + customer.getEmailAddr()));
// Get payment (=default) address
AddressIf defaddr = kkEngine.getDefaultAddressPerCustomer(sessionId);
if(defaddr == null) {
// Well, there's no default address - just make the first address
// we have in the database the default address from now on (if there's
// no default address this is most likely a newly registered user).
AddressIf[] addrs = customer.getAddresses();
// There has to be at least one address, Konakart doesn't let you register otherwise.
defaddr = addrs[0];
kkEngine.setDefaultAddressPerCustomer(sessionId, defaddr.getId());
}
// Now print that address information
Element defAddrElem = (Element) rootElement.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "payment-address"));
Element defAddrNameElem = (Element) defAddrElem.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "last-name"));
defAddrNameElem.appendChild(doc.createTextNode("" + defaddr.getLastName()));
Element defAddrfNameElem = (Element) defAddrElem.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "first-name"));
defAddrfNameElem.appendChild(doc.createTextNode("" + defaddr.getFirstName()));
Element defAddrCompanyElem = (Element) defAddrElem.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "company"));
defAddrCompanyElem.appendChild(doc.createTextNode("" + defaddr.getCompany()));
Element defAddrCityElem = (Element) defAddrElem.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "city"));
defAddrCityElem.appendChild(doc.createTextNode("" + defaddr.getCity()));
Element defAddrCountryElem = (Element) defAddrElem.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "country"));
defAddrCountryElem.appendChild(doc.createTextNode("" + defaddr.getCountryName()));
Element defAddrStreetElem = (Element) defAddrElem.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "street"));
defAddrStreetElem.appendChild(doc.createTextNode("" + defaddr.getStreetAddress()));
Element defAddrGenderElem = (Element) defAddrElem.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "gender"));
defAddrGenderElem.appendChild(doc.createTextNode("" + defaddr.getGender()));
Element defAddrPostcodeElem = (Element) defAddrElem.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "postcode"));
defAddrPostcodeElem.appendChild(doc.createTextNode("" + defaddr.getPostcode()));
Element defAddrPhoneElem = (Element) defAddrElem.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "telephone"));
defAddrPhoneElem.appendChild(doc.createTextNode("" + customer.getTelephoneNumber()));
// Get delivery (=default) address
AddressIf[] addrs = kkEngine.getAddressesPerCustomer(sessionId);
int devaddrid = Integer.parseInt(customer.getCustom1());
AddressIf devaddr = null;
for(AddressIf a : addrs) {
if(a.getId() == devaddrid) {
devaddr = a;
}
}
if(devaddr == null) devaddr = defaddr;
// Now print that address information
Element devaddrElem = (Element) rootElement.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "delivery-address"));
Element devaddrNameElem = (Element) devaddrElem.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "last-name"));
devaddrNameElem.appendChild(doc.createTextNode("" + devaddr.getLastName()));
Element devaddrfNameElem = (Element) devaddrElem.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "first-name"));
devaddrfNameElem.appendChild(doc.createTextNode("" + devaddr.getFirstName()));
Element devaddrCompanyElem = (Element) devaddrElem.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "company"));
devaddrCompanyElem.appendChild(doc.createTextNode("" + devaddr.getCompany()));
Element devaddrCityElem = (Element) devaddrElem.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "city"));
devaddrCityElem.appendChild(doc.createTextNode("" + devaddr.getCity()));
Element devaddrCountryElem = (Element) devaddrElem.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "country"));
devaddrCountryElem.appendChild(doc.createTextNode("" + devaddr.getCountryName()));
Element devaddrStreetElem = (Element) devaddrElem.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "street"));
devaddrStreetElem.appendChild(doc.createTextNode("" + devaddr.getStreetAddress()));
Element devaddrGenderElem = (Element) devaddrElem.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "gender"));
devaddrGenderElem.appendChild(doc.createTextNode("" + devaddr.getGender()));
Element devaddrPostcodeElem = (Element) devaddrElem.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "postcode"));
devaddrPostcodeElem.appendChild(doc.createTextNode("" + devaddr.getPostcode()));
String remarks = (String) getEnvironment().getRequest().getSession(true).getAttribute("checkout-data-remarks");
if(remarks != null) appendField("remarks", remarks, rootElement, doc);
boolean process = getEnvironment().getRequest().getParameter("process") != null;
String confirmParam = getEnvironment().getRequest().getParameter("confirm");
boolean confirmGeneralTermsConditions = false;
if (confirmParam != null) {
log.warn("DEBUG: Confirm general terms and conditions: " + confirmParam);
confirmGeneralTermsConditions = true;
}
if(process && !confirmGeneralTermsConditions) {
log.warn("General terms and conditions have not been accepted, hence do not process order...");
process = false;
Element perrElem = (Element) rootElement.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "terms-not-accepted-yet"));
perrElem.appendChild(doc.createTextNode("General terms and conditions have not been accepted!"));
}
if(process) { // INFO: Check whether order should be processed ...
// If process is true, we're creating and submitting this order
// at the same time as we are displaying the information. So first,
// we need the items in the basket to create an order object.
try {
int tmpCustomerId = shared.getTemporaryCustomerId(getEnvironment().getRequest().getSession(true));
items = kkEngine.getBasketItemsPerCustomer(null, tmpCustomerId, languageId);
// Create orders
log.warn("DEBUG: Create default order ...");
orderDefault = kkEngine.createOrder(sessionId, items, languageId);
//OrderIf orderDefault = kkEngine.createOrder(sessionId, items, languageId);
shipping = shared.getShippingCost(items, sessionId, languageId, getEnvironment().getRequest().getSession(true));
orderDefault.setShippingQuote(shipping);
orderDefault = kkEngine.getOrderTotals(orderDefault, languageId);
fixOrderTotals(orderDefault, shipping);
setOrderAddressFields(orderDefault, shipping, devaddr, defaddr);
// Status trail
OrderStatusHistoryIf[] trail = new OrderStatusHistoryIf[1];
trail[0] = new OrderStatusHistory();
trail[0].setOrderStatus("New order.");
trail[0].setCustomerNotified(true);
orderDefault.setStatusTrail(trail);
} catch(Exception e) {
process = false;
log.error(e, e);
Element perrElem = (Element) rootElement.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "process-error"));
if(e.getMessage() != null) perrElem.appendChild(doc.createTextNode(e.getMessage()));
}
if (trackInfo != null) {
trackInfo.setRequestAction("order-processed");
} else {
log.warn("Tracking information bean is null! Check life cycle of resource!");
}
} else {
log.warn("DEBUG: Order either not submitted or processed yet. Continue ...");
if (trackInfo != null) {
trackInfo.setRequestAction("review-order");
} else {
log.warn("Tracking information bean is null! Check life cycle of resource!");
}
}
// Payment info
javax.servlet.http.HttpSession session = getEnvironment().getRequest().getSession(true);
String type = (String) session.getAttribute("checkout-card-data-type");
String payment_info_kk = null;
String payment_info_mail = null;
if("Pluscard".equals(type)) {
// Pluscard
Element pc = (Element) rootElement.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "payment-method-pluscard"));
Element numberElem = (Element) pc.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "number"));
String number = (String) session.getAttribute("checkout-card-data-number");
number = number.replace("[^0-9]+", "");
String num_prefix, num_suffix;
String suffix = number.substring(number.length()-4);
num_suffix = "..." + suffix;
num_prefix = number.substring(0, number.length()-4) + "****";
try {
// It's +7 because pluscards have a 7 digit prefix
char[] asterisks = new char[number.length()-4+7];
Arrays.fill(asterisks, '*');
String asterisks_str = new String(asterisks);
numberElem.appendChild(doc.createTextNode(asterisks_str + suffix));
} catch(Exception e) { }
String name = (String) session.getAttribute("checkout-card-data-name");
Element nameElem = (Element) pc.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "name"));
nameElem.appendChild(doc.createTextNode(name));
String valid = (String) session.getAttribute("checkout-card-data-valid");
Element validElem = (Element) pc.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "valid"));
validElem.appendChild(doc.createTextNode(valid));
if(process) {
try {
orderDefault.setPaymentMethod("Pluscard");
payment_info_kk = num_suffix + " (" + valid + ")";
payment_info_mail = "6004512-" + num_prefix;
} catch(Exception e) {
process = false;
log.error(e, e);
Element perrElem = (Element) rootElement.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "process-error"));
if(e.getMessage() != null) perrElem.appendChild(doc.createTextNode(e.getMessage()));
}
}
} else {
// Credit card
Element cc = (Element) rootElement.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "payment-method-creditcard"));
Element numberElem = (Element) cc.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "number"));
String number = (String) session.getAttribute("checkout-card-data-number");
number = number.replace("[^0-9]+", "");
String num_prefix, num_suffix, suffix;
suffix = number.substring(number.length()-4);
num_suffix = "..." + suffix;
num_prefix = number.substring(0, number.length()-4) + "****";
try {
char[] asterisks = new char[number.length()-4];
Arrays.fill(asterisks, '*');
String asterisks_str = new String(asterisks);
numberElem.appendChild(doc.createTextNode(asterisks_str + suffix));
} catch(Exception e) { }
String name = (String) session.getAttribute("checkout-card-data-name");
Element nameElem = (Element) cc.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "name"));
nameElem.appendChild(doc.createTextNode(name));
String valid = (String) session.getAttribute("checkout-card-data-valid");
Element validElem = (Element) cc.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "valid"));
validElem.appendChild(doc.createTextNode(valid));
Element typeElem = (Element) cc.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "type"));
typeElem.appendChild(doc.createTextNode(type));
if(process) {
try {
orderDefault.setPaymentMethod("Creditcard");
String snum = number.replace("[^0-9]+", "");
payment_info_kk = type + ": " + num_suffix + " (" + valid + ")";
String cvc = (String) session.getAttribute("checkout-card-data-cvc");
payment_info_mail = type + ": " + num_prefix + "/" + cvc;
} catch(Exception e) {
process = false;
log.error(e, e);
Element perrElem = (Element) rootElement.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "process-error"));
if(e.getMessage() != null) perrElem.appendChild(doc.createTextNode(e.getMessage()));
}
}
String globusCardNumber = (String) session.getAttribute("checkout-globuscard-number");
if (globusCardNumber != null) {
- Element globusCardNumberElem = (Element) cc.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "globucard-number"));
+ Element globusCardNumberElem = (Element) cc.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "globuscard-number"));
globusCardNumberElem.appendChild(doc.createTextNode(globusCardNumber));
}
}
if(process) {
try {
int orderId = kkEngine.saveOrder(sessionId, orderDefault, languageId);
// Status updates
// TODO: Needs to be "moved" to branch store if multistore is true
kkEngine.changeOrderStatus(sessionId, orderId, orderDefault.getStatus(), true, "New order.");
if(remarks != null) {
try {
kkEngine.changeOrderStatus(sessionId, orderId, orderDefault.getStatus(), true, "Remarks: " + remarks);
} catch(Exception e) {
log.error(e, e);
}
}
if(payment_info_kk != null) {
kkEngine.changeOrderStatus(sessionId, orderId, orderDefault.getStatus(), false, "Payment details: " + payment_info_kk);
}
// INFO: Check whether ZIP corresponds to a specific store id and hence enable Multi-Store
String storeId = getBranchStoreId(devaddr.getPostcode());
boolean multistore = storeId != null;
if(multistore) {
log.warn("DEBUG: Multi-store seems to be enabled: " + devaddr.getPostcode() + ", " + storeId);
kkEngineBranch = shared.getKonakartEngineImpl(storeId);
} else {
log.warn("DEBUG: Multi-store seems to be disabled.");
}
if(multistore) {
OrderIf orderBranch = null; // INFO: Branch order object for multi-store mode
log.warn("DEBUG: Trying to create branch order ...");
log.warn("DEBUG: Realm: " + getRealm().getName() + ", " + getRealm().getConfigFile());
log.warn("DEBUG: Konakart repository: " + getRealm().getRepository("konakart-repository").getConfigFile());
org.wyona.yarep.core.Repository konakartRepo = getRealm().getRepository("konakart-repository");
org.wyona.yarep.core.Node ordersNode = konakartRepo.getNode("/orders/");
String language = "en"; // TODO: Not used actually (see implementation ...)
//String orderId = "" + orderDefault.getId();
//String orderId = orderDefault.getOrderNumber();
if (ordersNode.hasNode(orderId + "_" + language)) {
org.wyona.yarep.core.Node orderNode = ordersNode.getNode(orderId + "_" + language);
log.warn("DEBUG: Switch store ID '" + storeId + "' of order: " + orderId);
orderNode.setProperty("store-id", storeId);
} else {
log.error("No such order with ID: " + orderId);
}
// TODO: Add products to this store and append to category
for (OrderProductIf orderProduct : orderDefault.getOrderProducts()) {
com.konakart.appif.ProductIf productDefault = orderProduct.getProduct();
// INFO: Please note that the ID of an order-product is not the same as the ID of an actual product
log.warn("DEBUG: Order product ID: " + orderProduct.getId() + ", Product ID: " + productDefault.getId());
log.warn("DEBUG: Category ID of product: " + productDefault.getCategoryId());
/*
int language = 2;
com.konakart.appif.CategoryIf[] categories = kkEngine.getCategoriesPerProduct(productDefault.getId(), language);
*/
for (String shopId : kkEngine.getStoreIds()) {
log.warn("DEBUG: Store ID: " + shopId);
}
/*
AdminStore[] = KKAdminIf.getStores();
AdminStore = ...
AdminProducts = kkAdminIf.searchForProducts(...);
AdminProduct = ...
//kkEngineBranch
*/
}
/*
orderBranch = kkEngineBranch.createOrder(sessionId, items, languageId);
if (orderBranch != null) {
orderBranch.setShippingQuote(shipping);
// TODO: Something goes wrong here ...
orderBranch = kkEngineBranch.getOrderTotals(orderBranch, languageId);
fixOrderTotals(orderBranch, shipping);
setOrderAddressFields(orderBranch, shipping, devaddr, defaddr);
orderBranch.setStatusTrail(trail); // TODO: Add a branch specific trail
orderBranch.setPaymentMethod("Pluscard");
int idBranch = kkEngineBranch.saveOrder(sessionId, orderBranch, languageId);
log.warn("DEBUG: Branch order has been created: " + kkEngineBranch.getStore().getStoreId());
// TODO: ...
//kkEngine.changeOrderStatus(sessionId, idBranch, orderBranch.getStatus(), true, "New order.");
//kkEngine.changeOrderStatus(sessionId, idBranch, orderBranch.getStatus(), false, "Payment details: " + payment_info_kk);
} else {
log.error("Was not able to create order to branch store: " + storeId);
}
*/
} // INFO: End multistore
Element prElem = (Element) rootElement.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "process"));
prElem.setAttribute("orderid", "" + orderId);
// Print date
Date today = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy HH:mm");
String formattedDate = formatter.format(today);
Element dateElem = (Element) rootElement.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "date"));
dateElem.appendChild(doc.createTextNode(formattedDate));
sendMailToCustomer(orderId, orderDefault, customer);
sendMailToOwner(orderId, orderDefault, customer, payment_info_mail);
// Let Konakart send the order confirmation...
// kkEngineBranch.sendOrderConfirmationEmail(sessionId, id, "Order #" + id, languageId);
} catch(Exception e) {
process = false;
log.error(e, e);
Element perrElem = (Element) rootElement.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "process-error"));
if(e.getMessage() != null) perrElem.appendChild(doc.createTextNode(e.getMessage()));
}
}
// Output
java.io.ByteArrayOutputStream baout = new java.io.ByteArrayOutputStream();
org.wyona.commons.xml.XMLHelper.writeDocument(doc, baout);
return new java.io.ByteArrayInputStream(baout.toByteArray());
}
/**
* Generate mail body/content.
*/
private void getMailContent(StringBuilder content, int id, OrderIf order, CustomerIf customer) {
// Order info
// Note: I would have liked to use order.getDatePurchased here,
// but it always gives me a null pointer exception...
// And yes, I know, embedded HTML is scary :-(
SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy HH:mm");
Date today = new Date();
String formattedDate = formatter.format(today);
content.append("<br/><br/><strong>Bestellung vom / Commande du: " + formattedDate);
content.append("</strong><br/>Bestellung Nr. / Commande n°: " + id);
content.append("<br/><br/><hr/><br/><table>");
// Items
OrderProductIf[] items = order.getOrderProducts();
for(OrderProductIf item : items) {
String quantity = Integer.toString(item.getQuantity());
String name = item.getName();
String total_price = item.getFinalPriceExTax().setScale(2, BigDecimal.ROUND_HALF_EVEN).toString();
String single_price = item.getPrice().setScale(2, BigDecimal.ROUND_HALF_EVEN).toString();
content.append("<tr><td style=\"text-align:right;width:1%;\">");
content.append(quantity);
content.append("</td><td>");
content.append(name + " (à " + single_price + ")");
content.append("</td><td style=\"text-align:right;\">");
content.append(total_price);
content.append("</td></tr>");
}
// Totals
String subtotal = order.getSubTotalExTax().setScale(2, BigDecimal.ROUND_HALF_EVEN).toString();
content.append("<tr><td colspan=\"2\">Warenwert / Valeur:</td>");
content.append("<td style=\"text-align:right;\">");
content.append(subtotal);
content.append("</td></tr>");
String shw = order.getCustom1();
if(!"".equals(shw)) {
content.append("<tr><td colspan=\"2\">Lieferkosten Wein / Frais de port vins:</td>");
content.append("<td style=\"text-align:right;\">");
content.append(shw);
content.append("</td></tr>");
}
String shg = order.getCustom2();
if(!"".equals(shg)) {
content.append("<tr><td colspan=\"2\">Lieferkosten Geschenk / Frais de port cadeaux:</td>");
content.append("<td style=\"text-align:right;\">");
content.append(shg);
content.append("</td></tr>");
}
String rew = order.getCustom3();
if(!"0.00".equals(rew)) {
content.append("<tr><td colspan=\"2\">Mengenrabatt Wein / Rabais de quantité vins:</td>");
content.append("<td style=\"text-align:right;\">");
content.append(rew);
content.append("</td></tr>");
}
String total = order.getTotalExTax().setScale(2, BigDecimal.ROUND_HALF_EVEN).toString();
content.append("<tr><td colspan=\"2\" style=\"font-weight:bold;\">Total CHF (inkl. MwSt. / TVA incl.):</td>");
content.append("<td style=\"text-align:right;font-weight:bold;\">");
content.append(total);
content.append("</td></tr>");
content.append("</table>");
// Payment info
String lang;
try {
lang = getContentLanguage();
} catch(Exception e) {
lang = "de";
}
javax.servlet.http.HttpSession session = getEnvironment().getRequest().getSession(true);
if (session.getAttribute("coupon") != null) {
content.append("<br/><br/>Gutschein: Sie bezahlen keine Lieferkosten auf dieser Bestellung / Bon: les frais de livraison vous sont offerts pour cette commande<br/>");
}
content.append("<br/><br/><strong>Rechnungsadresse / Adresse de facturation</strong><br/>");
if(lang.equals("fr")) {
if(customer.getGender().equals("f")) {
content.append("Madame");
} else {
content.append("Monsieur");
}
} else {
if(customer.getGender().equals("f")) {
content.append("Frau");
} else {
content.append("Herr");
}
}
content.append("<br/>" + order.getBillingName());
String company = order.getBillingCompany();
if(company != null && company.length() > 0) {
content.append("<br/>" + company);
}
content.append("<br/>" + order.getBillingStreetAddress());
content.append("<br/>" + order.getBillingPostcode() + " " + order.getBillingCity());
content.append("<br/>" + customer.getTelephoneNumber());
content.append("<br/><a href=\"mailto:" + customer.getEmailAddr() + "\">" + customer.getEmailAddr() + "</a>");
// Delivery info
content.append("<br/><br/><strong>Lieferadresse / Adresse de livraison</strong>");
content.append("<br/>" + order.getDeliveryName());
company = order.getDeliveryCompany();
if(company != null && company.length() > 0) {
content.append("<br/>" + company);
}
content.append("<br/>" + order.getDeliveryStreetAddress());
content.append("<br/>" + order.getDeliveryPostcode() + " " + order.getDeliveryCity());
// Remarks
String remarks = (String) getEnvironment().getRequest().getSession(true).getAttribute("checkout-data-remarks");
if(remarks != null) {
content.append("<br/><br/><strong>Grusstext, Mitteilung an Globus / Texte de salutation, message à Globus</strong><br/>");
content.append(remarks);
}
}
/**
* Fix order totals.
*/
public void fixOrderTotals(OrderIf order, ShippingQuoteIf shipping) {
// Then we need to edit the OrderTotal objects, those
// are used in the "detailed" view, to show e.g. shipping and such
OrderTotalIf[] totals = order.getOrderTotals();
for(OrderTotalIf t : totals) {
if(t.getClassName().equals("ot_total")) {
// If it's the total, edit it...
// Not only do we need to change the value,
// we also have to change the text that is displayed
// manually ourselves because if we don't the value
// will be correct in the database but Konakart will
// display something diffrent!
t.setValue(t.getValue().add(shipping.getTotalIncTax()));
t.setText("<b>CHF" + t.getValue().setScale(2, BigDecimal.ROUND_HALF_EVEN) + "</b>");
}
}
// And now we add a OrderTotal object for our "Mengenrabatt",
// otherwise Konakart will completely ignore it which sucks.
OrderTotalIf[] custom_totals = new OrderTotal[totals.length+1];
System.arraycopy(totals, 0, custom_totals, 0, totals.length);
// Yes, all those fields are necessary
// TODO: Make this more generic than it currently is.
custom_totals[totals.length] = new OrderTotal();
custom_totals[totals.length].setTitle("Mengenrabatt Wein");
custom_totals[totals.length].setValue(shipping.getTotalIncTax());
custom_totals[totals.length].setText("-CHF" + shipping.getTotalIncTax().multiply(new BigDecimal("-1")).setScale(2, BigDecimal.ROUND_HALF_EVEN).toString());
custom_totals[totals.length].setClassName("ot_custom");
custom_totals[totals.length].setOrderId(order.getId());
custom_totals[totals.length].setSortOrder(3);
// And finally...
order.setOrderTotals(custom_totals);
}
/**
* Set custom fields, addrs.
*/
public void setOrderAddressFields(OrderIf order, ShippingQuoteIf shipping, AddressIf devaddr, AddressIf defaddr) {
// Add custom discount to order object
// This is a bit difficult because of Konakart...
// Here, we edit the totalIncTax/totalExTax fields, those
// are used for displaying the order total in e.g. a overview
order.setTotalExTax(order.getTotalExTax().add(shipping.getTotalIncTax()));
order.setTotalIncTax(order.getTotalExTax().add(shipping.getTotalIncTax()));
// Store cost in custom fields for use later on
order.setCustom1(shipping.getCustom1());
order.setCustom2(shipping.getCustom2());
order.setCustom3(shipping.getCustom3());
// Adresses
order.setCustomerAddrId(defaddr.getId());
order.setBillingAddrId(defaddr.getId());
order.setDeliveryAddrId(devaddr.getId());
order.setDeliveryCity(devaddr.getCity());
order.setDeliveryName(devaddr.getFirstName() + " " + devaddr.getLastName());
order.setDeliveryCountry(devaddr.getCountryName());
order.setDeliveryStreetAddress(devaddr.getStreetAddress());
order.setDeliveryPostcode(devaddr.getPostcode());
if(devaddr.getCompany() != null) order.setDeliveryCompany(devaddr.getCompany());
}
/**
* Send mail.
*/
public void sendMail(String sender, String recipient, String subject, String content) {
log.warn("DEBUG: Send e-mail to: " + recipient);
try {
// TODO: sender is also used as reply-to
// INFO: Use smtp host and port from Yanel global configuration
org.wyona.yanel.core.util.MailUtil.send(null, -1, sender, sender, recipient, subject, content, "utf-8", "html");
} catch(Exception e) {
log.error(e, e);
}
}
/**
* Send email to customer.
*/
public void sendMailToCustomer(int id, OrderIf order, CustomerIf customer) {
// Content
StringBuilder content = new StringBuilder();
String lang;
try {
lang = getContentLanguage();
} catch(Exception e) {
lang = "de";
}
// Salutation
if(lang.equals("fr")) {
if(customer.getGender().equals("f")) {
content.append("Madame, ");
} else {
content.append("Monsieur, ");
}
} else {
if(customer.getGender().equals("f")) {
content.append("Sehr geehrte Frau ");
} else {
content.append("Sehr geehrter Herr ");
}
content.append(customer.getLastName());
}
try {
String header = getResourceConfigProperty("header");
if(header != null) content.append(URLDecoder.decode(header));
} catch(Exception e) { /* If there's no header defined, we don't do anything */ }
// Bulk content
getMailContent(content, id, order, customer);
// Payment
content.append("<br/><br/><b>Zahlungsart / Mode de paiement</b><br/>");
javax.servlet.http.HttpSession session = getEnvironment().getRequest().getSession(true);
String type = (String) session.getAttribute("checkout-card-data-type");
if("Pluscard".equals(type)) {
content.append("Pluscard");
} else {
content.append("Kreditkarte / Carte de crédit");
}
content.append("<br/><br/>");
try {
String footer = getResourceConfigProperty("footer");
if(footer != null) content.append(URLDecoder.decode(footer));
} catch(Exception e) { /* If there's no footer defined, we don't do anything */ }
// Send
try {
String recipient = customer.getEmailAddr();
String sender = getResourceConfigProperty("email-from");
String subject = getResourceConfigProperty("email-subject") + id;
sendMail(sender, recipient, subject, content.toString());
} catch(Exception e) {
log.error(e, e);
}
}
/**
* Send email to shop owner and general administrator.
*/
public void sendMailToOwner(int id, OrderIf order, CustomerIf customer, String payment) {
// Content
StringBuilder content = new StringBuilder();
content.append("Eine neue Bestellung ist eingetroffen.");
content.append("<br/>Vous avez reçu une nouvelle commande.");
try {
String adminurl = getResourceConfigProperty("admin-url");
if(adminurl != null) {
content.append("<br/><br/>Details und Status ändern / Details et changer le status:<br/>");
content.append("<a href=\"" + adminurl + "\">" + adminurl + "</a>");
}
} catch(Exception e) { /* If there's no admin-url defined, we don't do anything */ }
getMailContent(content, id, order, customer);
// Payment details
javax.servlet.http.HttpSession session = getEnvironment().getRequest().getSession(true);
String name = (String) session.getAttribute("checkout-card-data-name");
content.append("<br/><br/><b>Zahlungsart / Mode de paiement</b><br/>");
content.append(order.getPaymentMethod());
content.append("<br/>" + name);
content.append("<br/>" + payment);
content.append("<br/><br/><hr/><br/>");
// Time to send that email now
// Settings
try {
String recipient = getResourceConfigProperty("email-to");
String sender = getResourceConfigProperty("email-from");
String subject = getResourceConfigProperty("email-subject") + id;
String branchTo = getBranchEmail(order.getDeliveryPostcode());
String sendbranch = getResourceConfigProperty("send-branch-emails");
content.append("Filiale: " + branchTo + "<br/>");
if(branchTo != null) {
if("true".equals(sendbranch)) {
// Send mail to branch
sendMail(sender, branchTo, subject, content.toString());
}
}
// Send mail to owner
sendMail(sender, recipient, subject, content.toString());
} catch(Exception e) {
log.error(e, e);
}
}
/**
* Get branch email which corresponds to ZIP code of customer.
* @param zipcode ZIP code of customer
*/
public String getBranchEmail(String zipcode) throws Exception {
String branchlist = getResourceConfigProperty("email-branches");
if(branchlist != null) {
if(handler == null) {
this.handler = new BranchListHandler(zipcode);
InputSource source = new InputSource(getRealm().getRepository().getNode(branchlist).getInputStream());
XMLReader parser = XMLReaderFactory.createXMLReader();
parser.setContentHandler(handler);
parser.parse(source);
}
return handler.recipient;
}
return null;
}
/**
* Get branch store Id which corresponds to ZIP code of customer.
* @param zipcode ZIP code of customer
*/
public String getBranchStoreId(String zipcode) throws Exception {
String branchlist = getResourceConfigProperty("email-branches");
if(branchlist != null) {
if(handler == null) {
this.handler = new BranchListHandler(zipcode);
InputSource source = new InputSource(getRealm().getRepository().getNode(branchlist).getInputStream());
XMLReader parser = XMLReaderFactory.createXMLReader();
parser.setContentHandler(handler);
parser.parse(source);
}
return handler.storeId;
}
return null;
}
/**
* Append error element for given field.
*/
/*
public void appendErr(String field, Element elem, org.w3c.dom.Document doc) {
Element err = (Element) elem.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "error"));
err.setAttribute("id", field);
}
*/
/**
* Append field to XML output.
*/
public void appendField(String field, String val, Element elem, org.w3c.dom.Document doc) {
Element err = (Element) elem.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "field"));
err.setAttribute("id", field);
err.appendChild(doc.createTextNode(val));
}
/**
* Exists?
*/
public boolean exists() {
try {
SharedResource shared = new SharedResource();
KKEngIf kkEngine = shared.getKonakartEngineImpl();
String sessionId = shared.getSessionId(getEnvironment().getRequest().getSession(true));
int customerId = shared.getCustomerId(getEnvironment().getRequest().getSession(true));
int languageId = shared.getLanguageId(getContentLanguage());
// Get customer
CustomerIf customer = shared.getCustomer(sessionId, customerId);
if(customer == null) {
return false;
}
} catch(Exception e) {
return false;
}
return true;
}
/**
* Check whether order should be processed finally
*/
private boolean readyToProcess() {
boolean process = getEnvironment().getRequest().getParameter("process") != null;
String confirmParam = getEnvironment().getRequest().getParameter("confirm");
boolean confirmGeneralTermsConditions = false;
if (confirmParam != null) {
log.debug("Confirm general terms and conditions: " + confirmParam);
confirmGeneralTermsConditions = true;
}
if(process && !confirmGeneralTermsConditions) {
log.warn("General terms and conditions have not been accepted, hence do not process order...");
process = false;
}
return process;
}
/**
* @see org.wyona.yanel.core.api.attributes.AnnotatableV1#getAnnotations()
*/
public String[] getAnnotations() throws Exception {
if (true) {
//if (readyToProcess()) {
SharedResource shared = new SharedResource();
KKEngIf kkEngine = shared.getKonakartEngineImpl();
int tmpCustomerId = shared.getTemporaryCustomerId(getEnvironment().getRequest().getSession(true));
int languageId = shared.getLanguageId(getContentLanguage());
BasketIf[] items = kkEngine.getBasketItemsPerCustomer(null, tmpCustomerId, languageId); // TODO: It seems like the basket has already been deleted!?
java.util.List<String> annotations = new java.util.ArrayList();
for (int i = 0; i < items.length; i++) {
annotations.add("" + items[i].getProductId());
annotations.add(items[i].getProduct().getName());
}
return annotations.toArray(new String[annotations.size()]);
} else {
log.warn("No annotations!");
return null;
}
}
/**
* @see org.wyona.yanel.core.api.attributes.AnnotatableV1#clearAllAnnotations()
*/
public void clearAllAnnotations() throws Exception {
log.warn("No implemented yet!");
}
/**
* @see org.wyona.yanel.core.api.attributes.AnnotatableV1#removeAnnotation(String)
*/
public void removeAnnotation(String name) throws Exception {
log.warn("No implemented yet!");
}
/**
* @see org.wyona.yanel.core.api.attributes.AnnotatableV1#setAnnotation(String)
*/
public void setAnnotation(String name) throws Exception {
log.warn("No implemented yet!");
}
/**
* @see org.wyona.yanel.core.api.attributes.TrackableV1#doTrack(TrackingInformationV1)
*/
public void doTrack(org.wyona.yanel.core.attributes.tracking.TrackingInformationV1 trackInfo) {
this.trackInfo = trackInfo;
}
}
| true | true | protected InputStream getContentXML(String viewId) throws Exception {
if (log.isDebugEnabled()) {
log.debug("requested viewId: " + viewId);
}
if (trackInfo != null) {
String[] annotations = getAnnotations();
if (annotations != null) {
for (int i = 0; i < annotations.length; i++) {
trackInfo.addTag(annotations[i]);
}
} else {
log.error("No annotations!");
}
trackInfo.setPageType("konakart-order-overview");
} else {
log.warn("Tracking information bean is null! Check life cycle of resource!");
}
SharedResource shared = new SharedResource();
KKEngIf kkEngine = shared.getKonakartEngineImpl();
KKEngIf kkEngineBranch = null; // Will be initialized later (if in multi-store mode)
//boolean multistore = false; // Will have to be checked after reading delivery address
String sessionId = shared.getSessionId(getEnvironment().getRequest().getSession(true));
int customerId = shared.getCustomerId(getEnvironment().getRequest().getSession(true));
int languageId = shared.getLanguageId(getContentLanguage());
OrderIf orderDefault = null; // Order object which will be filled with totals
// Build document
org.w3c.dom.Document doc = null;
try {
doc = org.wyona.commons.xml.XMLHelper.createDocument(KONAKART_NAMESPACE, "overview");
} catch (Exception e) {
throw new Exception(e.getMessage(), e);
}
// Root element
Element rootElement = doc.getDocumentElement();
// We'll need these later
BasketIf[] items = null;
ShippingQuoteIf shipping = null;
// Get customer
CustomerIf customer = shared.getCustomer(sessionId, customerId);
if(customer == null) {
Element exception = (Element) rootElement.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "not-logged-in-yet"));
java.io.ByteArrayOutputStream baout = new java.io.ByteArrayOutputStream();
org.wyona.commons.xml.XMLHelper.writeDocument(doc, baout);
return new java.io.ByteArrayInputStream(baout.toByteArray());
}
Element mailElem = (Element) rootElement.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "email"));
mailElem.appendChild(doc.createTextNode("" + customer.getEmailAddr()));
// Get payment (=default) address
AddressIf defaddr = kkEngine.getDefaultAddressPerCustomer(sessionId);
if(defaddr == null) {
// Well, there's no default address - just make the first address
// we have in the database the default address from now on (if there's
// no default address this is most likely a newly registered user).
AddressIf[] addrs = customer.getAddresses();
// There has to be at least one address, Konakart doesn't let you register otherwise.
defaddr = addrs[0];
kkEngine.setDefaultAddressPerCustomer(sessionId, defaddr.getId());
}
// Now print that address information
Element defAddrElem = (Element) rootElement.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "payment-address"));
Element defAddrNameElem = (Element) defAddrElem.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "last-name"));
defAddrNameElem.appendChild(doc.createTextNode("" + defaddr.getLastName()));
Element defAddrfNameElem = (Element) defAddrElem.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "first-name"));
defAddrfNameElem.appendChild(doc.createTextNode("" + defaddr.getFirstName()));
Element defAddrCompanyElem = (Element) defAddrElem.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "company"));
defAddrCompanyElem.appendChild(doc.createTextNode("" + defaddr.getCompany()));
Element defAddrCityElem = (Element) defAddrElem.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "city"));
defAddrCityElem.appendChild(doc.createTextNode("" + defaddr.getCity()));
Element defAddrCountryElem = (Element) defAddrElem.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "country"));
defAddrCountryElem.appendChild(doc.createTextNode("" + defaddr.getCountryName()));
Element defAddrStreetElem = (Element) defAddrElem.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "street"));
defAddrStreetElem.appendChild(doc.createTextNode("" + defaddr.getStreetAddress()));
Element defAddrGenderElem = (Element) defAddrElem.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "gender"));
defAddrGenderElem.appendChild(doc.createTextNode("" + defaddr.getGender()));
Element defAddrPostcodeElem = (Element) defAddrElem.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "postcode"));
defAddrPostcodeElem.appendChild(doc.createTextNode("" + defaddr.getPostcode()));
Element defAddrPhoneElem = (Element) defAddrElem.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "telephone"));
defAddrPhoneElem.appendChild(doc.createTextNode("" + customer.getTelephoneNumber()));
// Get delivery (=default) address
AddressIf[] addrs = kkEngine.getAddressesPerCustomer(sessionId);
int devaddrid = Integer.parseInt(customer.getCustom1());
AddressIf devaddr = null;
for(AddressIf a : addrs) {
if(a.getId() == devaddrid) {
devaddr = a;
}
}
if(devaddr == null) devaddr = defaddr;
// Now print that address information
Element devaddrElem = (Element) rootElement.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "delivery-address"));
Element devaddrNameElem = (Element) devaddrElem.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "last-name"));
devaddrNameElem.appendChild(doc.createTextNode("" + devaddr.getLastName()));
Element devaddrfNameElem = (Element) devaddrElem.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "first-name"));
devaddrfNameElem.appendChild(doc.createTextNode("" + devaddr.getFirstName()));
Element devaddrCompanyElem = (Element) devaddrElem.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "company"));
devaddrCompanyElem.appendChild(doc.createTextNode("" + devaddr.getCompany()));
Element devaddrCityElem = (Element) devaddrElem.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "city"));
devaddrCityElem.appendChild(doc.createTextNode("" + devaddr.getCity()));
Element devaddrCountryElem = (Element) devaddrElem.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "country"));
devaddrCountryElem.appendChild(doc.createTextNode("" + devaddr.getCountryName()));
Element devaddrStreetElem = (Element) devaddrElem.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "street"));
devaddrStreetElem.appendChild(doc.createTextNode("" + devaddr.getStreetAddress()));
Element devaddrGenderElem = (Element) devaddrElem.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "gender"));
devaddrGenderElem.appendChild(doc.createTextNode("" + devaddr.getGender()));
Element devaddrPostcodeElem = (Element) devaddrElem.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "postcode"));
devaddrPostcodeElem.appendChild(doc.createTextNode("" + devaddr.getPostcode()));
String remarks = (String) getEnvironment().getRequest().getSession(true).getAttribute("checkout-data-remarks");
if(remarks != null) appendField("remarks", remarks, rootElement, doc);
boolean process = getEnvironment().getRequest().getParameter("process") != null;
String confirmParam = getEnvironment().getRequest().getParameter("confirm");
boolean confirmGeneralTermsConditions = false;
if (confirmParam != null) {
log.warn("DEBUG: Confirm general terms and conditions: " + confirmParam);
confirmGeneralTermsConditions = true;
}
if(process && !confirmGeneralTermsConditions) {
log.warn("General terms and conditions have not been accepted, hence do not process order...");
process = false;
Element perrElem = (Element) rootElement.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "terms-not-accepted-yet"));
perrElem.appendChild(doc.createTextNode("General terms and conditions have not been accepted!"));
}
if(process) { // INFO: Check whether order should be processed ...
// If process is true, we're creating and submitting this order
// at the same time as we are displaying the information. So first,
// we need the items in the basket to create an order object.
try {
int tmpCustomerId = shared.getTemporaryCustomerId(getEnvironment().getRequest().getSession(true));
items = kkEngine.getBasketItemsPerCustomer(null, tmpCustomerId, languageId);
// Create orders
log.warn("DEBUG: Create default order ...");
orderDefault = kkEngine.createOrder(sessionId, items, languageId);
//OrderIf orderDefault = kkEngine.createOrder(sessionId, items, languageId);
shipping = shared.getShippingCost(items, sessionId, languageId, getEnvironment().getRequest().getSession(true));
orderDefault.setShippingQuote(shipping);
orderDefault = kkEngine.getOrderTotals(orderDefault, languageId);
fixOrderTotals(orderDefault, shipping);
setOrderAddressFields(orderDefault, shipping, devaddr, defaddr);
// Status trail
OrderStatusHistoryIf[] trail = new OrderStatusHistoryIf[1];
trail[0] = new OrderStatusHistory();
trail[0].setOrderStatus("New order.");
trail[0].setCustomerNotified(true);
orderDefault.setStatusTrail(trail);
} catch(Exception e) {
process = false;
log.error(e, e);
Element perrElem = (Element) rootElement.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "process-error"));
if(e.getMessage() != null) perrElem.appendChild(doc.createTextNode(e.getMessage()));
}
if (trackInfo != null) {
trackInfo.setRequestAction("order-processed");
} else {
log.warn("Tracking information bean is null! Check life cycle of resource!");
}
} else {
log.warn("DEBUG: Order either not submitted or processed yet. Continue ...");
if (trackInfo != null) {
trackInfo.setRequestAction("review-order");
} else {
log.warn("Tracking information bean is null! Check life cycle of resource!");
}
}
// Payment info
javax.servlet.http.HttpSession session = getEnvironment().getRequest().getSession(true);
String type = (String) session.getAttribute("checkout-card-data-type");
String payment_info_kk = null;
String payment_info_mail = null;
if("Pluscard".equals(type)) {
// Pluscard
Element pc = (Element) rootElement.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "payment-method-pluscard"));
Element numberElem = (Element) pc.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "number"));
String number = (String) session.getAttribute("checkout-card-data-number");
number = number.replace("[^0-9]+", "");
String num_prefix, num_suffix;
String suffix = number.substring(number.length()-4);
num_suffix = "..." + suffix;
num_prefix = number.substring(0, number.length()-4) + "****";
try {
// It's +7 because pluscards have a 7 digit prefix
char[] asterisks = new char[number.length()-4+7];
Arrays.fill(asterisks, '*');
String asterisks_str = new String(asterisks);
numberElem.appendChild(doc.createTextNode(asterisks_str + suffix));
} catch(Exception e) { }
String name = (String) session.getAttribute("checkout-card-data-name");
Element nameElem = (Element) pc.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "name"));
nameElem.appendChild(doc.createTextNode(name));
String valid = (String) session.getAttribute("checkout-card-data-valid");
Element validElem = (Element) pc.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "valid"));
validElem.appendChild(doc.createTextNode(valid));
if(process) {
try {
orderDefault.setPaymentMethod("Pluscard");
payment_info_kk = num_suffix + " (" + valid + ")";
payment_info_mail = "6004512-" + num_prefix;
} catch(Exception e) {
process = false;
log.error(e, e);
Element perrElem = (Element) rootElement.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "process-error"));
if(e.getMessage() != null) perrElem.appendChild(doc.createTextNode(e.getMessage()));
}
}
} else {
// Credit card
Element cc = (Element) rootElement.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "payment-method-creditcard"));
Element numberElem = (Element) cc.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "number"));
String number = (String) session.getAttribute("checkout-card-data-number");
number = number.replace("[^0-9]+", "");
String num_prefix, num_suffix, suffix;
suffix = number.substring(number.length()-4);
num_suffix = "..." + suffix;
num_prefix = number.substring(0, number.length()-4) + "****";
try {
char[] asterisks = new char[number.length()-4];
Arrays.fill(asterisks, '*');
String asterisks_str = new String(asterisks);
numberElem.appendChild(doc.createTextNode(asterisks_str + suffix));
} catch(Exception e) { }
String name = (String) session.getAttribute("checkout-card-data-name");
Element nameElem = (Element) cc.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "name"));
nameElem.appendChild(doc.createTextNode(name));
String valid = (String) session.getAttribute("checkout-card-data-valid");
Element validElem = (Element) cc.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "valid"));
validElem.appendChild(doc.createTextNode(valid));
Element typeElem = (Element) cc.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "type"));
typeElem.appendChild(doc.createTextNode(type));
if(process) {
try {
orderDefault.setPaymentMethod("Creditcard");
String snum = number.replace("[^0-9]+", "");
payment_info_kk = type + ": " + num_suffix + " (" + valid + ")";
String cvc = (String) session.getAttribute("checkout-card-data-cvc");
payment_info_mail = type + ": " + num_prefix + "/" + cvc;
} catch(Exception e) {
process = false;
log.error(e, e);
Element perrElem = (Element) rootElement.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "process-error"));
if(e.getMessage() != null) perrElem.appendChild(doc.createTextNode(e.getMessage()));
}
}
String globusCardNumber = (String) session.getAttribute("checkout-globuscard-number");
if (globusCardNumber != null) {
Element globusCardNumberElem = (Element) cc.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "globucard-number"));
globusCardNumberElem.appendChild(doc.createTextNode(globusCardNumber));
}
}
if(process) {
try {
int orderId = kkEngine.saveOrder(sessionId, orderDefault, languageId);
// Status updates
// TODO: Needs to be "moved" to branch store if multistore is true
kkEngine.changeOrderStatus(sessionId, orderId, orderDefault.getStatus(), true, "New order.");
if(remarks != null) {
try {
kkEngine.changeOrderStatus(sessionId, orderId, orderDefault.getStatus(), true, "Remarks: " + remarks);
} catch(Exception e) {
log.error(e, e);
}
}
if(payment_info_kk != null) {
kkEngine.changeOrderStatus(sessionId, orderId, orderDefault.getStatus(), false, "Payment details: " + payment_info_kk);
}
// INFO: Check whether ZIP corresponds to a specific store id and hence enable Multi-Store
String storeId = getBranchStoreId(devaddr.getPostcode());
boolean multistore = storeId != null;
if(multistore) {
log.warn("DEBUG: Multi-store seems to be enabled: " + devaddr.getPostcode() + ", " + storeId);
kkEngineBranch = shared.getKonakartEngineImpl(storeId);
} else {
log.warn("DEBUG: Multi-store seems to be disabled.");
}
if(multistore) {
OrderIf orderBranch = null; // INFO: Branch order object for multi-store mode
log.warn("DEBUG: Trying to create branch order ...");
log.warn("DEBUG: Realm: " + getRealm().getName() + ", " + getRealm().getConfigFile());
log.warn("DEBUG: Konakart repository: " + getRealm().getRepository("konakart-repository").getConfigFile());
org.wyona.yarep.core.Repository konakartRepo = getRealm().getRepository("konakart-repository");
org.wyona.yarep.core.Node ordersNode = konakartRepo.getNode("/orders/");
String language = "en"; // TODO: Not used actually (see implementation ...)
//String orderId = "" + orderDefault.getId();
//String orderId = orderDefault.getOrderNumber();
if (ordersNode.hasNode(orderId + "_" + language)) {
org.wyona.yarep.core.Node orderNode = ordersNode.getNode(orderId + "_" + language);
log.warn("DEBUG: Switch store ID '" + storeId + "' of order: " + orderId);
orderNode.setProperty("store-id", storeId);
} else {
log.error("No such order with ID: " + orderId);
}
// TODO: Add products to this store and append to category
for (OrderProductIf orderProduct : orderDefault.getOrderProducts()) {
com.konakart.appif.ProductIf productDefault = orderProduct.getProduct();
// INFO: Please note that the ID of an order-product is not the same as the ID of an actual product
log.warn("DEBUG: Order product ID: " + orderProduct.getId() + ", Product ID: " + productDefault.getId());
log.warn("DEBUG: Category ID of product: " + productDefault.getCategoryId());
/*
int language = 2;
com.konakart.appif.CategoryIf[] categories = kkEngine.getCategoriesPerProduct(productDefault.getId(), language);
*/
for (String shopId : kkEngine.getStoreIds()) {
log.warn("DEBUG: Store ID: " + shopId);
}
/*
AdminStore[] = KKAdminIf.getStores();
AdminStore = ...
AdminProducts = kkAdminIf.searchForProducts(...);
AdminProduct = ...
//kkEngineBranch
*/
}
/*
orderBranch = kkEngineBranch.createOrder(sessionId, items, languageId);
if (orderBranch != null) {
orderBranch.setShippingQuote(shipping);
// TODO: Something goes wrong here ...
orderBranch = kkEngineBranch.getOrderTotals(orderBranch, languageId);
fixOrderTotals(orderBranch, shipping);
setOrderAddressFields(orderBranch, shipping, devaddr, defaddr);
orderBranch.setStatusTrail(trail); // TODO: Add a branch specific trail
orderBranch.setPaymentMethod("Pluscard");
int idBranch = kkEngineBranch.saveOrder(sessionId, orderBranch, languageId);
log.warn("DEBUG: Branch order has been created: " + kkEngineBranch.getStore().getStoreId());
// TODO: ...
//kkEngine.changeOrderStatus(sessionId, idBranch, orderBranch.getStatus(), true, "New order.");
//kkEngine.changeOrderStatus(sessionId, idBranch, orderBranch.getStatus(), false, "Payment details: " + payment_info_kk);
} else {
log.error("Was not able to create order to branch store: " + storeId);
}
*/
} // INFO: End multistore
Element prElem = (Element) rootElement.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "process"));
prElem.setAttribute("orderid", "" + orderId);
// Print date
Date today = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy HH:mm");
String formattedDate = formatter.format(today);
Element dateElem = (Element) rootElement.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "date"));
dateElem.appendChild(doc.createTextNode(formattedDate));
sendMailToCustomer(orderId, orderDefault, customer);
sendMailToOwner(orderId, orderDefault, customer, payment_info_mail);
// Let Konakart send the order confirmation...
// kkEngineBranch.sendOrderConfirmationEmail(sessionId, id, "Order #" + id, languageId);
} catch(Exception e) {
process = false;
log.error(e, e);
Element perrElem = (Element) rootElement.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "process-error"));
if(e.getMessage() != null) perrElem.appendChild(doc.createTextNode(e.getMessage()));
}
}
// Output
java.io.ByteArrayOutputStream baout = new java.io.ByteArrayOutputStream();
org.wyona.commons.xml.XMLHelper.writeDocument(doc, baout);
return new java.io.ByteArrayInputStream(baout.toByteArray());
}
| protected InputStream getContentXML(String viewId) throws Exception {
if (log.isDebugEnabled()) {
log.debug("requested viewId: " + viewId);
}
if (trackInfo != null) {
String[] annotations = getAnnotations();
if (annotations != null) {
for (int i = 0; i < annotations.length; i++) {
trackInfo.addTag(annotations[i]);
}
} else {
log.error("No annotations!");
}
trackInfo.setPageType("konakart-order-overview");
} else {
log.warn("Tracking information bean is null! Check life cycle of resource!");
}
SharedResource shared = new SharedResource();
KKEngIf kkEngine = shared.getKonakartEngineImpl();
KKEngIf kkEngineBranch = null; // Will be initialized later (if in multi-store mode)
//boolean multistore = false; // Will have to be checked after reading delivery address
String sessionId = shared.getSessionId(getEnvironment().getRequest().getSession(true));
int customerId = shared.getCustomerId(getEnvironment().getRequest().getSession(true));
int languageId = shared.getLanguageId(getContentLanguage());
OrderIf orderDefault = null; // Order object which will be filled with totals
// Build document
org.w3c.dom.Document doc = null;
try {
doc = org.wyona.commons.xml.XMLHelper.createDocument(KONAKART_NAMESPACE, "overview");
} catch (Exception e) {
throw new Exception(e.getMessage(), e);
}
// Root element
Element rootElement = doc.getDocumentElement();
// We'll need these later
BasketIf[] items = null;
ShippingQuoteIf shipping = null;
// Get customer
CustomerIf customer = shared.getCustomer(sessionId, customerId);
if(customer == null) {
Element exception = (Element) rootElement.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "not-logged-in-yet"));
java.io.ByteArrayOutputStream baout = new java.io.ByteArrayOutputStream();
org.wyona.commons.xml.XMLHelper.writeDocument(doc, baout);
return new java.io.ByteArrayInputStream(baout.toByteArray());
}
Element mailElem = (Element) rootElement.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "email"));
mailElem.appendChild(doc.createTextNode("" + customer.getEmailAddr()));
// Get payment (=default) address
AddressIf defaddr = kkEngine.getDefaultAddressPerCustomer(sessionId);
if(defaddr == null) {
// Well, there's no default address - just make the first address
// we have in the database the default address from now on (if there's
// no default address this is most likely a newly registered user).
AddressIf[] addrs = customer.getAddresses();
// There has to be at least one address, Konakart doesn't let you register otherwise.
defaddr = addrs[0];
kkEngine.setDefaultAddressPerCustomer(sessionId, defaddr.getId());
}
// Now print that address information
Element defAddrElem = (Element) rootElement.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "payment-address"));
Element defAddrNameElem = (Element) defAddrElem.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "last-name"));
defAddrNameElem.appendChild(doc.createTextNode("" + defaddr.getLastName()));
Element defAddrfNameElem = (Element) defAddrElem.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "first-name"));
defAddrfNameElem.appendChild(doc.createTextNode("" + defaddr.getFirstName()));
Element defAddrCompanyElem = (Element) defAddrElem.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "company"));
defAddrCompanyElem.appendChild(doc.createTextNode("" + defaddr.getCompany()));
Element defAddrCityElem = (Element) defAddrElem.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "city"));
defAddrCityElem.appendChild(doc.createTextNode("" + defaddr.getCity()));
Element defAddrCountryElem = (Element) defAddrElem.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "country"));
defAddrCountryElem.appendChild(doc.createTextNode("" + defaddr.getCountryName()));
Element defAddrStreetElem = (Element) defAddrElem.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "street"));
defAddrStreetElem.appendChild(doc.createTextNode("" + defaddr.getStreetAddress()));
Element defAddrGenderElem = (Element) defAddrElem.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "gender"));
defAddrGenderElem.appendChild(doc.createTextNode("" + defaddr.getGender()));
Element defAddrPostcodeElem = (Element) defAddrElem.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "postcode"));
defAddrPostcodeElem.appendChild(doc.createTextNode("" + defaddr.getPostcode()));
Element defAddrPhoneElem = (Element) defAddrElem.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "telephone"));
defAddrPhoneElem.appendChild(doc.createTextNode("" + customer.getTelephoneNumber()));
// Get delivery (=default) address
AddressIf[] addrs = kkEngine.getAddressesPerCustomer(sessionId);
int devaddrid = Integer.parseInt(customer.getCustom1());
AddressIf devaddr = null;
for(AddressIf a : addrs) {
if(a.getId() == devaddrid) {
devaddr = a;
}
}
if(devaddr == null) devaddr = defaddr;
// Now print that address information
Element devaddrElem = (Element) rootElement.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "delivery-address"));
Element devaddrNameElem = (Element) devaddrElem.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "last-name"));
devaddrNameElem.appendChild(doc.createTextNode("" + devaddr.getLastName()));
Element devaddrfNameElem = (Element) devaddrElem.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "first-name"));
devaddrfNameElem.appendChild(doc.createTextNode("" + devaddr.getFirstName()));
Element devaddrCompanyElem = (Element) devaddrElem.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "company"));
devaddrCompanyElem.appendChild(doc.createTextNode("" + devaddr.getCompany()));
Element devaddrCityElem = (Element) devaddrElem.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "city"));
devaddrCityElem.appendChild(doc.createTextNode("" + devaddr.getCity()));
Element devaddrCountryElem = (Element) devaddrElem.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "country"));
devaddrCountryElem.appendChild(doc.createTextNode("" + devaddr.getCountryName()));
Element devaddrStreetElem = (Element) devaddrElem.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "street"));
devaddrStreetElem.appendChild(doc.createTextNode("" + devaddr.getStreetAddress()));
Element devaddrGenderElem = (Element) devaddrElem.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "gender"));
devaddrGenderElem.appendChild(doc.createTextNode("" + devaddr.getGender()));
Element devaddrPostcodeElem = (Element) devaddrElem.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "postcode"));
devaddrPostcodeElem.appendChild(doc.createTextNode("" + devaddr.getPostcode()));
String remarks = (String) getEnvironment().getRequest().getSession(true).getAttribute("checkout-data-remarks");
if(remarks != null) appendField("remarks", remarks, rootElement, doc);
boolean process = getEnvironment().getRequest().getParameter("process") != null;
String confirmParam = getEnvironment().getRequest().getParameter("confirm");
boolean confirmGeneralTermsConditions = false;
if (confirmParam != null) {
log.warn("DEBUG: Confirm general terms and conditions: " + confirmParam);
confirmGeneralTermsConditions = true;
}
if(process && !confirmGeneralTermsConditions) {
log.warn("General terms and conditions have not been accepted, hence do not process order...");
process = false;
Element perrElem = (Element) rootElement.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "terms-not-accepted-yet"));
perrElem.appendChild(doc.createTextNode("General terms and conditions have not been accepted!"));
}
if(process) { // INFO: Check whether order should be processed ...
// If process is true, we're creating and submitting this order
// at the same time as we are displaying the information. So first,
// we need the items in the basket to create an order object.
try {
int tmpCustomerId = shared.getTemporaryCustomerId(getEnvironment().getRequest().getSession(true));
items = kkEngine.getBasketItemsPerCustomer(null, tmpCustomerId, languageId);
// Create orders
log.warn("DEBUG: Create default order ...");
orderDefault = kkEngine.createOrder(sessionId, items, languageId);
//OrderIf orderDefault = kkEngine.createOrder(sessionId, items, languageId);
shipping = shared.getShippingCost(items, sessionId, languageId, getEnvironment().getRequest().getSession(true));
orderDefault.setShippingQuote(shipping);
orderDefault = kkEngine.getOrderTotals(orderDefault, languageId);
fixOrderTotals(orderDefault, shipping);
setOrderAddressFields(orderDefault, shipping, devaddr, defaddr);
// Status trail
OrderStatusHistoryIf[] trail = new OrderStatusHistoryIf[1];
trail[0] = new OrderStatusHistory();
trail[0].setOrderStatus("New order.");
trail[0].setCustomerNotified(true);
orderDefault.setStatusTrail(trail);
} catch(Exception e) {
process = false;
log.error(e, e);
Element perrElem = (Element) rootElement.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "process-error"));
if(e.getMessage() != null) perrElem.appendChild(doc.createTextNode(e.getMessage()));
}
if (trackInfo != null) {
trackInfo.setRequestAction("order-processed");
} else {
log.warn("Tracking information bean is null! Check life cycle of resource!");
}
} else {
log.warn("DEBUG: Order either not submitted or processed yet. Continue ...");
if (trackInfo != null) {
trackInfo.setRequestAction("review-order");
} else {
log.warn("Tracking information bean is null! Check life cycle of resource!");
}
}
// Payment info
javax.servlet.http.HttpSession session = getEnvironment().getRequest().getSession(true);
String type = (String) session.getAttribute("checkout-card-data-type");
String payment_info_kk = null;
String payment_info_mail = null;
if("Pluscard".equals(type)) {
// Pluscard
Element pc = (Element) rootElement.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "payment-method-pluscard"));
Element numberElem = (Element) pc.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "number"));
String number = (String) session.getAttribute("checkout-card-data-number");
number = number.replace("[^0-9]+", "");
String num_prefix, num_suffix;
String suffix = number.substring(number.length()-4);
num_suffix = "..." + suffix;
num_prefix = number.substring(0, number.length()-4) + "****";
try {
// It's +7 because pluscards have a 7 digit prefix
char[] asterisks = new char[number.length()-4+7];
Arrays.fill(asterisks, '*');
String asterisks_str = new String(asterisks);
numberElem.appendChild(doc.createTextNode(asterisks_str + suffix));
} catch(Exception e) { }
String name = (String) session.getAttribute("checkout-card-data-name");
Element nameElem = (Element) pc.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "name"));
nameElem.appendChild(doc.createTextNode(name));
String valid = (String) session.getAttribute("checkout-card-data-valid");
Element validElem = (Element) pc.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "valid"));
validElem.appendChild(doc.createTextNode(valid));
if(process) {
try {
orderDefault.setPaymentMethod("Pluscard");
payment_info_kk = num_suffix + " (" + valid + ")";
payment_info_mail = "6004512-" + num_prefix;
} catch(Exception e) {
process = false;
log.error(e, e);
Element perrElem = (Element) rootElement.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "process-error"));
if(e.getMessage() != null) perrElem.appendChild(doc.createTextNode(e.getMessage()));
}
}
} else {
// Credit card
Element cc = (Element) rootElement.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "payment-method-creditcard"));
Element numberElem = (Element) cc.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "number"));
String number = (String) session.getAttribute("checkout-card-data-number");
number = number.replace("[^0-9]+", "");
String num_prefix, num_suffix, suffix;
suffix = number.substring(number.length()-4);
num_suffix = "..." + suffix;
num_prefix = number.substring(0, number.length()-4) + "****";
try {
char[] asterisks = new char[number.length()-4];
Arrays.fill(asterisks, '*');
String asterisks_str = new String(asterisks);
numberElem.appendChild(doc.createTextNode(asterisks_str + suffix));
} catch(Exception e) { }
String name = (String) session.getAttribute("checkout-card-data-name");
Element nameElem = (Element) cc.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "name"));
nameElem.appendChild(doc.createTextNode(name));
String valid = (String) session.getAttribute("checkout-card-data-valid");
Element validElem = (Element) cc.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "valid"));
validElem.appendChild(doc.createTextNode(valid));
Element typeElem = (Element) cc.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "type"));
typeElem.appendChild(doc.createTextNode(type));
if(process) {
try {
orderDefault.setPaymentMethod("Creditcard");
String snum = number.replace("[^0-9]+", "");
payment_info_kk = type + ": " + num_suffix + " (" + valid + ")";
String cvc = (String) session.getAttribute("checkout-card-data-cvc");
payment_info_mail = type + ": " + num_prefix + "/" + cvc;
} catch(Exception e) {
process = false;
log.error(e, e);
Element perrElem = (Element) rootElement.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "process-error"));
if(e.getMessage() != null) perrElem.appendChild(doc.createTextNode(e.getMessage()));
}
}
String globusCardNumber = (String) session.getAttribute("checkout-globuscard-number");
if (globusCardNumber != null) {
Element globusCardNumberElem = (Element) cc.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "globuscard-number"));
globusCardNumberElem.appendChild(doc.createTextNode(globusCardNumber));
}
}
if(process) {
try {
int orderId = kkEngine.saveOrder(sessionId, orderDefault, languageId);
// Status updates
// TODO: Needs to be "moved" to branch store if multistore is true
kkEngine.changeOrderStatus(sessionId, orderId, orderDefault.getStatus(), true, "New order.");
if(remarks != null) {
try {
kkEngine.changeOrderStatus(sessionId, orderId, orderDefault.getStatus(), true, "Remarks: " + remarks);
} catch(Exception e) {
log.error(e, e);
}
}
if(payment_info_kk != null) {
kkEngine.changeOrderStatus(sessionId, orderId, orderDefault.getStatus(), false, "Payment details: " + payment_info_kk);
}
// INFO: Check whether ZIP corresponds to a specific store id and hence enable Multi-Store
String storeId = getBranchStoreId(devaddr.getPostcode());
boolean multistore = storeId != null;
if(multistore) {
log.warn("DEBUG: Multi-store seems to be enabled: " + devaddr.getPostcode() + ", " + storeId);
kkEngineBranch = shared.getKonakartEngineImpl(storeId);
} else {
log.warn("DEBUG: Multi-store seems to be disabled.");
}
if(multistore) {
OrderIf orderBranch = null; // INFO: Branch order object for multi-store mode
log.warn("DEBUG: Trying to create branch order ...");
log.warn("DEBUG: Realm: " + getRealm().getName() + ", " + getRealm().getConfigFile());
log.warn("DEBUG: Konakart repository: " + getRealm().getRepository("konakart-repository").getConfigFile());
org.wyona.yarep.core.Repository konakartRepo = getRealm().getRepository("konakart-repository");
org.wyona.yarep.core.Node ordersNode = konakartRepo.getNode("/orders/");
String language = "en"; // TODO: Not used actually (see implementation ...)
//String orderId = "" + orderDefault.getId();
//String orderId = orderDefault.getOrderNumber();
if (ordersNode.hasNode(orderId + "_" + language)) {
org.wyona.yarep.core.Node orderNode = ordersNode.getNode(orderId + "_" + language);
log.warn("DEBUG: Switch store ID '" + storeId + "' of order: " + orderId);
orderNode.setProperty("store-id", storeId);
} else {
log.error("No such order with ID: " + orderId);
}
// TODO: Add products to this store and append to category
for (OrderProductIf orderProduct : orderDefault.getOrderProducts()) {
com.konakart.appif.ProductIf productDefault = orderProduct.getProduct();
// INFO: Please note that the ID of an order-product is not the same as the ID of an actual product
log.warn("DEBUG: Order product ID: " + orderProduct.getId() + ", Product ID: " + productDefault.getId());
log.warn("DEBUG: Category ID of product: " + productDefault.getCategoryId());
/*
int language = 2;
com.konakart.appif.CategoryIf[] categories = kkEngine.getCategoriesPerProduct(productDefault.getId(), language);
*/
for (String shopId : kkEngine.getStoreIds()) {
log.warn("DEBUG: Store ID: " + shopId);
}
/*
AdminStore[] = KKAdminIf.getStores();
AdminStore = ...
AdminProducts = kkAdminIf.searchForProducts(...);
AdminProduct = ...
//kkEngineBranch
*/
}
/*
orderBranch = kkEngineBranch.createOrder(sessionId, items, languageId);
if (orderBranch != null) {
orderBranch.setShippingQuote(shipping);
// TODO: Something goes wrong here ...
orderBranch = kkEngineBranch.getOrderTotals(orderBranch, languageId);
fixOrderTotals(orderBranch, shipping);
setOrderAddressFields(orderBranch, shipping, devaddr, defaddr);
orderBranch.setStatusTrail(trail); // TODO: Add a branch specific trail
orderBranch.setPaymentMethod("Pluscard");
int idBranch = kkEngineBranch.saveOrder(sessionId, orderBranch, languageId);
log.warn("DEBUG: Branch order has been created: " + kkEngineBranch.getStore().getStoreId());
// TODO: ...
//kkEngine.changeOrderStatus(sessionId, idBranch, orderBranch.getStatus(), true, "New order.");
//kkEngine.changeOrderStatus(sessionId, idBranch, orderBranch.getStatus(), false, "Payment details: " + payment_info_kk);
} else {
log.error("Was not able to create order to branch store: " + storeId);
}
*/
} // INFO: End multistore
Element prElem = (Element) rootElement.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "process"));
prElem.setAttribute("orderid", "" + orderId);
// Print date
Date today = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy HH:mm");
String formattedDate = formatter.format(today);
Element dateElem = (Element) rootElement.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "date"));
dateElem.appendChild(doc.createTextNode(formattedDate));
sendMailToCustomer(orderId, orderDefault, customer);
sendMailToOwner(orderId, orderDefault, customer, payment_info_mail);
// Let Konakart send the order confirmation...
// kkEngineBranch.sendOrderConfirmationEmail(sessionId, id, "Order #" + id, languageId);
} catch(Exception e) {
process = false;
log.error(e, e);
Element perrElem = (Element) rootElement.appendChild(doc.createElementNS(KONAKART_NAMESPACE, "process-error"));
if(e.getMessage() != null) perrElem.appendChild(doc.createTextNode(e.getMessage()));
}
}
// Output
java.io.ByteArrayOutputStream baout = new java.io.ByteArrayOutputStream();
org.wyona.commons.xml.XMLHelper.writeDocument(doc, baout);
return new java.io.ByteArrayInputStream(baout.toByteArray());
}
|
diff --git a/src/org/mozilla/javascript/Interpreter.java b/src/org/mozilla/javascript/Interpreter.java
index ffeb89c2..54c3cd9a 100644
--- a/src/org/mozilla/javascript/Interpreter.java
+++ b/src/org/mozilla/javascript/Interpreter.java
@@ -1,4736 +1,4736 @@
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Rhino code, released
* May 6, 1999.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1997-2000
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Patrick Beard
* Norris Boyd
* Igor Bukanov
* Ethan Hugg
* Bob Jervis
* Terry Lucas
* Roger Lawrence
* Milen Nankov
* Hannes Wallnoefer
*
* 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.PrintStream;
import java.io.Serializable;
import java.util.List;
import java.util.ArrayList;
import org.mozilla.javascript.ScriptRuntime.NoSuchMethodShim;
import org.mozilla.javascript.debug.DebugFrame;
public class Interpreter implements Evaluator
{
// Additional interpreter-specific codes
private static final int
// Stack: ... value1 -> ... value1 value1
Icode_DUP = -1,
// Stack: ... value2 value1 -> ... value2 value1 value2 value1
Icode_DUP2 = -2,
// Stack: ... value2 value1 -> ... value1 value2
Icode_SWAP = -3,
// Stack: ... value1 -> ...
Icode_POP = -4,
// Store stack top into return register and then pop it
Icode_POP_RESULT = -5,
// To jump conditionally and pop additional stack value
Icode_IFEQ_POP = -6,
// various types of ++/--
Icode_VAR_INC_DEC = -7,
Icode_NAME_INC_DEC = -8,
Icode_PROP_INC_DEC = -9,
Icode_ELEM_INC_DEC = -10,
Icode_REF_INC_DEC = -11,
// load/save scope from/to local
Icode_SCOPE_LOAD = -12,
Icode_SCOPE_SAVE = -13,
Icode_TYPEOFNAME = -14,
// helper for function calls
Icode_NAME_AND_THIS = -15,
Icode_PROP_AND_THIS = -16,
Icode_ELEM_AND_THIS = -17,
Icode_VALUE_AND_THIS = -18,
// Create closure object for nested functions
Icode_CLOSURE_EXPR = -19,
Icode_CLOSURE_STMT = -20,
// Special calls
Icode_CALLSPECIAL = -21,
// To return undefined value
Icode_RETUNDEF = -22,
// Exception handling implementation
Icode_GOSUB = -23,
Icode_STARTSUB = -24,
Icode_RETSUB = -25,
// To indicating a line number change in icodes.
Icode_LINE = -26,
// To store shorts and ints inline
Icode_SHORTNUMBER = -27,
Icode_INTNUMBER = -28,
// To create and populate array to hold values for [] and {} literals
Icode_LITERAL_NEW = -29,
Icode_LITERAL_SET = -30,
// Array literal with skipped index like [1,,2]
Icode_SPARE_ARRAYLIT = -31,
// Load index register to prepare for the following index operation
Icode_REG_IND_C0 = -32,
Icode_REG_IND_C1 = -33,
Icode_REG_IND_C2 = -34,
Icode_REG_IND_C3 = -35,
Icode_REG_IND_C4 = -36,
Icode_REG_IND_C5 = -37,
Icode_REG_IND1 = -38,
Icode_REG_IND2 = -39,
Icode_REG_IND4 = -40,
// Load string register to prepare for the following string operation
Icode_REG_STR_C0 = -41,
Icode_REG_STR_C1 = -42,
Icode_REG_STR_C2 = -43,
Icode_REG_STR_C3 = -44,
Icode_REG_STR1 = -45,
Icode_REG_STR2 = -46,
Icode_REG_STR4 = -47,
// Version of getvar/setvar that read var index directly from bytecode
Icode_GETVAR1 = -48,
Icode_SETVAR1 = -49,
// Load unefined
Icode_UNDEF = -50,
Icode_ZERO = -51,
Icode_ONE = -52,
// entrance and exit from .()
Icode_ENTERDQ = -53,
Icode_LEAVEDQ = -54,
Icode_TAIL_CALL = -55,
// Clear local to allow GC its context
Icode_LOCAL_CLEAR = -56,
// Literal get/set
Icode_LITERAL_GETTER = -57,
Icode_LITERAL_SETTER = -58,
// const
Icode_SETCONST = -59,
Icode_SETCONSTVAR = -60,
Icode_SETCONSTVAR1 = -61,
// Generator opcodes (along with Token.YIELD)
Icode_GENERATOR = -62,
Icode_GENERATOR_END = -63,
Icode_DEBUGGER = -64,
// Last icode
MIN_ICODE = -64;
// data for parsing
private CompilerEnvirons compilerEnv;
private boolean itsInFunctionFlag;
private boolean itsInTryFlag;
private InterpreterData itsData;
private ScriptOrFnNode scriptOrFn;
private int itsICodeTop;
private int itsStackDepth;
private int itsLineNumber;
private int itsDoubleTableTop;
private ObjToIntMap itsStrings = new ObjToIntMap(20);
private int itsLocalTop;
private static final int MIN_LABEL_TABLE_SIZE = 32;
private static final int MIN_FIXUP_TABLE_SIZE = 40;
private int[] itsLabelTable;
private int itsLabelTableTop;
// itsFixupTable[i] = (label_index << 32) | fixup_site
private long[] itsFixupTable;
private int itsFixupTableTop;
private ObjArray itsLiteralIds = new ObjArray();
private int itsExceptionTableTop;
private static final int EXCEPTION_TRY_START_SLOT = 0;
private static final int EXCEPTION_TRY_END_SLOT = 1;
private static final int EXCEPTION_HANDLER_SLOT = 2;
private static final int EXCEPTION_TYPE_SLOT = 3;
private static final int EXCEPTION_LOCAL_SLOT = 4;
private static final int EXCEPTION_SCOPE_SLOT = 5;
// SLOT_SIZE: space for try start/end, handler, start, handler type,
// exception local and scope local
private static final int EXCEPTION_SLOT_SIZE = 6;
// ECF_ or Expression Context Flags constants: for now only TAIL is available
private static final int ECF_TAIL = 1 << 0;
/**
* Class to hold data corresponding to one interpreted call stack frame.
*/
private static class CallFrame implements Cloneable, Serializable
{
static final long serialVersionUID = -2843792508994958978L;
CallFrame parentFrame;
// amount of stack frames before this one on the interpretation stack
int frameIndex;
// If true indicates read-only frame that is a part of continuation
boolean frozen;
InterpretedFunction fnOrScript;
InterpreterData idata;
// Stack structure
// stack[0 <= i < localShift]: arguments and local variables
// stack[localShift <= i <= emptyStackTop]: used for local temporaries
// stack[emptyStackTop < i < stack.length]: stack data
// sDbl[i]: if stack[i] is UniqueTag.DOUBLE_MARK, sDbl[i] holds the number value
Object[] stack;
int[] stackAttributes;
double[] sDbl;
CallFrame varSource; // defaults to this unless continuation frame
int localShift;
int emptyStackTop;
DebugFrame debuggerFrame;
boolean useActivation;
boolean isContinuationsTopFrame;
Scriptable thisObj;
Scriptable[] scriptRegExps;
// The values that change during interpretation
Object result;
double resultDbl;
int pc;
int pcPrevBranch;
int pcSourceLineStart;
Scriptable scope;
int savedStackTop;
int savedCallOp;
Object throwable;
CallFrame cloneFrozen()
{
if (!frozen) Kit.codeBug();
CallFrame copy;
try {
copy = (CallFrame)clone();
} catch (CloneNotSupportedException ex) {
throw new IllegalStateException();
}
// clone stack but keep varSource to point to values
// from this frame to share variables.
copy.stack = stack.clone();
copy.stackAttributes = stackAttributes.clone();
copy.sDbl = sDbl.clone();
copy.frozen = false;
return copy;
}
}
private static final class ContinuationJump implements Serializable
{
static final long serialVersionUID = 7687739156004308247L;
CallFrame capturedFrame;
CallFrame branchFrame;
Object result;
double resultDbl;
ContinuationJump(NativeContinuation c, CallFrame current)
{
this.capturedFrame = (CallFrame)c.getImplementation();
if (this.capturedFrame == null || current == null) {
// Continuation and current execution does not share
// any frames if there is nothing to capture or
// if there is no currently executed frames
this.branchFrame = null;
} else {
// Search for branch frame where parent frame chains starting
// from captured and current meet.
CallFrame chain1 = this.capturedFrame;
CallFrame chain2 = current;
// First work parents of chain1 or chain2 until the same
// frame depth.
int diff = chain1.frameIndex - chain2.frameIndex;
if (diff != 0) {
if (diff < 0) {
// swap to make sure that
// chain1.frameIndex > chain2.frameIndex and diff > 0
chain1 = current;
chain2 = this.capturedFrame;
diff = -diff;
}
do {
chain1 = chain1.parentFrame;
} while (--diff != 0);
if (chain1.frameIndex != chain2.frameIndex) Kit.codeBug();
}
// Now walk parents in parallel until a shared frame is found
// or until the root is reached.
while (chain1 != chain2 && chain1 != null) {
chain1 = chain1.parentFrame;
chain2 = chain2.parentFrame;
}
this.branchFrame = chain1;
if (this.branchFrame != null && !this.branchFrame.frozen)
Kit.codeBug();
}
}
}
private static CallFrame captureFrameForGenerator(CallFrame frame) {
frame.frozen = true;
CallFrame result = frame.cloneFrozen();
frame.frozen = false;
// now isolate this frame from its previous context
result.parentFrame = null;
result.frameIndex = 0;
return result;
}
static {
// Checks for byte code consistencies, good compiler can eliminate them
if (Token.LAST_BYTECODE_TOKEN > 127) {
String str = "Violation of Token.LAST_BYTECODE_TOKEN <= 127";
System.err.println(str);
throw new IllegalStateException(str);
}
if (MIN_ICODE < -128) {
String str = "Violation of Interpreter.MIN_ICODE >= -128";
System.err.println(str);
throw new IllegalStateException(str);
}
}
private static String bytecodeName(int bytecode)
{
if (!validBytecode(bytecode)) {
throw new IllegalArgumentException(String.valueOf(bytecode));
}
if (!Token.printICode) {
return String.valueOf(bytecode);
}
if (validTokenCode(bytecode)) {
return Token.name(bytecode);
}
switch (bytecode) {
case Icode_DUP: return "DUP";
case Icode_DUP2: return "DUP2";
case Icode_SWAP: return "SWAP";
case Icode_POP: return "POP";
case Icode_POP_RESULT: return "POP_RESULT";
case Icode_IFEQ_POP: return "IFEQ_POP";
case Icode_VAR_INC_DEC: return "VAR_INC_DEC";
case Icode_NAME_INC_DEC: return "NAME_INC_DEC";
case Icode_PROP_INC_DEC: return "PROP_INC_DEC";
case Icode_ELEM_INC_DEC: return "ELEM_INC_DEC";
case Icode_REF_INC_DEC: return "REF_INC_DEC";
case Icode_SCOPE_LOAD: return "SCOPE_LOAD";
case Icode_SCOPE_SAVE: return "SCOPE_SAVE";
case Icode_TYPEOFNAME: return "TYPEOFNAME";
case Icode_NAME_AND_THIS: return "NAME_AND_THIS";
case Icode_PROP_AND_THIS: return "PROP_AND_THIS";
case Icode_ELEM_AND_THIS: return "ELEM_AND_THIS";
case Icode_VALUE_AND_THIS: return "VALUE_AND_THIS";
case Icode_CLOSURE_EXPR: return "CLOSURE_EXPR";
case Icode_CLOSURE_STMT: return "CLOSURE_STMT";
case Icode_CALLSPECIAL: return "CALLSPECIAL";
case Icode_RETUNDEF: return "RETUNDEF";
case Icode_GOSUB: return "GOSUB";
case Icode_STARTSUB: return "STARTSUB";
case Icode_RETSUB: return "RETSUB";
case Icode_LINE: return "LINE";
case Icode_SHORTNUMBER: return "SHORTNUMBER";
case Icode_INTNUMBER: return "INTNUMBER";
case Icode_LITERAL_NEW: return "LITERAL_NEW";
case Icode_LITERAL_SET: return "LITERAL_SET";
case Icode_SPARE_ARRAYLIT: return "SPARE_ARRAYLIT";
case Icode_REG_IND_C0: return "REG_IND_C0";
case Icode_REG_IND_C1: return "REG_IND_C1";
case Icode_REG_IND_C2: return "REG_IND_C2";
case Icode_REG_IND_C3: return "REG_IND_C3";
case Icode_REG_IND_C4: return "REG_IND_C4";
case Icode_REG_IND_C5: return "REG_IND_C5";
case Icode_REG_IND1: return "LOAD_IND1";
case Icode_REG_IND2: return "LOAD_IND2";
case Icode_REG_IND4: return "LOAD_IND4";
case Icode_REG_STR_C0: return "REG_STR_C0";
case Icode_REG_STR_C1: return "REG_STR_C1";
case Icode_REG_STR_C2: return "REG_STR_C2";
case Icode_REG_STR_C3: return "REG_STR_C3";
case Icode_REG_STR1: return "LOAD_STR1";
case Icode_REG_STR2: return "LOAD_STR2";
case Icode_REG_STR4: return "LOAD_STR4";
case Icode_GETVAR1: return "GETVAR1";
case Icode_SETVAR1: return "SETVAR1";
case Icode_UNDEF: return "UNDEF";
case Icode_ZERO: return "ZERO";
case Icode_ONE: return "ONE";
case Icode_ENTERDQ: return "ENTERDQ";
case Icode_LEAVEDQ: return "LEAVEDQ";
case Icode_TAIL_CALL: return "TAIL_CALL";
case Icode_LOCAL_CLEAR: return "LOCAL_CLEAR";
case Icode_LITERAL_GETTER: return "LITERAL_GETTER";
case Icode_LITERAL_SETTER: return "LITERAL_SETTER";
case Icode_SETCONST: return "SETCONST";
case Icode_SETCONSTVAR: return "SETCONSTVAR";
case Icode_SETCONSTVAR1: return "SETCONSTVAR1";
case Icode_GENERATOR: return "GENERATOR";
case Icode_GENERATOR_END: return "GENERATOR_END";
case Icode_DEBUGGER: return "DEBUGGER";
}
// icode without name
throw new IllegalStateException(String.valueOf(bytecode));
}
private static boolean validIcode(int icode)
{
return MIN_ICODE <= icode && icode <= -1;
}
private static boolean validTokenCode(int token)
{
return Token.FIRST_BYTECODE_TOKEN <= token
&& token <= Token.LAST_BYTECODE_TOKEN;
}
private static boolean validBytecode(int bytecode)
{
return validIcode(bytecode) || validTokenCode(bytecode);
}
public Object compile(CompilerEnvirons compilerEnv,
ScriptOrFnNode tree,
String encodedSource,
boolean returnFunction)
{
this.compilerEnv = compilerEnv;
new NodeTransformer().transform(tree);
if (Token.printTrees) {
System.out.println(tree.toStringTree(tree));
}
if (returnFunction) {
tree = tree.getFunctionNode(0);
}
scriptOrFn = tree;
itsData = new InterpreterData(compilerEnv.getLanguageVersion(),
scriptOrFn.getSourceName(),
encodedSource);
itsData.topLevel = true;
if (returnFunction) {
generateFunctionICode();
} else {
generateICodeFromTree(scriptOrFn);
}
return itsData;
}
public Script createScriptObject(Object bytecode, Object staticSecurityDomain)
{
if(bytecode != itsData)
{
Kit.codeBug();
}
return InterpretedFunction.createScript(itsData,
staticSecurityDomain);
}
public void setEvalScriptFlag(Script script) {
((InterpretedFunction)script).idata.evalScriptFlag = true;
}
public Function createFunctionObject(Context cx, Scriptable scope,
Object bytecode, Object staticSecurityDomain)
{
if(bytecode != itsData)
{
Kit.codeBug();
}
return InterpretedFunction.createFunction(cx, scope, itsData,
staticSecurityDomain);
}
private void generateFunctionICode()
{
itsInFunctionFlag = true;
FunctionNode theFunction = (FunctionNode)scriptOrFn;
itsData.itsFunctionType = theFunction.getFunctionType();
itsData.itsNeedsActivation = theFunction.requiresActivation();
itsData.itsName = theFunction.getFunctionName();
if (!theFunction.getIgnoreDynamicScope()) {
if (compilerEnv.isUseDynamicScope()) {
itsData.useDynamicScope = true;
}
}
if (theFunction.isGenerator()) {
addIcode(Icode_GENERATOR);
addUint16(theFunction.getBaseLineno() & 0xFFFF);
}
generateICodeFromTree(theFunction.getLastChild());
}
private void generateICodeFromTree(Node tree)
{
generateNestedFunctions();
generateRegExpLiterals();
visitStatement(tree, 0);
fixLabelGotos();
// add RETURN_RESULT only to scripts as function always ends with RETURN
if (itsData.itsFunctionType == 0) {
addToken(Token.RETURN_RESULT);
}
if (itsData.itsICode.length != itsICodeTop) {
// Make itsData.itsICode length exactly itsICodeTop to save memory
// and catch bugs with jumps beyond icode as early as possible
byte[] tmp = new byte[itsICodeTop];
System.arraycopy(itsData.itsICode, 0, tmp, 0, itsICodeTop);
itsData.itsICode = tmp;
}
if (itsStrings.size() == 0) {
itsData.itsStringTable = null;
} else {
itsData.itsStringTable = new String[itsStrings.size()];
ObjToIntMap.Iterator iter = itsStrings.newIterator();
for (iter.start(); !iter.done(); iter.next()) {
String str = (String)iter.getKey();
int index = iter.getValue();
if (itsData.itsStringTable[index] != null) Kit.codeBug();
itsData.itsStringTable[index] = str;
}
}
if (itsDoubleTableTop == 0) {
itsData.itsDoubleTable = null;
} else if (itsData.itsDoubleTable.length != itsDoubleTableTop) {
double[] tmp = new double[itsDoubleTableTop];
System.arraycopy(itsData.itsDoubleTable, 0, tmp, 0,
itsDoubleTableTop);
itsData.itsDoubleTable = tmp;
}
if (itsExceptionTableTop != 0
&& itsData.itsExceptionTable.length != itsExceptionTableTop)
{
int[] tmp = new int[itsExceptionTableTop];
System.arraycopy(itsData.itsExceptionTable, 0, tmp, 0,
itsExceptionTableTop);
itsData.itsExceptionTable = tmp;
}
itsData.itsMaxVars = scriptOrFn.getParamAndVarCount();
// itsMaxFrameArray: interpret method needs this amount for its
// stack and sDbl arrays
itsData.itsMaxFrameArray = itsData.itsMaxVars
+ itsData.itsMaxLocals
+ itsData.itsMaxStack;
itsData.argNames = scriptOrFn.getParamAndVarNames();
itsData.argIsConst = scriptOrFn.getParamAndVarConst();
itsData.argCount = scriptOrFn.getParamCount();
itsData.encodedSourceStart = scriptOrFn.getEncodedSourceStart();
itsData.encodedSourceEnd = scriptOrFn.getEncodedSourceEnd();
if (itsLiteralIds.size() != 0) {
itsData.literalIds = itsLiteralIds.toArray();
}
if (Token.printICode) dumpICode(itsData);
}
private void generateNestedFunctions()
{
int functionCount = scriptOrFn.getFunctionCount();
if (functionCount == 0) return;
InterpreterData[] array = new InterpreterData[functionCount];
for (int i = 0; i != functionCount; i++) {
FunctionNode def = scriptOrFn.getFunctionNode(i);
Interpreter jsi = new Interpreter();
jsi.compilerEnv = compilerEnv;
jsi.scriptOrFn = def;
jsi.itsData = new InterpreterData(itsData);
jsi.generateFunctionICode();
array[i] = jsi.itsData;
}
itsData.itsNestedFunctions = array;
}
private void generateRegExpLiterals()
{
int N = scriptOrFn.getRegexpCount();
if (N == 0) return;
Context cx = Context.getContext();
RegExpProxy rep = ScriptRuntime.checkRegExpProxy(cx);
Object[] array = new Object[N];
for (int i = 0; i != N; i++) {
String string = scriptOrFn.getRegexpString(i);
String flags = scriptOrFn.getRegexpFlags(i);
array[i] = rep.compileRegExp(cx, string, flags);
}
itsData.itsRegExpLiterals = array;
}
private void updateLineNumber(Node node)
{
int lineno = node.getLineno();
if (lineno != itsLineNumber && lineno >= 0) {
if (itsData.firstLinePC < 0) {
itsData.firstLinePC = lineno;
}
itsLineNumber = lineno;
addIcode(Icode_LINE);
addUint16(lineno & 0xFFFF);
}
}
private RuntimeException badTree(Node node)
{
throw new RuntimeException(node.toString());
}
private void visitStatement(Node node, int initialStackDepth)
{
int type = node.getType();
Node child = node.getFirstChild();
switch (type) {
case Token.FUNCTION:
{
int fnIndex = node.getExistingIntProp(Node.FUNCTION_PROP);
int fnType = scriptOrFn.getFunctionNode(fnIndex).
getFunctionType();
// Only function expressions or function expression
// statements need closure code creating new function
// object on stack as function statements are initialized
// at script/function start.
// In addition, function expressions can not be present here
// at statement level, they must only be present as expressions.
if (fnType == FunctionNode.FUNCTION_EXPRESSION_STATEMENT) {
addIndexOp(Icode_CLOSURE_STMT, fnIndex);
} else {
if (fnType != FunctionNode.FUNCTION_STATEMENT) {
throw Kit.codeBug();
}
}
// For function statements or function expression statements
// in scripts, we need to ensure that the result of the script
// is the function if it is the last statement in the script.
// For example, eval("function () {}") should return a
// function, not undefined.
if (!itsInFunctionFlag) {
addIndexOp(Icode_CLOSURE_EXPR, fnIndex);
stackChange(1);
addIcode(Icode_POP_RESULT);
stackChange(-1);
}
}
break;
case Token.LABEL:
case Token.LOOP:
case Token.BLOCK:
case Token.EMPTY:
case Token.WITH:
updateLineNumber(node);
case Token.SCRIPT:
// fall through
while (child != null) {
visitStatement(child, initialStackDepth);
child = child.getNext();
}
break;
case Token.ENTERWITH:
visitExpression(child, 0);
addToken(Token.ENTERWITH);
stackChange(-1);
break;
case Token.LEAVEWITH:
addToken(Token.LEAVEWITH);
break;
case Token.LOCAL_BLOCK:
{
int local = allocLocal();
node.putIntProp(Node.LOCAL_PROP, local);
updateLineNumber(node);
while (child != null) {
visitStatement(child, initialStackDepth);
child = child.getNext();
}
addIndexOp(Icode_LOCAL_CLEAR, local);
releaseLocal(local);
}
break;
case Token.DEBUGGER:
addIcode(Icode_DEBUGGER);
break;
case Token.SWITCH:
updateLineNumber(node);
// See comments in IRFactory.createSwitch() for description
// of SWITCH node
{
visitExpression(child, 0);
for (Node.Jump caseNode = (Node.Jump)child.getNext();
caseNode != null;
caseNode = (Node.Jump)caseNode.getNext())
{
if (caseNode.getType() != Token.CASE)
throw badTree(caseNode);
Node test = caseNode.getFirstChild();
addIcode(Icode_DUP);
stackChange(1);
visitExpression(test, 0);
addToken(Token.SHEQ);
stackChange(-1);
// If true, Icode_IFEQ_POP will jump and remove case
// value from stack
addGoto(caseNode.target, Icode_IFEQ_POP);
stackChange(-1);
}
addIcode(Icode_POP);
stackChange(-1);
}
break;
case Token.TARGET:
markTargetLabel(node);
break;
case Token.IFEQ :
case Token.IFNE :
{
Node target = ((Node.Jump)node).target;
visitExpression(child, 0);
addGoto(target, type);
stackChange(-1);
}
break;
case Token.GOTO:
{
Node target = ((Node.Jump)node).target;
addGoto(target, type);
}
break;
case Token.JSR:
{
Node target = ((Node.Jump)node).target;
addGoto(target, Icode_GOSUB);
}
break;
case Token.FINALLY:
{
// Account for incomming GOTOSUB address
stackChange(1);
int finallyRegister = getLocalBlockRef(node);
addIndexOp(Icode_STARTSUB, finallyRegister);
stackChange(-1);
while (child != null) {
visitStatement(child, initialStackDepth);
child = child.getNext();
}
addIndexOp(Icode_RETSUB, finallyRegister);
}
break;
case Token.EXPR_VOID:
case Token.EXPR_RESULT:
updateLineNumber(node);
visitExpression(child, 0);
addIcode((type == Token.EXPR_VOID) ? Icode_POP : Icode_POP_RESULT);
stackChange(-1);
break;
case Token.TRY:
{
Node.Jump tryNode = (Node.Jump)node;
int exceptionObjectLocal = getLocalBlockRef(tryNode);
int scopeLocal = allocLocal();
addIndexOp(Icode_SCOPE_SAVE, scopeLocal);
int tryStart = itsICodeTop;
boolean savedFlag = itsInTryFlag;
itsInTryFlag = true;
while (child != null) {
visitStatement(child, initialStackDepth);
child = child.getNext();
}
itsInTryFlag = savedFlag;
Node catchTarget = tryNode.target;
if (catchTarget != null) {
int catchStartPC
= itsLabelTable[getTargetLabel(catchTarget)];
addExceptionHandler(
tryStart, catchStartPC, catchStartPC,
false, exceptionObjectLocal, scopeLocal);
}
Node finallyTarget = tryNode.getFinally();
if (finallyTarget != null) {
int finallyStartPC
= itsLabelTable[getTargetLabel(finallyTarget)];
addExceptionHandler(
tryStart, finallyStartPC, finallyStartPC,
true, exceptionObjectLocal, scopeLocal);
}
addIndexOp(Icode_LOCAL_CLEAR, scopeLocal);
releaseLocal(scopeLocal);
}
break;
case Token.CATCH_SCOPE:
{
int localIndex = getLocalBlockRef(node);
int scopeIndex = node.getExistingIntProp(Node.CATCH_SCOPE_PROP);
String name = child.getString();
child = child.getNext();
visitExpression(child, 0); // load expression object
addStringPrefix(name);
addIndexPrefix(localIndex);
addToken(Token.CATCH_SCOPE);
addUint8(scopeIndex != 0 ? 1 : 0);
stackChange(-1);
}
break;
case Token.THROW:
updateLineNumber(node);
visitExpression(child, 0);
addToken(Token.THROW);
addUint16(itsLineNumber & 0xFFFF);
stackChange(-1);
break;
case Token.RETHROW:
updateLineNumber(node);
addIndexOp(Token.RETHROW, getLocalBlockRef(node));
break;
case Token.RETURN:
updateLineNumber(node);
if (node.getIntProp(Node.GENERATOR_END_PROP, 0) != 0) {
// We're in a generator, so change RETURN to GENERATOR_END
addIcode(Icode_GENERATOR_END);
addUint16(itsLineNumber & 0xFFFF);
} else if (child != null) {
visitExpression(child, ECF_TAIL);
addToken(Token.RETURN);
stackChange(-1);
} else {
addIcode(Icode_RETUNDEF);
}
break;
case Token.RETURN_RESULT:
updateLineNumber(node);
addToken(Token.RETURN_RESULT);
break;
case Token.ENUM_INIT_KEYS:
case Token.ENUM_INIT_VALUES:
case Token.ENUM_INIT_ARRAY:
visitExpression(child, 0);
addIndexOp(type, getLocalBlockRef(node));
stackChange(-1);
break;
case Icode_GENERATOR:
break;
default:
throw badTree(node);
}
if (itsStackDepth != initialStackDepth) {
throw Kit.codeBug();
}
}
private void visitExpression(Node node, int contextFlags)
{
int type = node.getType();
Node child = node.getFirstChild();
int savedStackDepth = itsStackDepth;
switch (type) {
case Token.FUNCTION:
{
int fnIndex = node.getExistingIntProp(Node.FUNCTION_PROP);
FunctionNode fn = scriptOrFn.getFunctionNode(fnIndex);
// See comments in visitStatement for Token.FUNCTION case
if (fn.getFunctionType() != FunctionNode.FUNCTION_EXPRESSION) {
throw Kit.codeBug();
}
addIndexOp(Icode_CLOSURE_EXPR, fnIndex);
stackChange(1);
}
break;
case Token.LOCAL_LOAD:
{
int localIndex = getLocalBlockRef(node);
addIndexOp(Token.LOCAL_LOAD, localIndex);
stackChange(1);
}
break;
case Token.COMMA:
{
Node lastChild = node.getLastChild();
while (child != lastChild) {
visitExpression(child, 0);
addIcode(Icode_POP);
stackChange(-1);
child = child.getNext();
}
// Preserve tail context flag if any
visitExpression(child, contextFlags & ECF_TAIL);
}
break;
case Token.USE_STACK:
// Indicates that stack was modified externally,
// like placed catch object
stackChange(1);
break;
case Token.REF_CALL:
case Token.CALL:
case Token.NEW:
{
if (type == Token.NEW) {
visitExpression(child, 0);
} else {
generateCallFunAndThis(child);
}
int argCount = 0;
while ((child = child.getNext()) != null) {
visitExpression(child, 0);
++argCount;
}
int callType = node.getIntProp(Node.SPECIALCALL_PROP,
Node.NON_SPECIALCALL);
if (callType != Node.NON_SPECIALCALL) {
// embed line number and source filename
addIndexOp(Icode_CALLSPECIAL, argCount);
addUint8(callType);
addUint8(type == Token.NEW ? 1 : 0);
addUint16(itsLineNumber & 0xFFFF);
} else {
// Only use the tail call optimization if we're not in a try
// or we're not generating debug info (since the
// optimization will confuse the debugger)
if (type == Token.CALL && (contextFlags & ECF_TAIL) != 0 &&
!compilerEnv.isGenerateDebugInfo() && !itsInTryFlag)
{
type = Icode_TAIL_CALL;
}
addIndexOp(type, argCount);
}
// adjust stack
if (type == Token.NEW) {
// new: f, args -> result
stackChange(-argCount);
} else {
// call: f, thisObj, args -> result
// ref_call: f, thisObj, args -> ref
stackChange(-1 - argCount);
}
if (argCount > itsData.itsMaxCalleeArgs) {
itsData.itsMaxCalleeArgs = argCount;
}
}
break;
case Token.AND:
case Token.OR:
{
visitExpression(child, 0);
addIcode(Icode_DUP);
stackChange(1);
int afterSecondJumpStart = itsICodeTop;
int jump = (type == Token.AND) ? Token.IFNE : Token.IFEQ;
addGotoOp(jump);
stackChange(-1);
addIcode(Icode_POP);
stackChange(-1);
child = child.getNext();
// Preserve tail context flag if any
visitExpression(child, contextFlags & ECF_TAIL);
resolveForwardGoto(afterSecondJumpStart);
}
break;
case Token.HOOK:
{
Node ifThen = child.getNext();
Node ifElse = ifThen.getNext();
visitExpression(child, 0);
int elseJumpStart = itsICodeTop;
addGotoOp(Token.IFNE);
stackChange(-1);
// Preserve tail context flag if any
visitExpression(ifThen, contextFlags & ECF_TAIL);
int afterElseJumpStart = itsICodeTop;
addGotoOp(Token.GOTO);
resolveForwardGoto(elseJumpStart);
itsStackDepth = savedStackDepth;
// Preserve tail context flag if any
visitExpression(ifElse, contextFlags & ECF_TAIL);
resolveForwardGoto(afterElseJumpStart);
}
break;
case Token.GETPROP:
case Token.GETPROPNOWARN:
visitExpression(child, 0);
child = child.getNext();
addStringOp(type, child.getString());
break;
case Token.GETELEM:
case Token.DELPROP:
case Token.BITAND:
case Token.BITOR:
case Token.BITXOR:
case Token.LSH:
case Token.RSH:
case Token.URSH:
case Token.ADD:
case Token.SUB:
case Token.MOD:
case Token.DIV:
case Token.MUL:
case Token.EQ:
case Token.NE:
case Token.SHEQ:
case Token.SHNE:
case Token.IN:
case Token.INSTANCEOF:
case Token.LE:
case Token.LT:
case Token.GE:
case Token.GT:
visitExpression(child, 0);
child = child.getNext();
visitExpression(child, 0);
addToken(type);
stackChange(-1);
break;
case Token.POS:
case Token.NEG:
case Token.NOT:
case Token.BITNOT:
case Token.TYPEOF:
case Token.VOID:
visitExpression(child, 0);
if (type == Token.VOID) {
addIcode(Icode_POP);
addIcode(Icode_UNDEF);
} else {
addToken(type);
}
break;
case Token.GET_REF:
case Token.DEL_REF:
visitExpression(child, 0);
addToken(type);
break;
case Token.SETPROP:
case Token.SETPROP_OP:
{
visitExpression(child, 0);
child = child.getNext();
String property = child.getString();
child = child.getNext();
if (type == Token.SETPROP_OP) {
addIcode(Icode_DUP);
stackChange(1);
addStringOp(Token.GETPROP, property);
// Compensate for the following USE_STACK
stackChange(-1);
}
visitExpression(child, 0);
addStringOp(Token.SETPROP, property);
stackChange(-1);
}
break;
case Token.SETELEM:
case Token.SETELEM_OP:
visitExpression(child, 0);
child = child.getNext();
visitExpression(child, 0);
child = child.getNext();
if (type == Token.SETELEM_OP) {
addIcode(Icode_DUP2);
stackChange(2);
addToken(Token.GETELEM);
stackChange(-1);
// Compensate for the following USE_STACK
stackChange(-1);
}
visitExpression(child, 0);
addToken(Token.SETELEM);
stackChange(-2);
break;
case Token.SET_REF:
case Token.SET_REF_OP:
visitExpression(child, 0);
child = child.getNext();
if (type == Token.SET_REF_OP) {
addIcode(Icode_DUP);
stackChange(1);
addToken(Token.GET_REF);
// Compensate for the following USE_STACK
stackChange(-1);
}
visitExpression(child, 0);
addToken(Token.SET_REF);
stackChange(-1);
break;
case Token.SETNAME:
{
String name = child.getString();
visitExpression(child, 0);
child = child.getNext();
visitExpression(child, 0);
addStringOp(Token.SETNAME, name);
stackChange(-1);
}
break;
case Token.SETCONST:
{
String name = child.getString();
visitExpression(child, 0);
child = child.getNext();
visitExpression(child, 0);
addStringOp(Icode_SETCONST, name);
stackChange(-1);
}
break;
case Token.TYPEOFNAME:
{
int index = -1;
// use typeofname if an activation frame exists
// since the vars all exist there instead of in jregs
if (itsInFunctionFlag && !itsData.itsNeedsActivation)
index = scriptOrFn.getIndexForNameNode(node);
if (index == -1) {
addStringOp(Icode_TYPEOFNAME, node.getString());
stackChange(1);
} else {
addVarOp(Token.GETVAR, index);
stackChange(1);
addToken(Token.TYPEOF);
}
}
break;
case Token.BINDNAME:
case Token.NAME:
case Token.STRING:
addStringOp(type, node.getString());
stackChange(1);
break;
case Token.INC:
case Token.DEC:
visitIncDec(node, child);
break;
case Token.NUMBER:
{
double num = node.getDouble();
int inum = (int)num;
if (inum == num) {
if (inum == 0) {
addIcode(Icode_ZERO);
// Check for negative zero
if (1.0 / num < 0.0) {
addToken(Token.NEG);
}
} else if (inum == 1) {
addIcode(Icode_ONE);
} else if ((short)inum == inum) {
addIcode(Icode_SHORTNUMBER);
// write short as uin16 bit pattern
addUint16(inum & 0xFFFF);
} else {
addIcode(Icode_INTNUMBER);
addInt(inum);
}
} else {
int index = getDoubleIndex(num);
addIndexOp(Token.NUMBER, index);
}
stackChange(1);
}
break;
case Token.GETVAR:
{
if (itsData.itsNeedsActivation) Kit.codeBug();
int index = scriptOrFn.getIndexForNameNode(node);
addVarOp(Token.GETVAR, index);
stackChange(1);
}
break;
case Token.SETVAR:
{
if (itsData.itsNeedsActivation) Kit.codeBug();
int index = scriptOrFn.getIndexForNameNode(child);
child = child.getNext();
visitExpression(child, 0);
addVarOp(Token.SETVAR, index);
}
break;
case Token.SETCONSTVAR:
{
if (itsData.itsNeedsActivation) Kit.codeBug();
int index = scriptOrFn.getIndexForNameNode(child);
child = child.getNext();
visitExpression(child, 0);
addVarOp(Token.SETCONSTVAR, index);
}
break;
case Token.NULL:
case Token.THIS:
case Token.THISFN:
case Token.FALSE:
case Token.TRUE:
addToken(type);
stackChange(1);
break;
case Token.ENUM_NEXT:
case Token.ENUM_ID:
addIndexOp(type, getLocalBlockRef(node));
stackChange(1);
break;
case Token.REGEXP:
{
int index = node.getExistingIntProp(Node.REGEXP_PROP);
addIndexOp(Token.REGEXP, index);
stackChange(1);
}
break;
case Token.ARRAYLIT:
case Token.OBJECTLIT:
visitLiteral(node, child);
break;
case Token.ARRAYCOMP:
visitArrayComprehension(node, child, child.getNext());
break;
case Token.REF_SPECIAL:
visitExpression(child, 0);
addStringOp(type, (String)node.getProp(Node.NAME_PROP));
break;
case Token.REF_MEMBER:
case Token.REF_NS_MEMBER:
case Token.REF_NAME:
case Token.REF_NS_NAME:
{
int memberTypeFlags = node.getIntProp(Node.MEMBER_TYPE_PROP, 0);
// generate possible target, possible namespace and member
int childCount = 0;
do {
visitExpression(child, 0);
++childCount;
child = child.getNext();
} while (child != null);
addIndexOp(type, memberTypeFlags);
stackChange(1 - childCount);
}
break;
case Token.DOTQUERY:
{
int queryPC;
updateLineNumber(node);
visitExpression(child, 0);
addIcode(Icode_ENTERDQ);
stackChange(-1);
queryPC = itsICodeTop;
visitExpression(child.getNext(), 0);
addBackwardGoto(Icode_LEAVEDQ, queryPC);
}
break;
case Token.DEFAULTNAMESPACE :
case Token.ESCXMLATTR :
case Token.ESCXMLTEXT :
visitExpression(child, 0);
addToken(type);
break;
case Token.YIELD:
if (child != null) {
visitExpression(child, 0);
} else {
addIcode(Icode_UNDEF);
stackChange(1);
}
addToken(Token.YIELD);
addUint16(node.getLineno() & 0xFFFF);
break;
case Token.WITHEXPR: {
Node enterWith = node.getFirstChild();
Node with = enterWith.getNext();
visitExpression(enterWith.getFirstChild(), 0);
addToken(Token.ENTERWITH);
stackChange(-1);
visitExpression(with.getFirstChild(), 0);
addToken(Token.LEAVEWITH);
break;
}
default:
throw badTree(node);
}
if (savedStackDepth + 1 != itsStackDepth) {
Kit.codeBug();
}
}
private void generateCallFunAndThis(Node left)
{
// Generate code to place on stack function and thisObj
int type = left.getType();
switch (type) {
case Token.NAME: {
String name = left.getString();
// stack: ... -> ... function thisObj
addStringOp(Icode_NAME_AND_THIS, name);
stackChange(2);
break;
}
case Token.GETPROP:
case Token.GETELEM: {
Node target = left.getFirstChild();
visitExpression(target, 0);
Node id = target.getNext();
if (type == Token.GETPROP) {
String property = id.getString();
// stack: ... target -> ... function thisObj
addStringOp(Icode_PROP_AND_THIS, property);
stackChange(1);
} else {
visitExpression(id, 0);
// stack: ... target id -> ... function thisObj
addIcode(Icode_ELEM_AND_THIS);
}
break;
}
default:
// Including Token.GETVAR
visitExpression(left, 0);
// stack: ... value -> ... function thisObj
addIcode(Icode_VALUE_AND_THIS);
stackChange(1);
break;
}
}
private void visitIncDec(Node node, Node child)
{
int incrDecrMask = node.getExistingIntProp(Node.INCRDECR_PROP);
int childType = child.getType();
switch (childType) {
case Token.GETVAR : {
if (itsData.itsNeedsActivation) Kit.codeBug();
int i = scriptOrFn.getIndexForNameNode(child);
addVarOp(Icode_VAR_INC_DEC, i);
addUint8(incrDecrMask);
stackChange(1);
break;
}
case Token.NAME : {
String name = child.getString();
addStringOp(Icode_NAME_INC_DEC, name);
addUint8(incrDecrMask);
stackChange(1);
break;
}
case Token.GETPROP : {
Node object = child.getFirstChild();
visitExpression(object, 0);
String property = object.getNext().getString();
addStringOp(Icode_PROP_INC_DEC, property);
addUint8(incrDecrMask);
break;
}
case Token.GETELEM : {
Node object = child.getFirstChild();
visitExpression(object, 0);
Node index = object.getNext();
visitExpression(index, 0);
addIcode(Icode_ELEM_INC_DEC);
addUint8(incrDecrMask);
stackChange(-1);
break;
}
case Token.GET_REF : {
Node ref = child.getFirstChild();
visitExpression(ref, 0);
addIcode(Icode_REF_INC_DEC);
addUint8(incrDecrMask);
break;
}
default : {
throw badTree(node);
}
}
}
private void visitLiteral(Node node, Node child)
{
int type = node.getType();
int count;
Object[] propertyIds = null;
if (type == Token.ARRAYLIT) {
count = 0;
for (Node n = child; n != null; n = n.getNext()) {
++count;
}
} else if (type == Token.OBJECTLIT) {
propertyIds = (Object[])node.getProp(Node.OBJECT_IDS_PROP);
count = propertyIds.length;
} else {
throw badTree(node);
}
addIndexOp(Icode_LITERAL_NEW, count);
stackChange(2);
while (child != null) {
int childType = child.getType();
if (childType == Token.GET) {
visitExpression(child.getFirstChild(), 0);
addIcode(Icode_LITERAL_GETTER);
} else if (childType == Token.SET) {
visitExpression(child.getFirstChild(), 0);
addIcode(Icode_LITERAL_SETTER);
} else {
visitExpression(child, 0);
addIcode(Icode_LITERAL_SET);
}
stackChange(-1);
child = child.getNext();
}
if (type == Token.ARRAYLIT) {
int[] skipIndexes = (int[])node.getProp(Node.SKIP_INDEXES_PROP);
if (skipIndexes == null) {
addToken(Token.ARRAYLIT);
} else {
int index = itsLiteralIds.size();
itsLiteralIds.add(skipIndexes);
addIndexOp(Icode_SPARE_ARRAYLIT, index);
}
} else {
int index = itsLiteralIds.size();
itsLiteralIds.add(propertyIds);
addIndexOp(Token.OBJECTLIT, index);
}
stackChange(-1);
}
private void visitArrayComprehension(Node node, Node initStmt, Node expr)
{
// A bit of a hack: array comprehensions are implemented using
// statement nodes for the iteration, yet they appear in an
// expression context. So we pass the current stack depth to
// visitStatement so it can check that the depth is not altered
// by statements.
visitStatement(initStmt, itsStackDepth);
visitExpression(expr, 0);
}
private int getLocalBlockRef(Node node)
{
Node localBlock = (Node)node.getProp(Node.LOCAL_BLOCK_PROP);
return localBlock.getExistingIntProp(Node.LOCAL_PROP);
}
private int getTargetLabel(Node target)
{
int label = target.labelId();
if (label != -1) {
return label;
}
label = itsLabelTableTop;
if (itsLabelTable == null || label == itsLabelTable.length) {
if (itsLabelTable == null) {
itsLabelTable = new int[MIN_LABEL_TABLE_SIZE];
}else {
int[] tmp = new int[itsLabelTable.length * 2];
System.arraycopy(itsLabelTable, 0, tmp, 0, label);
itsLabelTable = tmp;
}
}
itsLabelTableTop = label + 1;
itsLabelTable[label] = -1;
target.labelId(label);
return label;
}
private void markTargetLabel(Node target)
{
int label = getTargetLabel(target);
if (itsLabelTable[label] != -1) {
// Can mark label only once
Kit.codeBug();
}
itsLabelTable[label] = itsICodeTop;
}
private void addGoto(Node target, int gotoOp)
{
int label = getTargetLabel(target);
if (!(label < itsLabelTableTop)) Kit.codeBug();
int targetPC = itsLabelTable[label];
if (targetPC != -1) {
addBackwardGoto(gotoOp, targetPC);
} else {
int gotoPC = itsICodeTop;
addGotoOp(gotoOp);
int top = itsFixupTableTop;
if (itsFixupTable == null || top == itsFixupTable.length) {
if (itsFixupTable == null) {
itsFixupTable = new long[MIN_FIXUP_TABLE_SIZE];
} else {
long[] tmp = new long[itsFixupTable.length * 2];
System.arraycopy(itsFixupTable, 0, tmp, 0, top);
itsFixupTable = tmp;
}
}
itsFixupTableTop = top + 1;
itsFixupTable[top] = ((long)label << 32) | gotoPC;
}
}
private void fixLabelGotos()
{
for (int i = 0; i < itsFixupTableTop; i++) {
long fixup = itsFixupTable[i];
int label = (int)(fixup >> 32);
int jumpSource = (int)fixup;
int pc = itsLabelTable[label];
if (pc == -1) {
// Unlocated label
throw Kit.codeBug();
}
resolveGoto(jumpSource, pc);
}
itsFixupTableTop = 0;
}
private void addBackwardGoto(int gotoOp, int jumpPC)
{
int fromPC = itsICodeTop;
// Ensure that this is a jump backward
if (fromPC <= jumpPC) throw Kit.codeBug();
addGotoOp(gotoOp);
resolveGoto(fromPC, jumpPC);
}
private void resolveForwardGoto(int fromPC)
{
// Ensure that forward jump skips at least self bytecode
if (itsICodeTop < fromPC + 3) throw Kit.codeBug();
resolveGoto(fromPC, itsICodeTop);
}
private void resolveGoto(int fromPC, int jumpPC)
{
int offset = jumpPC - fromPC;
// Ensure that jumps do not overlap
if (0 <= offset && offset <= 2) throw Kit.codeBug();
int offsetSite = fromPC + 1;
if (offset != (short)offset) {
if (itsData.longJumps == null) {
itsData.longJumps = new UintMap();
}
itsData.longJumps.put(offsetSite, jumpPC);
offset = 0;
}
byte[] array = itsData.itsICode;
array[offsetSite] = (byte)(offset >> 8);
array[offsetSite + 1] = (byte)offset;
}
private void addToken(int token)
{
if (!validTokenCode(token)) throw Kit.codeBug();
addUint8(token);
}
private void addIcode(int icode)
{
if (!validIcode(icode)) throw Kit.codeBug();
// Write negative icode as uint8 bits
addUint8(icode & 0xFF);
}
private void addUint8(int value)
{
if ((value & ~0xFF) != 0) throw Kit.codeBug();
byte[] array = itsData.itsICode;
int top = itsICodeTop;
if (top == array.length) {
array = increaseICodeCapacity(1);
}
array[top] = (byte)value;
itsICodeTop = top + 1;
}
private void addUint16(int value)
{
if ((value & ~0xFFFF) != 0) throw Kit.codeBug();
byte[] array = itsData.itsICode;
int top = itsICodeTop;
if (top + 2 > array.length) {
array = increaseICodeCapacity(2);
}
array[top] = (byte)(value >>> 8);
array[top + 1] = (byte)value;
itsICodeTop = top + 2;
}
private void addInt(int i)
{
byte[] array = itsData.itsICode;
int top = itsICodeTop;
if (top + 4 > array.length) {
array = increaseICodeCapacity(4);
}
array[top] = (byte)(i >>> 24);
array[top + 1] = (byte)(i >>> 16);
array[top + 2] = (byte)(i >>> 8);
array[top + 3] = (byte)i;
itsICodeTop = top + 4;
}
private int getDoubleIndex(double num)
{
int index = itsDoubleTableTop;
if (index == 0) {
itsData.itsDoubleTable = new double[64];
} else if (itsData.itsDoubleTable.length == index) {
double[] na = new double[index * 2];
System.arraycopy(itsData.itsDoubleTable, 0, na, 0, index);
itsData.itsDoubleTable = na;
}
itsData.itsDoubleTable[index] = num;
itsDoubleTableTop = index + 1;
return index;
}
private void addGotoOp(int gotoOp)
{
byte[] array = itsData.itsICode;
int top = itsICodeTop;
if (top + 3 > array.length) {
array = increaseICodeCapacity(3);
}
array[top] = (byte)gotoOp;
// Offset would written later
itsICodeTop = top + 1 + 2;
}
private void addVarOp(int op, int varIndex)
{
switch (op) {
case Token.SETCONSTVAR:
if (varIndex < 128) {
addIcode(Icode_SETCONSTVAR1);
addUint8(varIndex);
return;
}
addIndexOp(Icode_SETCONSTVAR, varIndex);
return;
case Token.GETVAR:
case Token.SETVAR:
if (varIndex < 128) {
addIcode(op == Token.GETVAR ? Icode_GETVAR1 : Icode_SETVAR1);
addUint8(varIndex);
return;
}
// fallthrough
case Icode_VAR_INC_DEC:
addIndexOp(op, varIndex);
return;
}
throw Kit.codeBug();
}
private void addStringOp(int op, String str)
{
addStringPrefix(str);
if (validIcode(op)) {
addIcode(op);
} else {
addToken(op);
}
}
private void addIndexOp(int op, int index)
{
addIndexPrefix(index);
if (validIcode(op)) {
addIcode(op);
} else {
addToken(op);
}
}
private void addStringPrefix(String str)
{
int index = itsStrings.get(str, -1);
if (index == -1) {
index = itsStrings.size();
itsStrings.put(str, index);
}
if (index < 4) {
addIcode(Icode_REG_STR_C0 - index);
} else if (index <= 0xFF) {
addIcode(Icode_REG_STR1);
addUint8(index);
} else if (index <= 0xFFFF) {
addIcode(Icode_REG_STR2);
addUint16(index);
} else {
addIcode(Icode_REG_STR4);
addInt(index);
}
}
private void addIndexPrefix(int index)
{
if (index < 0) Kit.codeBug();
if (index < 6) {
addIcode(Icode_REG_IND_C0 - index);
} else if (index <= 0xFF) {
addIcode(Icode_REG_IND1);
addUint8(index);
} else if (index <= 0xFFFF) {
addIcode(Icode_REG_IND2);
addUint16(index);
} else {
addIcode(Icode_REG_IND4);
addInt(index);
}
}
private void addExceptionHandler(int icodeStart, int icodeEnd,
int handlerStart, boolean isFinally,
int exceptionObjectLocal, int scopeLocal)
{
int top = itsExceptionTableTop;
int[] table = itsData.itsExceptionTable;
if (table == null) {
if (top != 0) Kit.codeBug();
table = new int[EXCEPTION_SLOT_SIZE * 2];
itsData.itsExceptionTable = table;
} else if (table.length == top) {
table = new int[table.length * 2];
System.arraycopy(itsData.itsExceptionTable, 0, table, 0, top);
itsData.itsExceptionTable = table;
}
table[top + EXCEPTION_TRY_START_SLOT] = icodeStart;
table[top + EXCEPTION_TRY_END_SLOT] = icodeEnd;
table[top + EXCEPTION_HANDLER_SLOT] = handlerStart;
table[top + EXCEPTION_TYPE_SLOT] = isFinally ? 1 : 0;
table[top + EXCEPTION_LOCAL_SLOT] = exceptionObjectLocal;
table[top + EXCEPTION_SCOPE_SLOT] = scopeLocal;
itsExceptionTableTop = top + EXCEPTION_SLOT_SIZE;
}
private byte[] increaseICodeCapacity(int extraSize)
{
int capacity = itsData.itsICode.length;
int top = itsICodeTop;
if (top + extraSize <= capacity) throw Kit.codeBug();
capacity *= 2;
if (top + extraSize > capacity) {
capacity = top + extraSize;
}
byte[] array = new byte[capacity];
System.arraycopy(itsData.itsICode, 0, array, 0, top);
itsData.itsICode = array;
return array;
}
private void stackChange(int change)
{
if (change <= 0) {
itsStackDepth += change;
} else {
int newDepth = itsStackDepth + change;
if (newDepth > itsData.itsMaxStack) {
itsData.itsMaxStack = newDepth;
}
itsStackDepth = newDepth;
}
}
private int allocLocal()
{
int localSlot = itsLocalTop;
++itsLocalTop;
if (itsLocalTop > itsData.itsMaxLocals) {
itsData.itsMaxLocals = itsLocalTop;
}
return localSlot;
}
private void releaseLocal(int localSlot)
{
--itsLocalTop;
if (localSlot != itsLocalTop) Kit.codeBug();
}
private static int getShort(byte[] iCode, int pc) {
return (iCode[pc] << 8) | (iCode[pc + 1] & 0xFF);
}
private static int getIndex(byte[] iCode, int pc) {
return ((iCode[pc] & 0xFF) << 8) | (iCode[pc + 1] & 0xFF);
}
private static int getInt(byte[] iCode, int pc) {
return (iCode[pc] << 24) | ((iCode[pc + 1] & 0xFF) << 16)
| ((iCode[pc + 2] & 0xFF) << 8) | (iCode[pc + 3] & 0xFF);
}
private static int getExceptionHandler(CallFrame frame,
boolean onlyFinally)
{
int[] exceptionTable = frame.idata.itsExceptionTable;
if (exceptionTable == null) {
// No exception handlers
return -1;
}
// Icode switch in the interpreter increments PC immediately
// and it is necessary to subtract 1 from the saved PC
// to point it before the start of the next instruction.
int pc = frame.pc - 1;
// OPT: use binary search
int best = -1, bestStart = 0, bestEnd = 0;
for (int i = 0; i != exceptionTable.length; i += EXCEPTION_SLOT_SIZE) {
int start = exceptionTable[i + EXCEPTION_TRY_START_SLOT];
int end = exceptionTable[i + EXCEPTION_TRY_END_SLOT];
if (!(start <= pc && pc < end)) {
continue;
}
if (onlyFinally && exceptionTable[i + EXCEPTION_TYPE_SLOT] != 1) {
continue;
}
if (best >= 0) {
// Since handlers always nest and they never have shared end
// although they can share start it is sufficient to compare
// handlers ends
if (bestEnd < end) {
continue;
}
// Check the above assumption
if (bestStart > start) Kit.codeBug(); // should be nested
if (bestEnd == end) Kit.codeBug(); // no ens sharing
}
best = i;
bestStart = start;
bestEnd = end;
}
return best;
}
private static void dumpICode(InterpreterData idata)
{
if (!Token.printICode) {
return;
}
byte iCode[] = idata.itsICode;
int iCodeLength = iCode.length;
String[] strings = idata.itsStringTable;
PrintStream out = System.out;
out.println("ICode dump, for " + idata.itsName
+ ", length = " + iCodeLength);
out.println("MaxStack = " + idata.itsMaxStack);
int indexReg = 0;
for (int pc = 0; pc < iCodeLength; ) {
out.flush();
out.print(" [" + pc + "] ");
int token = iCode[pc];
int icodeLength = bytecodeSpan(token);
String tname = bytecodeName(token);
int old_pc = pc;
++pc;
switch (token) {
default:
if (icodeLength != 1) Kit.codeBug();
out.println(tname);
break;
case Icode_GOSUB :
case Token.GOTO :
case Token.IFEQ :
case Token.IFNE :
case Icode_IFEQ_POP :
case Icode_LEAVEDQ : {
int newPC = pc + getShort(iCode, pc) - 1;
out.println(tname + " " + newPC);
pc += 2;
break;
}
case Icode_VAR_INC_DEC :
case Icode_NAME_INC_DEC :
case Icode_PROP_INC_DEC :
case Icode_ELEM_INC_DEC :
case Icode_REF_INC_DEC: {
int incrDecrType = iCode[pc];
out.println(tname + " " + incrDecrType);
++pc;
break;
}
case Icode_CALLSPECIAL : {
int callType = iCode[pc] & 0xFF;
boolean isNew = (iCode[pc + 1] != 0);
int line = getIndex(iCode, pc+2);
out.println(tname+" "+callType+" "+isNew+" "+indexReg+" "+line);
pc += 4;
break;
}
case Token.CATCH_SCOPE:
{
boolean afterFisrtFlag = (iCode[pc] != 0);
out.println(tname+" "+afterFisrtFlag);
++pc;
}
break;
case Token.REGEXP :
out.println(tname+" "+idata.itsRegExpLiterals[indexReg]);
break;
case Token.OBJECTLIT :
case Icode_SPARE_ARRAYLIT :
out.println(tname+" "+idata.literalIds[indexReg]);
break;
case Icode_CLOSURE_EXPR :
case Icode_CLOSURE_STMT :
out.println(tname+" "+idata.itsNestedFunctions[indexReg]);
break;
case Token.CALL :
case Icode_TAIL_CALL :
case Token.REF_CALL :
case Token.NEW :
out.println(tname+' '+indexReg);
break;
case Token.THROW :
case Token.YIELD :
case Icode_GENERATOR :
case Icode_GENERATOR_END :
{
int line = getIndex(iCode, pc);
out.println(tname + " : " + line);
pc += 2;
break;
}
case Icode_SHORTNUMBER : {
int value = getShort(iCode, pc);
out.println(tname + " " + value);
pc += 2;
break;
}
case Icode_INTNUMBER : {
int value = getInt(iCode, pc);
out.println(tname + " " + value);
pc += 4;
break;
}
case Token.NUMBER : {
double value = idata.itsDoubleTable[indexReg];
out.println(tname + " " + value);
break;
}
case Icode_LINE : {
int line = getIndex(iCode, pc);
out.println(tname + " : " + line);
pc += 2;
break;
}
case Icode_REG_STR1: {
String str = strings[0xFF & iCode[pc]];
out.println(tname + " \"" + str + '"');
++pc;
break;
}
case Icode_REG_STR2: {
String str = strings[getIndex(iCode, pc)];
out.println(tname + " \"" + str + '"');
pc += 2;
break;
}
case Icode_REG_STR4: {
String str = strings[getInt(iCode, pc)];
out.println(tname + " \"" + str + '"');
pc += 4;
break;
}
case Icode_REG_IND_C0:
indexReg = 0;
out.println(tname);
break;
case Icode_REG_IND_C1:
indexReg = 1;
out.println(tname);
break;
case Icode_REG_IND_C2:
indexReg = 2;
out.println(tname);
break;
case Icode_REG_IND_C3:
indexReg = 3;
out.println(tname);
break;
case Icode_REG_IND_C4:
indexReg = 4;
out.println(tname);
break;
case Icode_REG_IND_C5:
indexReg = 5;
out.println(tname);
break;
case Icode_REG_IND1: {
indexReg = 0xFF & iCode[pc];
out.println(tname+" "+indexReg);
++pc;
break;
}
case Icode_REG_IND2: {
indexReg = getIndex(iCode, pc);
out.println(tname+" "+indexReg);
pc += 2;
break;
}
case Icode_REG_IND4: {
indexReg = getInt(iCode, pc);
out.println(tname+" "+indexReg);
pc += 4;
break;
}
case Icode_GETVAR1:
case Icode_SETVAR1:
case Icode_SETCONSTVAR1:
indexReg = iCode[pc];
out.println(tname+" "+indexReg);
++pc;
break;
}
if (old_pc + icodeLength != pc) Kit.codeBug();
}
int[] table = idata.itsExceptionTable;
if (table != null) {
out.println("Exception handlers: "
+table.length / EXCEPTION_SLOT_SIZE);
for (int i = 0; i != table.length;
i += EXCEPTION_SLOT_SIZE)
{
int tryStart = table[i + EXCEPTION_TRY_START_SLOT];
int tryEnd = table[i + EXCEPTION_TRY_END_SLOT];
int handlerStart = table[i + EXCEPTION_HANDLER_SLOT];
int type = table[i + EXCEPTION_TYPE_SLOT];
int exceptionLocal = table[i + EXCEPTION_LOCAL_SLOT];
int scopeLocal = table[i + EXCEPTION_SCOPE_SLOT];
out.println(" tryStart="+tryStart+" tryEnd="+tryEnd
+" handlerStart="+handlerStart
+" type="+(type == 0 ? "catch" : "finally")
+" exceptionLocal="+exceptionLocal);
}
}
out.flush();
}
private static int bytecodeSpan(int bytecode)
{
switch (bytecode) {
case Token.THROW :
case Token.YIELD:
case Icode_GENERATOR:
case Icode_GENERATOR_END:
// source line
return 1 + 2;
case Icode_GOSUB :
case Token.GOTO :
case Token.IFEQ :
case Token.IFNE :
case Icode_IFEQ_POP :
case Icode_LEAVEDQ :
// target pc offset
return 1 + 2;
case Icode_CALLSPECIAL :
// call type
// is new
// line number
return 1 + 1 + 1 + 2;
case Token.CATCH_SCOPE:
// scope flag
return 1 + 1;
case Icode_VAR_INC_DEC:
case Icode_NAME_INC_DEC:
case Icode_PROP_INC_DEC:
case Icode_ELEM_INC_DEC:
case Icode_REF_INC_DEC:
// type of ++/--
return 1 + 1;
case Icode_SHORTNUMBER :
// short number
return 1 + 2;
case Icode_INTNUMBER :
// int number
return 1 + 4;
case Icode_REG_IND1:
// ubyte index
return 1 + 1;
case Icode_REG_IND2:
// ushort index
return 1 + 2;
case Icode_REG_IND4:
// int index
return 1 + 4;
case Icode_REG_STR1:
// ubyte string index
return 1 + 1;
case Icode_REG_STR2:
// ushort string index
return 1 + 2;
case Icode_REG_STR4:
// int string index
return 1 + 4;
case Icode_GETVAR1:
case Icode_SETVAR1:
case Icode_SETCONSTVAR1:
// byte var index
return 1 + 1;
case Icode_LINE :
// line number
return 1 + 2;
}
if (!validBytecode(bytecode)) throw Kit.codeBug();
return 1;
}
static int[] getLineNumbers(InterpreterData data)
{
UintMap presentLines = new UintMap();
byte[] iCode = data.itsICode;
int iCodeLength = iCode.length;
for (int pc = 0; pc != iCodeLength;) {
int bytecode = iCode[pc];
int span = bytecodeSpan(bytecode);
if (bytecode == Icode_LINE) {
if (span != 3) Kit.codeBug();
int line = getIndex(iCode, pc + 1);
presentLines.put(line, 0);
}
pc += span;
}
return presentLines.getKeys();
}
public void captureStackInfo(RhinoException ex)
{
Context cx = Context.getCurrentContext();
if (cx == null || cx.lastInterpreterFrame == null) {
// No interpreter invocations
ex.interpreterStackInfo = null;
ex.interpreterLineData = null;
return;
}
// has interpreter frame on the stack
CallFrame[] array;
if (cx.previousInterpreterInvocations == null
|| cx.previousInterpreterInvocations.size() == 0)
{
array = new CallFrame[1];
} else {
int previousCount = cx.previousInterpreterInvocations.size();
if (cx.previousInterpreterInvocations.peek()
== cx.lastInterpreterFrame)
{
// It can happen if exception was generated after
// frame was pushed to cx.previousInterpreterInvocations
// but before assignment to cx.lastInterpreterFrame.
// In this case frames has to be ignored.
--previousCount;
}
array = new CallFrame[previousCount + 1];
cx.previousInterpreterInvocations.toArray(array);
}
array[array.length - 1] = (CallFrame)cx.lastInterpreterFrame;
int interpreterFrameCount = 0;
for (int i = 0; i != array.length; ++i) {
interpreterFrameCount += 1 + array[i].frameIndex;
}
int[] linePC = new int[interpreterFrameCount];
// Fill linePC with pc positions from all interpreter frames.
// Start from the most nested frame
int linePCIndex = interpreterFrameCount;
for (int i = array.length; i != 0;) {
--i;
CallFrame frame = array[i];
while (frame != null) {
--linePCIndex;
linePC[linePCIndex] = frame.pcSourceLineStart;
frame = frame.parentFrame;
}
}
if (linePCIndex != 0) Kit.codeBug();
ex.interpreterStackInfo = array;
ex.interpreterLineData = linePC;
}
public String getSourcePositionFromStack(Context cx, int[] linep)
{
CallFrame frame = (CallFrame)cx.lastInterpreterFrame;
InterpreterData idata = frame.idata;
if (frame.pcSourceLineStart >= 0) {
linep[0] = getIndex(idata.itsICode, frame.pcSourceLineStart);
} else {
linep[0] = 0;
}
return idata.itsSourceFile;
}
public String getPatchedStack(RhinoException ex,
String nativeStackTrace)
{
String tag = "org.mozilla.javascript.Interpreter.interpretLoop";
StringBuffer sb = new StringBuffer(nativeStackTrace.length() + 1000);
String lineSeparator = SecurityUtilities.getSystemProperty("line.separator");
CallFrame[] array = (CallFrame[])ex.interpreterStackInfo;
int[] linePC = ex.interpreterLineData;
int arrayIndex = array.length;
int linePCIndex = linePC.length;
int offset = 0;
while (arrayIndex != 0) {
--arrayIndex;
int pos = nativeStackTrace.indexOf(tag, offset);
if (pos < 0) {
break;
}
// Skip tag length
pos += tag.length();
// Skip until the end of line
for (; pos != nativeStackTrace.length(); ++pos) {
char c = nativeStackTrace.charAt(pos);
if (c == '\n' || c == '\r') {
break;
}
}
sb.append(nativeStackTrace.substring(offset, pos));
offset = pos;
CallFrame frame = array[arrayIndex];
while (frame != null) {
if (linePCIndex == 0) Kit.codeBug();
--linePCIndex;
InterpreterData idata = frame.idata;
sb.append(lineSeparator);
sb.append("\tat script");
if (idata.itsName != null && idata.itsName.length() != 0) {
sb.append('.');
sb.append(idata.itsName);
}
sb.append('(');
sb.append(idata.itsSourceFile);
int pc = linePC[linePCIndex];
if (pc >= 0) {
// Include line info only if available
sb.append(':');
sb.append(getIndex(idata.itsICode, pc));
}
sb.append(')');
frame = frame.parentFrame;
}
}
sb.append(nativeStackTrace.substring(offset));
return sb.toString();
}
public List<String> getScriptStack(RhinoException ex)
{
if (ex.interpreterStackInfo == null) {
return null;
}
List<String> list = new ArrayList<String>();
String lineSeparator =
SecurityUtilities.getSystemProperty("line.separator");
CallFrame[] array = (CallFrame[])ex.interpreterStackInfo;
int[] linePC = ex.interpreterLineData;
int arrayIndex = array.length;
int linePCIndex = linePC.length;
while (arrayIndex != 0) {
--arrayIndex;
StringBuilder sb = new StringBuilder();
CallFrame frame = array[arrayIndex];
while (frame != null) {
if (linePCIndex == 0) Kit.codeBug();
--linePCIndex;
InterpreterData idata = frame.idata;
sb.append("\tat ");
sb.append(idata.itsSourceFile);
int pc = linePC[linePCIndex];
if (pc >= 0) {
// Include line info only if available
sb.append(':');
sb.append(getIndex(idata.itsICode, pc));
}
if (idata.itsName != null && idata.itsName.length() != 0) {
sb.append(" (");
sb.append(idata.itsName);
sb.append(')');
}
sb.append(lineSeparator);
frame = frame.parentFrame;
}
list.add(sb.toString());
}
return list;
}
static String getEncodedSource(InterpreterData idata)
{
if (idata.encodedSource == null) {
return null;
}
return idata.encodedSource.substring(idata.encodedSourceStart,
idata.encodedSourceEnd);
}
private static void initFunction(Context cx, Scriptable scope,
InterpretedFunction parent, int index)
{
InterpretedFunction fn;
fn = InterpretedFunction.createFunction(cx, scope, parent, index);
ScriptRuntime.initFunction(cx, scope, fn, fn.idata.itsFunctionType,
parent.idata.evalScriptFlag);
}
static Object interpret(InterpretedFunction ifun,
Context cx, Scriptable scope,
Scriptable thisObj, Object[] args)
{
if (!ScriptRuntime.hasTopCall(cx)) Kit.codeBug();
if (cx.interpreterSecurityDomain != ifun.securityDomain) {
Object savedDomain = cx.interpreterSecurityDomain;
cx.interpreterSecurityDomain = ifun.securityDomain;
try {
return ifun.securityController.callWithDomain(
ifun.securityDomain, cx, ifun, scope, thisObj, args);
} finally {
cx.interpreterSecurityDomain = savedDomain;
}
}
CallFrame frame = new CallFrame();
initFrame(cx, scope, thisObj, args, null, 0, args.length,
ifun, null, frame);
frame.isContinuationsTopFrame = cx.isContinuationsTopCall;
cx.isContinuationsTopCall = false;
return interpretLoop(cx, frame, null);
}
static class GeneratorState {
GeneratorState(int operation, Object value) {
this.operation = operation;
this.value = value;
}
int operation;
Object value;
RuntimeException returnedException;
}
public static Object resumeGenerator(Context cx,
Scriptable scope,
int operation,
Object savedState,
Object value)
{
CallFrame frame = (CallFrame) savedState;
GeneratorState generatorState = new GeneratorState(operation, value);
if (operation == NativeGenerator.GENERATOR_CLOSE) {
try {
return interpretLoop(cx, frame, generatorState);
} catch (RuntimeException e) {
// Only propagate exceptions other than closingException
if (e != value)
throw e;
}
return Undefined.instance;
}
Object result = interpretLoop(cx, frame, generatorState);
if (generatorState.returnedException != null)
throw generatorState.returnedException;
return result;
}
public static Object restartContinuation(NativeContinuation c, Context cx,
Scriptable scope, Object[] args)
{
if (!ScriptRuntime.hasTopCall(cx)) {
return ScriptRuntime.doTopCall(c, cx, scope, null, args);
}
Object arg;
if (args.length == 0) {
arg = Undefined.instance;
} else {
arg = args[0];
}
CallFrame capturedFrame = (CallFrame)c.getImplementation();
if (capturedFrame == null) {
// No frames to restart
return arg;
}
ContinuationJump cjump = new ContinuationJump(c, null);
cjump.result = arg;
return interpretLoop(cx, null, cjump);
}
private static Object interpretLoop(Context cx, CallFrame frame,
Object throwable)
{
// throwable holds exception object to rethrow or catch
// It is also used for continuation restart in which case
// it holds ContinuationJump
final Object DBL_MRK = UniqueTag.DOUBLE_MARK;
final Object undefined = Undefined.instance;
final boolean instructionCounting = (cx.instructionThreshold != 0);
// arbitrary number to add to instructionCount when calling
// other functions
final int INVOCATION_COST = 100;
// arbitrary exception cost for instruction counting
final int EXCEPTION_COST = 100;
String stringReg = null;
int indexReg = -1;
if (cx.lastInterpreterFrame != null) {
// save the top frame from the previous interpretLoop
// invocation on the stack
if (cx.previousInterpreterInvocations == null) {
cx.previousInterpreterInvocations = new ObjArray();
}
cx.previousInterpreterInvocations.push(cx.lastInterpreterFrame);
}
// When restarting continuation throwable is not null and to jump
// to the code that rewind continuation state indexReg should be set
// to -1.
// With the normal call throwable == null and indexReg == -1 allows to
// catch bugs with using indeReg to access array elements before
// initializing indexReg.
GeneratorState generatorState = null;
if (throwable != null) {
if (throwable instanceof GeneratorState) {
generatorState = (GeneratorState) throwable;
// reestablish this call frame
enterFrame(cx, frame, ScriptRuntime.emptyArgs, true);
throwable = null;
} else if (!(throwable instanceof ContinuationJump)) {
// It should be continuation
Kit.codeBug();
}
}
Object interpreterResult = null;
double interpreterResultDbl = 0.0;
StateLoop: for (;;) {
withoutExceptions: try {
if (throwable != null) {
// Need to return both 'frame' and 'throwable' from
// 'processThrowable', so just added a 'throwable'
// member in 'frame'.
frame = processThrowable(cx, throwable, frame, indexReg,
instructionCounting);
throwable = frame.throwable;
frame.throwable = null;
} else {
if (generatorState == null && frame.frozen) Kit.codeBug();
}
// Use local variables for constant values in frame
// for faster access
Object[] stack = frame.stack;
double[] sDbl = frame.sDbl;
Object[] vars = frame.varSource.stack;
double[] varDbls = frame.varSource.sDbl;
int[] varAttributes = frame.varSource.stackAttributes;
byte[] iCode = frame.idata.itsICode;
String[] strings = frame.idata.itsStringTable;
// Use local for stackTop as well. Since execption handlers
// can only exist at statement level where stack is empty,
// it is necessary to save/restore stackTop only across
// function calls and normal returns.
int stackTop = frame.savedStackTop;
// Store new frame in cx which is used for error reporting etc.
cx.lastInterpreterFrame = frame;
Loop: for (;;) {
// Exception handler assumes that PC is already incremented
// pass the instruction start when it searches the
// exception handler
int op = iCode[frame.pc++];
jumplessRun: {
// Back indent to ease implementation reading
switch (op) {
case Icode_GENERATOR: {
if (!frame.frozen) {
// First time encountering this opcode: create new generator
// object and return
frame.pc--; // we want to come back here when we resume
CallFrame generatorFrame = captureFrameForGenerator(frame);
generatorFrame.frozen = true;
NativeGenerator generator = new NativeGenerator(frame.scope,
generatorFrame.fnOrScript, generatorFrame);
frame.result = generator;
break Loop;
} else {
// We are now resuming execution. Fall through to YIELD case.
}
}
// fall through...
case Token.YIELD: {
if (!frame.frozen) {
return freezeGenerator(cx, frame, stackTop, generatorState);
} else {
Object obj = thawGenerator(frame, stackTop, generatorState, op);
if (obj != Scriptable.NOT_FOUND) {
throwable = obj;
break withoutExceptions;
}
continue Loop;
}
}
case Icode_GENERATOR_END: {
// throw StopIteration
frame.frozen = true;
int sourceLine = getIndex(iCode, frame.pc);
generatorState.returnedException = new JavaScriptException(
NativeIterator.getStopIterationObject(frame.scope),
frame.idata.itsSourceFile, sourceLine);
break Loop;
}
case Token.THROW: {
Object value = stack[stackTop];
if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
int sourceLine = getIndex(iCode, frame.pc);
throwable = new JavaScriptException(value,
frame.idata.itsSourceFile,
sourceLine);
break withoutExceptions;
}
case Token.RETHROW: {
indexReg += frame.localShift;
throwable = stack[indexReg];
break withoutExceptions;
}
case Token.GE :
case Token.LE :
case Token.GT :
case Token.LT : {
--stackTop;
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
boolean valBln;
object_compare:
{
number_compare:
{
double rDbl, lDbl;
if (rhs == DBL_MRK) {
rDbl = sDbl[stackTop + 1];
lDbl = stack_double(frame, stackTop);
} else if (lhs == DBL_MRK) {
rDbl = ScriptRuntime.toNumber(rhs);
lDbl = sDbl[stackTop];
} else {
break number_compare;
}
switch (op) {
case Token.GE:
valBln = (lDbl >= rDbl);
break object_compare;
case Token.LE:
valBln = (lDbl <= rDbl);
break object_compare;
case Token.GT:
valBln = (lDbl > rDbl);
break object_compare;
case Token.LT:
valBln = (lDbl < rDbl);
break object_compare;
default:
throw Kit.codeBug();
}
}
switch (op) {
case Token.GE:
valBln = ScriptRuntime.cmp_LE(rhs, lhs);
break;
case Token.LE:
valBln = ScriptRuntime.cmp_LE(lhs, rhs);
break;
case Token.GT:
valBln = ScriptRuntime.cmp_LT(rhs, lhs);
break;
case Token.LT:
valBln = ScriptRuntime.cmp_LT(lhs, rhs);
break;
default:
throw Kit.codeBug();
}
}
stack[stackTop] = ScriptRuntime.wrapBoolean(valBln);
continue Loop;
}
case Token.IN :
case Token.INSTANCEOF : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
boolean valBln;
if (op == Token.IN) {
valBln = ScriptRuntime.in(lhs, rhs, cx);
} else {
valBln = ScriptRuntime.instanceOf(lhs, rhs, cx);
}
stack[stackTop] = ScriptRuntime.wrapBoolean(valBln);
continue Loop;
}
case Token.EQ :
case Token.NE : {
--stackTop;
boolean valBln;
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
if (rhs == DBL_MRK) {
if (lhs == DBL_MRK) {
valBln = (sDbl[stackTop] == sDbl[stackTop + 1]);
} else {
valBln = ScriptRuntime.eqNumber(sDbl[stackTop + 1], lhs);
}
} else {
if (lhs == DBL_MRK) {
valBln = ScriptRuntime.eqNumber(sDbl[stackTop], rhs);
} else {
valBln = ScriptRuntime.eq(lhs, rhs);
}
}
valBln ^= (op == Token.NE);
stack[stackTop] = ScriptRuntime.wrapBoolean(valBln);
continue Loop;
}
case Token.SHEQ :
case Token.SHNE : {
--stackTop;
boolean valBln = shallowEquals(stack, sDbl, stackTop);
valBln ^= (op == Token.SHNE);
stack[stackTop] = ScriptRuntime.wrapBoolean(valBln);
continue Loop;
}
case Token.IFNE :
if (stack_boolean(frame, stackTop--)) {
frame.pc += 2;
continue Loop;
}
break jumplessRun;
case Token.IFEQ :
if (!stack_boolean(frame, stackTop--)) {
frame.pc += 2;
continue Loop;
}
break jumplessRun;
case Icode_IFEQ_POP :
if (!stack_boolean(frame, stackTop--)) {
frame.pc += 2;
continue Loop;
}
stack[stackTop--] = null;
break jumplessRun;
case Token.GOTO :
break jumplessRun;
case Icode_GOSUB :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = frame.pc + 2;
break jumplessRun;
case Icode_STARTSUB :
if (stackTop == frame.emptyStackTop + 1) {
// Call from Icode_GOSUB: store return PC address in the local
indexReg += frame.localShift;
stack[indexReg] = stack[stackTop];
sDbl[indexReg] = sDbl[stackTop];
--stackTop;
} else {
// Call from exception handler: exception object is already stored
// in the local
if (stackTop != frame.emptyStackTop) Kit.codeBug();
}
continue Loop;
case Icode_RETSUB : {
// indexReg: local to store return address
if (instructionCounting) {
addInstructionCount(cx, frame, 0);
}
indexReg += frame.localShift;
Object value = stack[indexReg];
if (value != DBL_MRK) {
// Invocation from exception handler, restore object to rethrow
throwable = value;
break withoutExceptions;
}
// Normal return from GOSUB
frame.pc = (int)sDbl[indexReg];
if (instructionCounting) {
frame.pcPrevBranch = frame.pc;
}
continue Loop;
}
case Icode_POP :
stack[stackTop] = null;
stackTop--;
continue Loop;
case Icode_POP_RESULT :
frame.result = stack[stackTop];
frame.resultDbl = sDbl[stackTop];
stack[stackTop] = null;
--stackTop;
continue Loop;
case Icode_DUP :
stack[stackTop + 1] = stack[stackTop];
sDbl[stackTop + 1] = sDbl[stackTop];
stackTop++;
continue Loop;
case Icode_DUP2 :
stack[stackTop + 1] = stack[stackTop - 1];
sDbl[stackTop + 1] = sDbl[stackTop - 1];
stack[stackTop + 2] = stack[stackTop];
sDbl[stackTop + 2] = sDbl[stackTop];
stackTop += 2;
continue Loop;
case Icode_SWAP : {
Object o = stack[stackTop];
stack[stackTop] = stack[stackTop - 1];
stack[stackTop - 1] = o;
double d = sDbl[stackTop];
sDbl[stackTop] = sDbl[stackTop - 1];
sDbl[stackTop - 1] = d;
continue Loop;
}
case Token.RETURN :
frame.result = stack[stackTop];
frame.resultDbl = sDbl[stackTop];
--stackTop;
break Loop;
case Token.RETURN_RESULT :
break Loop;
case Icode_RETUNDEF :
frame.result = undefined;
break Loop;
case Token.BITNOT : {
int rIntValue = stack_int32(frame, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = ~rIntValue;
continue Loop;
}
case Token.BITAND :
case Token.BITOR :
case Token.BITXOR :
case Token.LSH :
case Token.RSH : {
int lIntValue = stack_int32(frame, stackTop-1);
int rIntValue = stack_int32(frame, stackTop);
stack[--stackTop] = DBL_MRK;
switch (op) {
case Token.BITAND:
lIntValue &= rIntValue;
break;
case Token.BITOR:
lIntValue |= rIntValue;
break;
case Token.BITXOR:
lIntValue ^= rIntValue;
break;
case Token.LSH:
lIntValue <<= rIntValue;
break;
case Token.RSH:
lIntValue >>= rIntValue;
break;
}
sDbl[stackTop] = lIntValue;
continue Loop;
}
case Token.URSH : {
double lDbl = stack_double(frame, stackTop-1);
int rIntValue = stack_int32(frame, stackTop) & 0x1F;
stack[--stackTop] = DBL_MRK;
sDbl[stackTop] = ScriptRuntime.toUint32(lDbl) >>> rIntValue;
continue Loop;
}
case Token.NEG :
case Token.POS : {
double rDbl = stack_double(frame, stackTop);
stack[stackTop] = DBL_MRK;
if (op == Token.NEG) {
rDbl = -rDbl;
}
sDbl[stackTop] = rDbl;
continue Loop;
}
case Token.ADD :
--stackTop;
do_add(stack, sDbl, stackTop, cx);
continue Loop;
case Token.SUB :
case Token.MUL :
case Token.DIV :
case Token.MOD : {
double rDbl = stack_double(frame, stackTop);
--stackTop;
double lDbl = stack_double(frame, stackTop);
stack[stackTop] = DBL_MRK;
switch (op) {
case Token.SUB:
lDbl -= rDbl;
break;
case Token.MUL:
lDbl *= rDbl;
break;
case Token.DIV:
lDbl /= rDbl;
break;
case Token.MOD:
lDbl %= rDbl;
break;
}
sDbl[stackTop] = lDbl;
continue Loop;
}
case Token.NOT :
stack[stackTop] = ScriptRuntime.wrapBoolean(
!stack_boolean(frame, stackTop));
continue Loop;
case Token.BINDNAME :
stack[++stackTop] = ScriptRuntime.bind(cx, frame.scope, stringReg);
continue Loop;
case Token.SETNAME : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Scriptable lhs = (Scriptable)stack[stackTop];
stack[stackTop] = ScriptRuntime.setName(lhs, rhs, cx,
frame.scope, stringReg);
continue Loop;
}
case Icode_SETCONST: {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Scriptable lhs = (Scriptable)stack[stackTop];
stack[stackTop] = ScriptRuntime.setConst(lhs, rhs, cx, stringReg);
continue Loop;
}
case Token.DELPROP : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.delete(lhs, rhs, cx);
continue Loop;
}
case Token.GETPROPNOWARN : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getObjectPropNoWarn(lhs, stringReg, cx);
continue Loop;
}
case Token.GETPROP : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getObjectProp(lhs, stringReg, cx);
continue Loop;
}
case Token.SETPROP : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.setObjectProp(lhs, stringReg, rhs,
cx);
continue Loop;
}
case Icode_PROP_INC_DEC : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.propIncrDecr(lhs, stringReg,
cx, iCode[frame.pc]);
++frame.pc;
continue Loop;
}
case Token.GETELEM : {
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) {
lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
}
Object value;
Object id = stack[stackTop + 1];
if (id != DBL_MRK) {
value = ScriptRuntime.getObjectElem(lhs, id, cx);
} else {
double d = sDbl[stackTop + 1];
value = ScriptRuntime.getObjectIndex(lhs, d, cx);
}
stack[stackTop] = value;
continue Loop;
}
case Token.SETELEM : {
stackTop -= 2;
Object rhs = stack[stackTop + 2];
if (rhs == DBL_MRK) {
rhs = ScriptRuntime.wrapNumber(sDbl[stackTop + 2]);
}
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) {
lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
}
Object value;
Object id = stack[stackTop + 1];
if (id != DBL_MRK) {
value = ScriptRuntime.setObjectElem(lhs, id, rhs, cx);
} else {
double d = sDbl[stackTop + 1];
value = ScriptRuntime.setObjectIndex(lhs, d, rhs, cx);
}
stack[stackTop] = value;
continue Loop;
}
case Icode_ELEM_INC_DEC: {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.elemIncrDecr(lhs, rhs, cx,
iCode[frame.pc]);
++frame.pc;
continue Loop;
}
case Token.GET_REF : {
Ref ref = (Ref)stack[stackTop];
stack[stackTop] = ScriptRuntime.refGet(ref, cx);
continue Loop;
}
case Token.SET_REF : {
Object value = stack[stackTop];
if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Ref ref = (Ref)stack[stackTop];
stack[stackTop] = ScriptRuntime.refSet(ref, value, cx);
continue Loop;
}
case Token.DEL_REF : {
Ref ref = (Ref)stack[stackTop];
stack[stackTop] = ScriptRuntime.refDel(ref, cx);
continue Loop;
}
case Icode_REF_INC_DEC : {
Ref ref = (Ref)stack[stackTop];
stack[stackTop] = ScriptRuntime.refIncrDecr(ref, cx, iCode[frame.pc]);
++frame.pc;
continue Loop;
}
case Token.LOCAL_LOAD :
++stackTop;
indexReg += frame.localShift;
stack[stackTop] = stack[indexReg];
sDbl[stackTop] = sDbl[indexReg];
continue Loop;
case Icode_LOCAL_CLEAR :
indexReg += frame.localShift;
stack[indexReg] = null;
continue Loop;
case Icode_NAME_AND_THIS :
// stringReg: name
++stackTop;
stack[stackTop] = ScriptRuntime.getNameFunctionAndThis(stringReg,
cx, frame.scope);
++stackTop;
stack[stackTop] = ScriptRuntime.lastStoredScriptable(cx);
continue Loop;
case Icode_PROP_AND_THIS: {
Object obj = stack[stackTop];
if (obj == DBL_MRK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop]);
// stringReg: property
stack[stackTop] = ScriptRuntime.getPropFunctionAndThis(obj, stringReg,
cx);
++stackTop;
stack[stackTop] = ScriptRuntime.lastStoredScriptable(cx);
continue Loop;
}
case Icode_ELEM_AND_THIS: {
Object obj = stack[stackTop - 1];
if (obj == DBL_MRK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop - 1]);
Object id = stack[stackTop];
if (id == DBL_MRK) id = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop - 1] = ScriptRuntime.getElemFunctionAndThis(obj, id, cx);
stack[stackTop] = ScriptRuntime.lastStoredScriptable(cx);
continue Loop;
}
case Icode_VALUE_AND_THIS : {
Object value = stack[stackTop];
if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getValueFunctionAndThis(value, cx);
++stackTop;
stack[stackTop] = ScriptRuntime.lastStoredScriptable(cx);
continue Loop;
}
case Icode_CALLSPECIAL : {
if (instructionCounting) {
cx.instructionCount += INVOCATION_COST;
}
int callType = iCode[frame.pc] & 0xFF;
boolean isNew = (iCode[frame.pc + 1] != 0);
int sourceLine = getIndex(iCode, frame.pc + 2);
// indexReg: number of arguments
if (isNew) {
// stack change: function arg0 .. argN -> newResult
stackTop -= indexReg;
Object function = stack[stackTop];
if (function == DBL_MRK)
function = ScriptRuntime.wrapNumber(sDbl[stackTop]);
Object[] outArgs = getArgsArray(
stack, sDbl, stackTop + 1, indexReg);
stack[stackTop] = ScriptRuntime.newSpecial(
cx, function, outArgs, frame.scope, callType);
} else {
// stack change: function thisObj arg0 .. argN -> result
stackTop -= 1 + indexReg;
// Call code generation ensure that stack here
// is ... Callable Scriptable
Scriptable functionThis = (Scriptable)stack[stackTop + 1];
Callable function = (Callable)stack[stackTop];
Object[] outArgs = getArgsArray(
stack, sDbl, stackTop + 2, indexReg);
stack[stackTop] = ScriptRuntime.callSpecial(
cx, function, functionThis, outArgs,
frame.scope, frame.thisObj, callType,
frame.idata.itsSourceFile, sourceLine);
}
frame.pc += 4;
continue Loop;
}
case Token.CALL :
case Icode_TAIL_CALL :
case Token.REF_CALL : {
if (instructionCounting) {
cx.instructionCount += INVOCATION_COST;
}
// stack change: function thisObj arg0 .. argN -> result
// indexReg: number of arguments
stackTop -= 1 + indexReg;
// CALL generation ensures that fun and funThisObj
// are already Scriptable and Callable objects respectively
Callable fun = (Callable)stack[stackTop];
Scriptable funThisObj = (Scriptable)stack[stackTop + 1];
if (op == Token.REF_CALL) {
Object[] outArgs = getArgsArray(stack, sDbl, stackTop + 2,
indexReg);
stack[stackTop] = ScriptRuntime.callRef(fun, funThisObj,
outArgs, cx);
continue Loop;
}
Scriptable calleeScope = frame.scope;
if (frame.useActivation) {
calleeScope = ScriptableObject.getTopLevelScope(frame.scope);
}
if (fun instanceof InterpretedFunction) {
InterpretedFunction ifun = (InterpretedFunction)fun;
if (frame.fnOrScript.securityDomain == ifun.securityDomain) {
CallFrame callParentFrame = frame;
CallFrame calleeFrame = new CallFrame();
if (op == Icode_TAIL_CALL) {
// In principle tail call can re-use the current
// frame and its stack arrays but it is hard to
// do properly. Any exceptions that can legally
// happen during frame re-initialization including
// StackOverflowException during innocent looking
// System.arraycopy may leave the current frame
// data corrupted leading to undefined behaviour
// in the catch code bellow that unwinds JS stack
// on exceptions. Then there is issue about frame release
// end exceptions there.
// To avoid frame allocation a released frame
// can be cached for re-use which would also benefit
// non-tail calls but it is not clear that this caching
// would gain in performance due to potentially
// bad interaction with GC.
callParentFrame = frame.parentFrame;
// Release the current frame. See Bug #344501 to see why
// it is being done here.
exitFrame(cx, frame, null);
}
initFrame(cx, calleeScope, funThisObj, stack, sDbl,
stackTop + 2, indexReg, ifun, callParentFrame,
calleeFrame);
if (op != Icode_TAIL_CALL) {
frame.savedStackTop = stackTop;
frame.savedCallOp = op;
}
frame = calleeFrame;
continue StateLoop;
}
}
if (fun instanceof NativeContinuation) {
// Jump to the captured continuation
ContinuationJump cjump;
cjump = new ContinuationJump((NativeContinuation)fun, frame);
// continuation result is the first argument if any
// of continuation call
if (indexReg == 0) {
cjump.result = undefined;
} else {
cjump.result = stack[stackTop + 2];
cjump.resultDbl = sDbl[stackTop + 2];
}
// Start the real unwind job
throwable = cjump;
break withoutExceptions;
}
if (fun instanceof IdFunctionObject) {
IdFunctionObject ifun = (IdFunctionObject)fun;
if (NativeContinuation.isContinuationConstructor(ifun)) {
frame.stack[stackTop] = captureContinuation(cx,
frame.parentFrame, false);
continue Loop;
}
// Bug 405654 -- make best effort to keep Function.apply and
// Function.call within this interpreter loop invocation
if (BaseFunction.isApplyOrCall(ifun)) {
Callable applyCallable = ScriptRuntime.getCallable(funThisObj);
if (applyCallable instanceof InterpretedFunction) {
InterpretedFunction iApplyCallable = (InterpretedFunction)applyCallable;
if (frame.fnOrScript.securityDomain == iApplyCallable.securityDomain) {
frame = initFrameForApplyOrCall(cx, frame, indexReg,
stack, sDbl, stackTop, op, calleeScope, ifun,
iApplyCallable);
continue StateLoop;
}
}
}
}
// Bug 447697 -- make best effort to keep __noSuchMethod__ within this
// interpreter loop invocation
if (fun instanceof NoSuchMethodShim) {
// get the shim and the actual method
NoSuchMethodShim noSuchMethodShim = (NoSuchMethodShim) fun;
Callable noSuchMethodMethod = noSuchMethodShim.noSuchMethodMethod;
// if the method is in fact an InterpretedFunction
if (noSuchMethodMethod instanceof InterpretedFunction) {
InterpretedFunction ifun = (InterpretedFunction) noSuchMethodMethod;
if (frame.fnOrScript.securityDomain == ifun.securityDomain) {
frame = initFrameForNoSuchMethod(cx, frame, indexReg, stack, sDbl,
stackTop, op, funThisObj, calleeScope,
noSuchMethodShim, ifun);
continue StateLoop;
}
}
}
cx.lastInterpreterFrame = frame;
frame.savedCallOp = op;
frame.savedStackTop = stackTop;
stack[stackTop] = fun.call(cx, calleeScope, funThisObj,
getArgsArray(stack, sDbl, stackTop + 2, indexReg));
cx.lastInterpreterFrame = null;
continue Loop;
}
case Token.NEW : {
if (instructionCounting) {
cx.instructionCount += INVOCATION_COST;
}
// stack change: function arg0 .. argN -> newResult
// indexReg: number of arguments
stackTop -= indexReg;
Object lhs = stack[stackTop];
if (lhs instanceof InterpretedFunction) {
InterpretedFunction f = (InterpretedFunction)lhs;
if (frame.fnOrScript.securityDomain == f.securityDomain) {
Scriptable newInstance = f.createObject(cx, frame.scope);
CallFrame calleeFrame = new CallFrame();
initFrame(cx, frame.scope, newInstance, stack, sDbl,
stackTop + 1, indexReg, f, frame,
calleeFrame);
stack[stackTop] = newInstance;
frame.savedStackTop = stackTop;
frame.savedCallOp = op;
frame = calleeFrame;
continue StateLoop;
}
}
if (!(lhs instanceof Function)) {
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
throw ScriptRuntime.notFunctionError(lhs);
}
Function fun = (Function)lhs;
if (fun instanceof IdFunctionObject) {
IdFunctionObject ifun = (IdFunctionObject)fun;
if (NativeContinuation.isContinuationConstructor(ifun)) {
frame.stack[stackTop] =
captureContinuation(cx, frame.parentFrame, false);
continue Loop;
}
}
Object[] outArgs = getArgsArray(stack, sDbl, stackTop + 1, indexReg);
stack[stackTop] = fun.construct(cx, frame.scope, outArgs);
continue Loop;
}
case Token.TYPEOF : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.typeof(lhs);
continue Loop;
}
case Icode_TYPEOFNAME :
stack[++stackTop] = ScriptRuntime.typeofName(frame.scope, stringReg);
continue Loop;
case Token.STRING :
stack[++stackTop] = stringReg;
continue Loop;
case Icode_SHORTNUMBER :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = getShort(iCode, frame.pc);
frame.pc += 2;
continue Loop;
case Icode_INTNUMBER :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = getInt(iCode, frame.pc);
frame.pc += 4;
continue Loop;
case Token.NUMBER :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = frame.idata.itsDoubleTable[indexReg];
continue Loop;
case Token.NAME :
stack[++stackTop] = ScriptRuntime.name(cx, frame.scope, stringReg);
continue Loop;
case Icode_NAME_INC_DEC :
stack[++stackTop] = ScriptRuntime.nameIncrDecr(frame.scope, stringReg,
cx, iCode[frame.pc]);
++frame.pc;
continue Loop;
case Icode_SETCONSTVAR1:
indexReg = iCode[frame.pc++];
// fallthrough
case Token.SETCONSTVAR :
if (!frame.useActivation) {
if ((varAttributes[indexReg] & ScriptableObject.READONLY) == 0) {
throw Context.reportRuntimeError1("msg.var.redecl",
frame.idata.argNames[indexReg]);
}
if ((varAttributes[indexReg] & ScriptableObject.UNINITIALIZED_CONST)
!= 0)
{
vars[indexReg] = stack[stackTop];
varAttributes[indexReg] &= ~ScriptableObject.UNINITIALIZED_CONST;
varDbls[indexReg] = sDbl[stackTop];
}
} else {
Object val = stack[stackTop];
if (val == DBL_MRK) val = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stringReg = frame.idata.argNames[indexReg];
if (frame.scope instanceof ConstProperties) {
ConstProperties cp = (ConstProperties)frame.scope;
cp.putConst(stringReg, frame.scope, val);
} else
throw Kit.codeBug();
}
continue Loop;
case Icode_SETVAR1:
indexReg = iCode[frame.pc++];
// fallthrough
case Token.SETVAR :
if (!frame.useActivation) {
if ((varAttributes[indexReg] & ScriptableObject.READONLY) == 0) {
vars[indexReg] = stack[stackTop];
varDbls[indexReg] = sDbl[stackTop];
}
} else {
Object val = stack[stackTop];
if (val == DBL_MRK) val = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stringReg = frame.idata.argNames[indexReg];
frame.scope.put(stringReg, frame.scope, val);
}
continue Loop;
case Icode_GETVAR1:
indexReg = iCode[frame.pc++];
// fallthrough
case Token.GETVAR :
++stackTop;
if (!frame.useActivation) {
stack[stackTop] = vars[indexReg];
sDbl[stackTop] = varDbls[indexReg];
} else {
stringReg = frame.idata.argNames[indexReg];
stack[stackTop] = frame.scope.get(stringReg, frame.scope);
}
continue Loop;
case Icode_VAR_INC_DEC : {
// indexReg : varindex
++stackTop;
int incrDecrMask = iCode[frame.pc];
if (!frame.useActivation) {
stack[stackTop] = DBL_MRK;
Object varValue = vars[indexReg];
double d;
if (varValue == DBL_MRK) {
d = varDbls[indexReg];
} else {
d = ScriptRuntime.toNumber(varValue);
vars[indexReg] = DBL_MRK;
}
double d2 = ((incrDecrMask & Node.DECR_FLAG) == 0)
? d + 1.0 : d - 1.0;
varDbls[indexReg] = d2;
sDbl[stackTop] = ((incrDecrMask & Node.POST_FLAG) == 0) ? d2 : d;
} else {
String varName = frame.idata.argNames[indexReg];
stack[stackTop] = ScriptRuntime.nameIncrDecr(frame.scope, varName,
cx, incrDecrMask);
}
++frame.pc;
continue Loop;
}
case Icode_ZERO :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = 0;
continue Loop;
case Icode_ONE :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = 1;
continue Loop;
case Token.NULL :
stack[++stackTop] = null;
continue Loop;
case Token.THIS :
stack[++stackTop] = frame.thisObj;
continue Loop;
case Token.THISFN :
stack[++stackTop] = frame.fnOrScript;
continue Loop;
case Token.FALSE :
stack[++stackTop] = Boolean.FALSE;
continue Loop;
case Token.TRUE :
stack[++stackTop] = Boolean.TRUE;
continue Loop;
case Icode_UNDEF :
stack[++stackTop] = undefined;
continue Loop;
case Token.ENTERWITH : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
frame.scope = ScriptRuntime.enterWith(lhs, cx, frame.scope);
continue Loop;
}
case Token.LEAVEWITH :
frame.scope = ScriptRuntime.leaveWith(frame.scope);
continue Loop;
case Token.CATCH_SCOPE : {
// stack top: exception object
// stringReg: name of exception variable
// indexReg: local for exception scope
--stackTop;
indexReg += frame.localShift;
boolean afterFirstScope = (frame.idata.itsICode[frame.pc] != 0);
Throwable caughtException = (Throwable)stack[stackTop + 1];
Scriptable lastCatchScope;
if (!afterFirstScope) {
lastCatchScope = null;
} else {
lastCatchScope = (Scriptable)stack[indexReg];
}
stack[indexReg] = ScriptRuntime.newCatchScope(caughtException,
lastCatchScope, stringReg,
cx, frame.scope);
++frame.pc;
continue Loop;
}
case Token.ENUM_INIT_KEYS :
case Token.ENUM_INIT_VALUES :
case Token.ENUM_INIT_ARRAY : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
indexReg += frame.localShift;
int enumType = op == Token.ENUM_INIT_KEYS
? ScriptRuntime.ENUMERATE_KEYS :
op == Token.ENUM_INIT_VALUES
? ScriptRuntime.ENUMERATE_VALUES :
ScriptRuntime.ENUMERATE_ARRAY;
stack[indexReg] = ScriptRuntime.enumInit(lhs, cx, enumType);
continue Loop;
}
case Token.ENUM_NEXT :
case Token.ENUM_ID : {
indexReg += frame.localShift;
Object val = stack[indexReg];
++stackTop;
stack[stackTop] = (op == Token.ENUM_NEXT)
? (Object)ScriptRuntime.enumNext(val)
: (Object)ScriptRuntime.enumId(val, cx);
continue Loop;
}
case Token.REF_SPECIAL : {
//stringReg: name of special property
Object obj = stack[stackTop];
if (obj == DBL_MRK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.specialRef(obj, stringReg, cx);
continue Loop;
}
case Token.REF_MEMBER: {
//indexReg: flags
Object elem = stack[stackTop];
if (elem == DBL_MRK) elem = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Object obj = stack[stackTop];
if (obj == DBL_MRK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.memberRef(obj, elem, cx, indexReg);
continue Loop;
}
case Token.REF_NS_MEMBER: {
//indexReg: flags
Object elem = stack[stackTop];
if (elem == DBL_MRK) elem = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Object ns = stack[stackTop];
if (ns == DBL_MRK) ns = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Object obj = stack[stackTop];
if (obj == DBL_MRK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.memberRef(obj, ns, elem, cx, indexReg);
continue Loop;
}
case Token.REF_NAME: {
//indexReg: flags
Object name = stack[stackTop];
if (name == DBL_MRK) name = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.nameRef(name, cx, frame.scope,
indexReg);
continue Loop;
}
case Token.REF_NS_NAME: {
//indexReg: flags
Object name = stack[stackTop];
if (name == DBL_MRK) name = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Object ns = stack[stackTop];
if (ns == DBL_MRK) ns = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.nameRef(ns, name, cx, frame.scope,
indexReg);
continue Loop;
}
case Icode_SCOPE_LOAD :
indexReg += frame.localShift;
frame.scope = (Scriptable)stack[indexReg];
continue Loop;
case Icode_SCOPE_SAVE :
indexReg += frame.localShift;
stack[indexReg] = frame.scope;
continue Loop;
case Icode_CLOSURE_EXPR :
stack[++stackTop] = InterpretedFunction.createFunction(cx, frame.scope,
frame.fnOrScript,
indexReg);
continue Loop;
case Icode_CLOSURE_STMT :
initFunction(cx, frame.scope, frame.fnOrScript, indexReg);
continue Loop;
case Token.REGEXP :
stack[++stackTop] = frame.scriptRegExps[indexReg];
continue Loop;
case Icode_LITERAL_NEW :
// indexReg: number of values in the literal
++stackTop;
stack[stackTop] = new int[indexReg];
++stackTop;
stack[stackTop] = new Object[indexReg];
sDbl[stackTop] = 0;
continue Loop;
case Icode_LITERAL_SET : {
Object value = stack[stackTop];
if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
int i = (int)sDbl[stackTop];
((Object[])stack[stackTop])[i] = value;
sDbl[stackTop] = i + 1;
continue Loop;
}
case Icode_LITERAL_GETTER : {
Object value = stack[stackTop];
--stackTop;
int i = (int)sDbl[stackTop];
((Object[])stack[stackTop])[i] = value;
((int[])stack[stackTop - 1])[i] = -1;
sDbl[stackTop] = i + 1;
continue Loop;
}
case Icode_LITERAL_SETTER : {
Object value = stack[stackTop];
--stackTop;
int i = (int)sDbl[stackTop];
((Object[])stack[stackTop])[i] = value;
((int[])stack[stackTop - 1])[i] = +1;
sDbl[stackTop] = i + 1;
continue Loop;
}
case Token.ARRAYLIT :
case Icode_SPARE_ARRAYLIT :
case Token.OBJECTLIT : {
Object[] data = (Object[])stack[stackTop];
--stackTop;
int[] getterSetters = (int[])stack[stackTop];
Object val;
if (op == Token.OBJECTLIT) {
Object[] ids = (Object[])frame.idata.literalIds[indexReg];
val = ScriptRuntime.newObjectLiteral(ids, data, getterSetters, cx,
frame.scope);
} else {
int[] skipIndexces = null;
if (op == Icode_SPARE_ARRAYLIT) {
skipIndexces = (int[])frame.idata.literalIds[indexReg];
}
val = ScriptRuntime.newArrayLiteral(data, skipIndexces, cx,
frame.scope);
}
stack[stackTop] = val;
continue Loop;
}
case Icode_ENTERDQ : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
frame.scope = ScriptRuntime.enterDotQuery(lhs, frame.scope);
continue Loop;
}
case Icode_LEAVEDQ : {
boolean valBln = stack_boolean(frame, stackTop);
Object x = ScriptRuntime.updateDotQuery(valBln, frame.scope);
if (x != null) {
stack[stackTop] = x;
frame.scope = ScriptRuntime.leaveDotQuery(frame.scope);
frame.pc += 2;
continue Loop;
}
// reset stack and PC to code after ENTERDQ
--stackTop;
break jumplessRun;
}
case Token.DEFAULTNAMESPACE : {
Object value = stack[stackTop];
if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.setDefaultNamespace(value, cx);
continue Loop;
}
case Token.ESCXMLATTR : {
Object value = stack[stackTop];
if (value != DBL_MRK) {
stack[stackTop] = ScriptRuntime.escapeAttributeValue(value, cx);
}
continue Loop;
}
case Token.ESCXMLTEXT : {
Object value = stack[stackTop];
if (value != DBL_MRK) {
stack[stackTop] = ScriptRuntime.escapeTextValue(value, cx);
}
continue Loop;
}
case Icode_DEBUGGER:
if (frame.debuggerFrame != null) {
frame.debuggerFrame.onDebuggerStatement(cx);
}
- break Loop;
+ continue Loop;
case Icode_LINE :
frame.pcSourceLineStart = frame.pc;
if (frame.debuggerFrame != null) {
int line = getIndex(iCode, frame.pc);
frame.debuggerFrame.onLineChange(cx, line);
}
frame.pc += 2;
continue Loop;
case Icode_REG_IND_C0:
indexReg = 0;
continue Loop;
case Icode_REG_IND_C1:
indexReg = 1;
continue Loop;
case Icode_REG_IND_C2:
indexReg = 2;
continue Loop;
case Icode_REG_IND_C3:
indexReg = 3;
continue Loop;
case Icode_REG_IND_C4:
indexReg = 4;
continue Loop;
case Icode_REG_IND_C5:
indexReg = 5;
continue Loop;
case Icode_REG_IND1:
indexReg = 0xFF & iCode[frame.pc];
++frame.pc;
continue Loop;
case Icode_REG_IND2:
indexReg = getIndex(iCode, frame.pc);
frame.pc += 2;
continue Loop;
case Icode_REG_IND4:
indexReg = getInt(iCode, frame.pc);
frame.pc += 4;
continue Loop;
case Icode_REG_STR_C0:
stringReg = strings[0];
continue Loop;
case Icode_REG_STR_C1:
stringReg = strings[1];
continue Loop;
case Icode_REG_STR_C2:
stringReg = strings[2];
continue Loop;
case Icode_REG_STR_C3:
stringReg = strings[3];
continue Loop;
case Icode_REG_STR1:
stringReg = strings[0xFF & iCode[frame.pc]];
++frame.pc;
continue Loop;
case Icode_REG_STR2:
stringReg = strings[getIndex(iCode, frame.pc)];
frame.pc += 2;
continue Loop;
case Icode_REG_STR4:
stringReg = strings[getInt(iCode, frame.pc)];
frame.pc += 4;
continue Loop;
default :
dumpICode(frame.idata);
throw new RuntimeException(
"Unknown icode : "+op+" @ pc : "+(frame.pc-1));
} // end of interpreter switch
} // end of jumplessRun label block
// This should be reachable only for jump implementation
// when pc points to encoded target offset
if (instructionCounting) {
addInstructionCount(cx, frame, 2);
}
int offset = getShort(iCode, frame.pc);
if (offset != 0) {
// -1 accounts for pc pointing to jump opcode + 1
frame.pc += offset - 1;
} else {
frame.pc = frame.idata.longJumps.
getExistingInt(frame.pc);
}
if (instructionCounting) {
frame.pcPrevBranch = frame.pc;
}
continue Loop;
} // end of Loop: for
exitFrame(cx, frame, null);
interpreterResult = frame.result;
interpreterResultDbl = frame.resultDbl;
if (frame.parentFrame != null) {
frame = frame.parentFrame;
if (frame.frozen) {
frame = frame.cloneFrozen();
}
setCallResult(
frame, interpreterResult, interpreterResultDbl);
interpreterResult = null; // Help GC
continue StateLoop;
}
break StateLoop;
} // end of interpreter withoutExceptions: try
catch (Throwable ex) {
if (throwable != null) {
// This is serious bug and it is better to track it ASAP
ex.printStackTrace(System.err);
throw new IllegalStateException();
}
throwable = ex;
}
// This should be reachable only after above catch or from
// finally when it needs to propagate exception or from
// explicit throw
if (throwable == null) Kit.codeBug();
// Exception type
final int EX_CATCH_STATE = 2; // Can execute JS catch
final int EX_FINALLY_STATE = 1; // Can execute JS finally
final int EX_NO_JS_STATE = 0; // Terminate JS execution
int exState;
ContinuationJump cjump = null;
if (generatorState != null &&
generatorState.operation == NativeGenerator.GENERATOR_CLOSE &&
throwable == generatorState.value)
{
exState = EX_FINALLY_STATE;
} else if (throwable instanceof JavaScriptException) {
exState = EX_CATCH_STATE;
} else if (throwable instanceof EcmaError) {
// an offical ECMA error object,
exState = EX_CATCH_STATE;
} else if (throwable instanceof EvaluatorException) {
exState = EX_CATCH_STATE;
} else if (throwable instanceof RuntimeException) {
exState = cx.hasFeature(Context.FEATURE_ENHANCED_JAVA_ACCESS)
? EX_CATCH_STATE
: EX_FINALLY_STATE;
} else if (throwable instanceof Error) {
exState = cx.hasFeature(Context.FEATURE_ENHANCED_JAVA_ACCESS)
? EX_CATCH_STATE
: EX_NO_JS_STATE;
} else if (throwable instanceof ContinuationJump) {
// It must be ContinuationJump
exState = EX_FINALLY_STATE;
cjump = (ContinuationJump)throwable;
} else {
exState = cx.hasFeature(Context.FEATURE_ENHANCED_JAVA_ACCESS)
? EX_CATCH_STATE
: EX_FINALLY_STATE;
}
if (instructionCounting) {
try {
addInstructionCount(cx, frame, EXCEPTION_COST);
} catch (RuntimeException ex) {
throwable = ex;
exState = EX_FINALLY_STATE;
} catch (Error ex) {
// Error from instruction counting
// => unconditionally terminate JS
throwable = ex;
cjump = null;
exState = EX_NO_JS_STATE;
}
}
if (frame.debuggerFrame != null
&& throwable instanceof RuntimeException)
{
// Call debugger only for RuntimeException
RuntimeException rex = (RuntimeException)throwable;
try {
frame.debuggerFrame.onExceptionThrown(cx, rex);
} catch (Throwable ex) {
// Any exception from debugger
// => unconditionally terminate JS
throwable = ex;
cjump = null;
exState = EX_NO_JS_STATE;
}
}
for (;;) {
if (exState != EX_NO_JS_STATE) {
boolean onlyFinally = (exState != EX_CATCH_STATE);
indexReg = getExceptionHandler(frame, onlyFinally);
if (indexReg >= 0) {
// We caught an exception, restart the loop
// with exception pending the processing at the loop
// start
continue StateLoop;
}
}
// No allowed exception handlers in this frame, unwind
// to parent and try to look there
exitFrame(cx, frame, throwable);
frame = frame.parentFrame;
if (frame == null) { break; }
if (cjump != null && cjump.branchFrame == frame) {
// Continuation branch point was hit,
// restart the state loop to reenter continuation
indexReg = -1;
continue StateLoop;
}
}
// No more frames, rethrow the exception or deal with continuation
if (cjump != null) {
if (cjump.branchFrame != null) {
// The above loop should locate the top frame
Kit.codeBug();
}
if (cjump.capturedFrame != null) {
// Restarting detached continuation
indexReg = -1;
continue StateLoop;
}
// Return continuation result to the caller
interpreterResult = cjump.result;
interpreterResultDbl = cjump.resultDbl;
throwable = null;
}
break StateLoop;
} // end of StateLoop: for(;;)
// Do cleanups/restorations before the final return or throw
if (cx.previousInterpreterInvocations != null
&& cx.previousInterpreterInvocations.size() != 0)
{
cx.lastInterpreterFrame
= cx.previousInterpreterInvocations.pop();
} else {
// It was the last interpreter frame on the stack
cx.lastInterpreterFrame = null;
// Force GC of the value cx.previousInterpreterInvocations
cx.previousInterpreterInvocations = null;
}
if (throwable != null) {
if (throwable instanceof RuntimeException) {
throw (RuntimeException)throwable;
} else {
// Must be instance of Error or code bug
throw (Error)throwable;
}
}
return (interpreterResult != DBL_MRK)
? interpreterResult
: ScriptRuntime.wrapNumber(interpreterResultDbl);
}
/**
* Call __noSuchMethod__.
*/
private static CallFrame initFrameForNoSuchMethod(Context cx,
CallFrame frame, int indexReg, Object[] stack, double[] sDbl,
int stackTop, int op, Scriptable funThisObj, Scriptable calleeScope,
NoSuchMethodShim noSuchMethodShim, InterpretedFunction ifun)
{
// create an args array from the stack
Object[] argsArray = null;
// exactly like getArgsArray except that the first argument
// is the method name from the shim
int shift = stackTop + 2;
Object[] elements = new Object[indexReg];
for (int i=0; i < indexReg; ++i, ++shift) {
Object val = stack[shift];
if (val == UniqueTag.DOUBLE_MARK) {
val = ScriptRuntime.wrapNumber(sDbl[shift]);
}
elements[i] = val;
}
argsArray = new Object[2];
argsArray[0] = noSuchMethodShim.methodName;
argsArray[1] = cx.newArray(calleeScope, elements);
// exactly the same as if it's a regular InterpretedFunction
CallFrame callParentFrame = frame;
CallFrame calleeFrame = new CallFrame();
if (op == Icode_TAIL_CALL) {
callParentFrame = frame.parentFrame;
exitFrame(cx, frame, null);
}
// init the frame with the underlying method with the
// adjusted args array and shim's function
initFrame(cx, calleeScope, funThisObj, argsArray, null,
0, 2, ifun, callParentFrame, calleeFrame);
if (op != Icode_TAIL_CALL) {
frame.savedStackTop = stackTop;
frame.savedCallOp = op;
}
return calleeFrame;
}
private static boolean shallowEquals(Object[] stack, double[] sDbl,
int stackTop)
{
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
final Object DBL_MRK = UniqueTag.DOUBLE_MARK;
double rdbl, ldbl;
if (rhs == DBL_MRK) {
rdbl = sDbl[stackTop + 1];
if (lhs == DBL_MRK) {
ldbl = sDbl[stackTop];
} else if (lhs instanceof Number) {
ldbl = ((Number)lhs).doubleValue();
} else {
return false;
}
} else if (lhs == DBL_MRK) {
ldbl = sDbl[stackTop];
if (rhs == DBL_MRK) {
rdbl = sDbl[stackTop + 1];
} else if (rhs instanceof Number) {
rdbl = ((Number)rhs).doubleValue();
} else {
return false;
}
} else {
return ScriptRuntime.shallowEq(lhs, rhs);
}
return (ldbl == rdbl);
}
private static CallFrame processThrowable(Context cx, Object throwable,
CallFrame frame, int indexReg,
boolean instructionCounting)
{
// Recovering from exception, indexReg contains
// the index of handler
if (indexReg >= 0) {
// Normal exception handler, transfer
// control appropriately
if (frame.frozen) {
// XXX Deal with exceptios!!!
frame = frame.cloneFrozen();
}
int[] table = frame.idata.itsExceptionTable;
frame.pc = table[indexReg + EXCEPTION_HANDLER_SLOT];
if (instructionCounting) {
frame.pcPrevBranch = frame.pc;
}
frame.savedStackTop = frame.emptyStackTop;
int scopeLocal = frame.localShift
+ table[indexReg
+ EXCEPTION_SCOPE_SLOT];
int exLocal = frame.localShift
+ table[indexReg
+ EXCEPTION_LOCAL_SLOT];
frame.scope = (Scriptable)frame.stack[scopeLocal];
frame.stack[exLocal] = throwable;
throwable = null;
} else {
// Continuation restoration
ContinuationJump cjump = (ContinuationJump)throwable;
// Clear throwable to indicate that exceptions are OK
throwable = null;
if (cjump.branchFrame != frame) Kit.codeBug();
// Check that we have at least one frozen frame
// in the case of detached continuation restoration:
// unwind code ensure that
if (cjump.capturedFrame == null) Kit.codeBug();
// Need to rewind branchFrame, capturedFrame
// and all frames in between
int rewindCount = cjump.capturedFrame.frameIndex + 1;
if (cjump.branchFrame != null) {
rewindCount -= cjump.branchFrame.frameIndex;
}
int enterCount = 0;
CallFrame[] enterFrames = null;
CallFrame x = cjump.capturedFrame;
for (int i = 0; i != rewindCount; ++i) {
if (!x.frozen) Kit.codeBug();
if (isFrameEnterExitRequired(x)) {
if (enterFrames == null) {
// Allocate enough space to store the rest
// of rewind frames in case all of them
// would require to enter
enterFrames = new CallFrame[rewindCount
- i];
}
enterFrames[enterCount] = x;
++enterCount;
}
x = x.parentFrame;
}
while (enterCount != 0) {
// execute enter: walk enterFrames in the reverse
// order since they were stored starting from
// the capturedFrame, not branchFrame
--enterCount;
x = enterFrames[enterCount];
enterFrame(cx, x, ScriptRuntime.emptyArgs, true);
}
// Continuation jump is almost done: capturedFrame
// points to the call to the function that captured
// continuation, so clone capturedFrame and
// emulate return that function with the suplied result
frame = cjump.capturedFrame.cloneFrozen();
setCallResult(frame, cjump.result, cjump.resultDbl);
// restart the execution
}
frame.throwable = throwable;
return frame;
}
private static Object freezeGenerator(Context cx, CallFrame frame,
int stackTop,
GeneratorState generatorState)
{
if (generatorState.operation == NativeGenerator.GENERATOR_CLOSE) {
// Error: no yields when generator is closing
throw ScriptRuntime.typeError0("msg.yield.closing");
}
// return to our caller (which should be a method of NativeGenerator)
frame.frozen = true;
frame.result = frame.stack[stackTop];
frame.resultDbl = frame.sDbl[stackTop];
frame.savedStackTop = stackTop;
frame.pc--; // we want to come back here when we resume
ScriptRuntime.exitActivationFunction(cx);
return (frame.result != UniqueTag.DOUBLE_MARK)
? frame.result
: ScriptRuntime.wrapNumber(frame.resultDbl);
}
private static Object thawGenerator(CallFrame frame, int stackTop,
GeneratorState generatorState, int op)
{
// we are resuming execution
frame.frozen = false;
int sourceLine = getIndex(frame.idata.itsICode, frame.pc);
frame.pc += 2; // skip line number data
if (generatorState.operation == NativeGenerator.GENERATOR_THROW) {
// processing a call to <generator>.throw(exception): must
// act as if exception was thrown from resumption point
return new JavaScriptException(generatorState.value,
frame.idata.itsSourceFile,
sourceLine);
}
if (generatorState.operation == NativeGenerator.GENERATOR_CLOSE) {
return generatorState.value;
}
if (generatorState.operation != NativeGenerator.GENERATOR_SEND)
throw Kit.codeBug();
if (op == Token.YIELD)
frame.stack[stackTop] = generatorState.value;
return Scriptable.NOT_FOUND;
}
private static CallFrame initFrameForApplyOrCall(Context cx, CallFrame frame,
int indexReg, Object[] stack, double[] sDbl, int stackTop, int op,
Scriptable calleeScope, IdFunctionObject ifun,
InterpretedFunction iApplyCallable)
{
Scriptable applyThis;
if (indexReg != 0) {
applyThis = ScriptRuntime.toObjectOrNull(cx, stack[stackTop + 2]);
}
else {
applyThis = null;
}
if (applyThis == null) {
// This covers the case of args[0] == (null|undefined) as well.
applyThis = ScriptRuntime.getTopCallScope(cx);
}
if(op == Icode_TAIL_CALL) {
exitFrame(cx, frame, null);
frame = frame.parentFrame;
}
else {
frame.savedStackTop = stackTop;
frame.savedCallOp = op;
}
CallFrame calleeFrame = new CallFrame();
if(BaseFunction.isApply(ifun)) {
Object[] callArgs = indexReg < 2 ? ScriptRuntime.emptyArgs :
ScriptRuntime.getApplyArguments(cx, stack[stackTop + 3]);
initFrame(cx, calleeScope, applyThis, callArgs, null, 0,
callArgs.length, iApplyCallable, frame, calleeFrame);
}
else {
// Shift args left
for(int i = 1; i < indexReg; ++i) {
stack[stackTop + 1 + i] = stack[stackTop + 2 + i];
sDbl[stackTop + 1 + i] = sDbl[stackTop + 2 + i];
}
int argCount = indexReg < 2 ? 0 : indexReg - 1;
initFrame(cx, calleeScope, applyThis, stack, sDbl, stackTop + 2,
argCount, iApplyCallable, frame, calleeFrame);
}
frame = calleeFrame;
return frame;
}
private static void initFrame(Context cx, Scriptable callerScope,
Scriptable thisObj,
Object[] args, double[] argsDbl,
int argShift, int argCount,
InterpretedFunction fnOrScript,
CallFrame parentFrame, CallFrame frame)
{
InterpreterData idata = fnOrScript.idata;
boolean useActivation = idata.itsNeedsActivation;
DebugFrame debuggerFrame = null;
if (cx.debugger != null) {
debuggerFrame = cx.debugger.getFrame(cx, idata);
if (debuggerFrame != null) {
useActivation = true;
}
}
if (useActivation) {
// Copy args to new array to pass to enterActivationFunction
// or debuggerFrame.onEnter
if (argsDbl != null) {
args = getArgsArray(args, argsDbl, argShift, argCount);
}
argShift = 0;
argsDbl = null;
}
Scriptable scope;
if (idata.itsFunctionType != 0) {
if (!idata.useDynamicScope) {
scope = fnOrScript.getParentScope();
} else {
scope = callerScope;
}
if (useActivation) {
scope = ScriptRuntime.createFunctionActivation(
fnOrScript, scope, args);
}
} else {
scope = callerScope;
ScriptRuntime.initScript(fnOrScript, thisObj, cx, scope,
fnOrScript.idata.evalScriptFlag);
}
if (idata.itsNestedFunctions != null) {
if (idata.itsFunctionType != 0 && !idata.itsNeedsActivation)
Kit.codeBug();
for (int i = 0; i < idata.itsNestedFunctions.length; i++) {
InterpreterData fdata = idata.itsNestedFunctions[i];
if (fdata.itsFunctionType == FunctionNode.FUNCTION_STATEMENT) {
initFunction(cx, scope, fnOrScript, i);
}
}
}
Scriptable[] scriptRegExps = null;
if (idata.itsRegExpLiterals != null) {
// Wrapped regexps for functions are stored in
// InterpretedFunction
// but for script which should not contain references to scope
// the regexps re-wrapped during each script execution
if (idata.itsFunctionType != 0) {
scriptRegExps = fnOrScript.functionRegExps;
} else {
scriptRegExps = fnOrScript.createRegExpWraps(cx, scope);
}
}
// Initialize args, vars, locals and stack
int emptyStackTop = idata.itsMaxVars + idata.itsMaxLocals - 1;
int maxFrameArray = idata.itsMaxFrameArray;
if (maxFrameArray != emptyStackTop + idata.itsMaxStack + 1)
Kit.codeBug();
Object[] stack;
int[] stackAttributes;
double[] sDbl;
boolean stackReuse;
if (frame.stack != null && maxFrameArray <= frame.stack.length) {
// Reuse stacks from old frame
stackReuse = true;
stack = frame.stack;
stackAttributes = frame.stackAttributes;
sDbl = frame.sDbl;
} else {
stackReuse = false;
stack = new Object[maxFrameArray];
stackAttributes = new int[maxFrameArray];
sDbl = new double[maxFrameArray];
}
int varCount = idata.getParamAndVarCount();
for (int i = 0; i < varCount; i++) {
if (idata.getParamOrVarConst(i))
stackAttributes[i] = ScriptableObject.CONST;
}
int definedArgs = idata.argCount;
if (definedArgs > argCount) { definedArgs = argCount; }
// Fill the frame structure
frame.parentFrame = parentFrame;
frame.frameIndex = (parentFrame == null)
? 0 : parentFrame.frameIndex + 1;
if(frame.frameIndex > cx.getMaximumInterpreterStackDepth())
{
throw Context.reportRuntimeError("Exceeded maximum stack depth");
}
frame.frozen = false;
frame.fnOrScript = fnOrScript;
frame.idata = idata;
frame.stack = stack;
frame.stackAttributes = stackAttributes;
frame.sDbl = sDbl;
frame.varSource = frame;
frame.localShift = idata.itsMaxVars;
frame.emptyStackTop = emptyStackTop;
frame.debuggerFrame = debuggerFrame;
frame.useActivation = useActivation;
frame.thisObj = thisObj;
frame.scriptRegExps = scriptRegExps;
// Initialize initial values of variables that change during
// interpretation.
frame.result = Undefined.instance;
frame.pc = 0;
frame.pcPrevBranch = 0;
frame.pcSourceLineStart = idata.firstLinePC;
frame.scope = scope;
frame.savedStackTop = emptyStackTop;
frame.savedCallOp = 0;
System.arraycopy(args, argShift, stack, 0, definedArgs);
if (argsDbl != null) {
System.arraycopy(argsDbl, argShift, sDbl, 0, definedArgs);
}
for (int i = definedArgs; i != idata.itsMaxVars; ++i) {
stack[i] = Undefined.instance;
}
if (stackReuse) {
// Clean the stack part and space beyond stack if any
// of the old array to allow to GC objects there
for (int i = emptyStackTop + 1; i != stack.length; ++i) {
stack[i] = null;
}
}
enterFrame(cx, frame, args, false);
}
private static boolean isFrameEnterExitRequired(CallFrame frame)
{
return frame.debuggerFrame != null || frame.idata.itsNeedsActivation;
}
private static void enterFrame(Context cx, CallFrame frame, Object[] args,
boolean continuationRestart)
{
boolean usesActivation = frame.idata.itsNeedsActivation;
boolean isDebugged = frame.debuggerFrame != null;
if(usesActivation || isDebugged) {
Scriptable scope = frame.scope;
if(scope == null) {
Kit.codeBug();
} else if (continuationRestart) {
// Walk the parent chain of frame.scope until a NativeCall is
// found. Normally, frame.scope is a NativeCall when called
// from initFrame() for a debugged or activatable function.
// However, when called from interpretLoop() as part of
// restarting a continuation, it can also be a NativeWith if
// the continuation was captured within a "with" or "catch"
// block ("catch" implicitly uses NativeWith to create a scope
// to expose the exception variable).
for(;;) {
if(scope instanceof NativeWith) {
scope = scope.getParentScope();
if (scope == null || (frame.parentFrame != null &&
frame.parentFrame.scope == scope))
{
// If we get here, we didn't find a NativeCall in
// the call chain before reaching parent frame's
// scope. This should not be possible.
Kit.codeBug();
break; // Never reached, but keeps the static analyzer happy about "scope" not being null 5 lines above.
}
}
else {
break;
}
}
}
if (isDebugged) {
frame.debuggerFrame.onEnter(cx, scope, frame.thisObj, args);
}
// Enter activation only when itsNeedsActivation true,
// since debugger should not interfere with activation
// chaining
if (usesActivation) {
ScriptRuntime.enterActivationFunction(cx, scope);
}
}
}
private static void exitFrame(Context cx, CallFrame frame,
Object throwable)
{
if (frame.idata.itsNeedsActivation) {
ScriptRuntime.exitActivationFunction(cx);
}
if (frame.debuggerFrame != null) {
try {
if (throwable instanceof Throwable) {
frame.debuggerFrame.onExit(cx, true, throwable);
} else {
Object result;
ContinuationJump cjump = (ContinuationJump)throwable;
if (cjump == null) {
result = frame.result;
} else {
result = cjump.result;
}
if (result == UniqueTag.DOUBLE_MARK) {
double resultDbl;
if (cjump == null) {
resultDbl = frame.resultDbl;
} else {
resultDbl = cjump.resultDbl;
}
result = ScriptRuntime.wrapNumber(resultDbl);
}
frame.debuggerFrame.onExit(cx, false, result);
}
} catch (Throwable ex) {
System.err.println(
"RHINO USAGE WARNING: onExit terminated with exception");
ex.printStackTrace(System.err);
}
}
}
private static void setCallResult(CallFrame frame,
Object callResult,
double callResultDbl)
{
if (frame.savedCallOp == Token.CALL) {
frame.stack[frame.savedStackTop] = callResult;
frame.sDbl[frame.savedStackTop] = callResultDbl;
} else if (frame.savedCallOp == Token.NEW) {
// If construct returns scriptable,
// then it replaces on stack top saved original instance
// of the object.
if (callResult instanceof Scriptable) {
frame.stack[frame.savedStackTop] = callResult;
}
} else {
Kit.codeBug();
}
frame.savedCallOp = 0;
}
public static NativeContinuation captureContinuation(Context cx) {
if (cx.lastInterpreterFrame == null ||
!(cx.lastInterpreterFrame instanceof CallFrame))
{
throw new IllegalStateException("Interpreter frames not found");
}
return captureContinuation(cx, (CallFrame)cx.lastInterpreterFrame, true);
}
private static NativeContinuation captureContinuation(Context cx, CallFrame frame,
boolean requireContinuationsTopFrame)
{
NativeContinuation c = new NativeContinuation();
ScriptRuntime.setObjectProtoAndParent(
c, ScriptRuntime.getTopCallScope(cx));
// Make sure that all frames are frozen
CallFrame x = frame;
CallFrame outermost = frame;
while (x != null && !x.frozen) {
x.frozen = true;
// Allow to GC unused stack space
for (int i = x.savedStackTop + 1; i != x.stack.length; ++i) {
// Allow to GC unused stack space
x.stack[i] = null;
x.stackAttributes[i] = ScriptableObject.EMPTY;
}
if (x.savedCallOp == Token.CALL) {
// the call will always overwrite the stack top with the result
x.stack[x.savedStackTop] = null;
} else {
if (x.savedCallOp != Token.NEW) Kit.codeBug();
// the new operator uses stack top to store the constructed
// object so it shall not be cleared: see comments in
// setCallResult
}
outermost = x;
x = x.parentFrame;
}
while (outermost.parentFrame != null)
outermost = outermost.parentFrame;
if (requireContinuationsTopFrame && !outermost.isContinuationsTopFrame)
{
throw new IllegalStateException("Cannot capture continuation " +
"from JavaScript code not called directly by " +
"executeScriptWithContinuations or " +
"callFunctionWithContinuations");
}
c.initImplementation(frame);
return c;
}
private static int stack_int32(CallFrame frame, int i)
{
Object x = frame.stack[i];
double value;
if (x == UniqueTag.DOUBLE_MARK) {
value = frame.sDbl[i];
} else {
value = ScriptRuntime.toNumber(x);
}
return ScriptRuntime.toInt32(value);
}
private static double stack_double(CallFrame frame, int i)
{
Object x = frame.stack[i];
if (x != UniqueTag.DOUBLE_MARK) {
return ScriptRuntime.toNumber(x);
} else {
return frame.sDbl[i];
}
}
private static boolean stack_boolean(CallFrame frame, int i)
{
Object x = frame.stack[i];
if (x == Boolean.TRUE) {
return true;
} else if (x == Boolean.FALSE) {
return false;
} else if (x == UniqueTag.DOUBLE_MARK) {
double d = frame.sDbl[i];
return d == d && d != 0.0;
} else if (x == null || x == Undefined.instance) {
return false;
} else if (x instanceof Number) {
double d = ((Number)x).doubleValue();
return (d == d && d != 0.0);
} else if (x instanceof Boolean) {
return ((Boolean)x).booleanValue();
} else {
return ScriptRuntime.toBoolean(x);
}
}
private static void do_add(Object[] stack, double[] sDbl, int stackTop,
Context cx)
{
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
double d;
boolean leftRightOrder;
if (rhs == UniqueTag.DOUBLE_MARK) {
d = sDbl[stackTop + 1];
if (lhs == UniqueTag.DOUBLE_MARK) {
sDbl[stackTop] += d;
return;
}
leftRightOrder = true;
// fallthrough to object + number code
} else if (lhs == UniqueTag.DOUBLE_MARK) {
d = sDbl[stackTop];
lhs = rhs;
leftRightOrder = false;
// fallthrough to object + number code
} else {
if (lhs instanceof Scriptable || rhs instanceof Scriptable) {
stack[stackTop] = ScriptRuntime.add(lhs, rhs, cx);
} else if (lhs instanceof String) {
String lstr = (String)lhs;
String rstr = ScriptRuntime.toString(rhs);
stack[stackTop] = lstr.concat(rstr);
} else if (rhs instanceof String) {
String lstr = ScriptRuntime.toString(lhs);
String rstr = (String)rhs;
stack[stackTop] = lstr.concat(rstr);
} else {
double lDbl = (lhs instanceof Number)
? ((Number)lhs).doubleValue() : ScriptRuntime.toNumber(lhs);
double rDbl = (rhs instanceof Number)
? ((Number)rhs).doubleValue() : ScriptRuntime.toNumber(rhs);
stack[stackTop] = UniqueTag.DOUBLE_MARK;
sDbl[stackTop] = lDbl + rDbl;
}
return;
}
// handle object(lhs) + number(d) code
if (lhs instanceof Scriptable) {
rhs = ScriptRuntime.wrapNumber(d);
if (!leftRightOrder) {
Object tmp = lhs;
lhs = rhs;
rhs = tmp;
}
stack[stackTop] = ScriptRuntime.add(lhs, rhs, cx);
} else if (lhs instanceof String) {
String lstr = (String)lhs;
String rstr = ScriptRuntime.toString(d);
if (leftRightOrder) {
stack[stackTop] = lstr.concat(rstr);
} else {
stack[stackTop] = rstr.concat(lstr);
}
} else {
double lDbl = (lhs instanceof Number)
? ((Number)lhs).doubleValue() : ScriptRuntime.toNumber(lhs);
stack[stackTop] = UniqueTag.DOUBLE_MARK;
sDbl[stackTop] = lDbl + d;
}
}
private static Object[] getArgsArray(Object[] stack, double[] sDbl,
int shift, int count)
{
if (count == 0) {
return ScriptRuntime.emptyArgs;
}
Object[] args = new Object[count];
for (int i = 0; i != count; ++i, ++shift) {
Object val = stack[shift];
if (val == UniqueTag.DOUBLE_MARK) {
val = ScriptRuntime.wrapNumber(sDbl[shift]);
}
args[i] = val;
}
return args;
}
private static void addInstructionCount(Context cx, CallFrame frame,
int extra)
{
cx.instructionCount += frame.pc - frame.pcPrevBranch + extra;
if (cx.instructionCount > cx.instructionThreshold) {
cx.observeInstructionCount(cx.instructionCount);
cx.instructionCount = 0;
}
}
}
| true | true | private static Object interpretLoop(Context cx, CallFrame frame,
Object throwable)
{
// throwable holds exception object to rethrow or catch
// It is also used for continuation restart in which case
// it holds ContinuationJump
final Object DBL_MRK = UniqueTag.DOUBLE_MARK;
final Object undefined = Undefined.instance;
final boolean instructionCounting = (cx.instructionThreshold != 0);
// arbitrary number to add to instructionCount when calling
// other functions
final int INVOCATION_COST = 100;
// arbitrary exception cost for instruction counting
final int EXCEPTION_COST = 100;
String stringReg = null;
int indexReg = -1;
if (cx.lastInterpreterFrame != null) {
// save the top frame from the previous interpretLoop
// invocation on the stack
if (cx.previousInterpreterInvocations == null) {
cx.previousInterpreterInvocations = new ObjArray();
}
cx.previousInterpreterInvocations.push(cx.lastInterpreterFrame);
}
// When restarting continuation throwable is not null and to jump
// to the code that rewind continuation state indexReg should be set
// to -1.
// With the normal call throwable == null and indexReg == -1 allows to
// catch bugs with using indeReg to access array elements before
// initializing indexReg.
GeneratorState generatorState = null;
if (throwable != null) {
if (throwable instanceof GeneratorState) {
generatorState = (GeneratorState) throwable;
// reestablish this call frame
enterFrame(cx, frame, ScriptRuntime.emptyArgs, true);
throwable = null;
} else if (!(throwable instanceof ContinuationJump)) {
// It should be continuation
Kit.codeBug();
}
}
Object interpreterResult = null;
double interpreterResultDbl = 0.0;
StateLoop: for (;;) {
withoutExceptions: try {
if (throwable != null) {
// Need to return both 'frame' and 'throwable' from
// 'processThrowable', so just added a 'throwable'
// member in 'frame'.
frame = processThrowable(cx, throwable, frame, indexReg,
instructionCounting);
throwable = frame.throwable;
frame.throwable = null;
} else {
if (generatorState == null && frame.frozen) Kit.codeBug();
}
// Use local variables for constant values in frame
// for faster access
Object[] stack = frame.stack;
double[] sDbl = frame.sDbl;
Object[] vars = frame.varSource.stack;
double[] varDbls = frame.varSource.sDbl;
int[] varAttributes = frame.varSource.stackAttributes;
byte[] iCode = frame.idata.itsICode;
String[] strings = frame.idata.itsStringTable;
// Use local for stackTop as well. Since execption handlers
// can only exist at statement level where stack is empty,
// it is necessary to save/restore stackTop only across
// function calls and normal returns.
int stackTop = frame.savedStackTop;
// Store new frame in cx which is used for error reporting etc.
cx.lastInterpreterFrame = frame;
Loop: for (;;) {
// Exception handler assumes that PC is already incremented
// pass the instruction start when it searches the
// exception handler
int op = iCode[frame.pc++];
jumplessRun: {
// Back indent to ease implementation reading
switch (op) {
case Icode_GENERATOR: {
if (!frame.frozen) {
// First time encountering this opcode: create new generator
// object and return
frame.pc--; // we want to come back here when we resume
CallFrame generatorFrame = captureFrameForGenerator(frame);
generatorFrame.frozen = true;
NativeGenerator generator = new NativeGenerator(frame.scope,
generatorFrame.fnOrScript, generatorFrame);
frame.result = generator;
break Loop;
} else {
// We are now resuming execution. Fall through to YIELD case.
}
}
// fall through...
case Token.YIELD: {
if (!frame.frozen) {
return freezeGenerator(cx, frame, stackTop, generatorState);
} else {
Object obj = thawGenerator(frame, stackTop, generatorState, op);
if (obj != Scriptable.NOT_FOUND) {
throwable = obj;
break withoutExceptions;
}
continue Loop;
}
}
case Icode_GENERATOR_END: {
// throw StopIteration
frame.frozen = true;
int sourceLine = getIndex(iCode, frame.pc);
generatorState.returnedException = new JavaScriptException(
NativeIterator.getStopIterationObject(frame.scope),
frame.idata.itsSourceFile, sourceLine);
break Loop;
}
case Token.THROW: {
Object value = stack[stackTop];
if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
int sourceLine = getIndex(iCode, frame.pc);
throwable = new JavaScriptException(value,
frame.idata.itsSourceFile,
sourceLine);
break withoutExceptions;
}
case Token.RETHROW: {
indexReg += frame.localShift;
throwable = stack[indexReg];
break withoutExceptions;
}
case Token.GE :
case Token.LE :
case Token.GT :
case Token.LT : {
--stackTop;
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
boolean valBln;
object_compare:
{
number_compare:
{
double rDbl, lDbl;
if (rhs == DBL_MRK) {
rDbl = sDbl[stackTop + 1];
lDbl = stack_double(frame, stackTop);
} else if (lhs == DBL_MRK) {
rDbl = ScriptRuntime.toNumber(rhs);
lDbl = sDbl[stackTop];
} else {
break number_compare;
}
switch (op) {
case Token.GE:
valBln = (lDbl >= rDbl);
break object_compare;
case Token.LE:
valBln = (lDbl <= rDbl);
break object_compare;
case Token.GT:
valBln = (lDbl > rDbl);
break object_compare;
case Token.LT:
valBln = (lDbl < rDbl);
break object_compare;
default:
throw Kit.codeBug();
}
}
switch (op) {
case Token.GE:
valBln = ScriptRuntime.cmp_LE(rhs, lhs);
break;
case Token.LE:
valBln = ScriptRuntime.cmp_LE(lhs, rhs);
break;
case Token.GT:
valBln = ScriptRuntime.cmp_LT(rhs, lhs);
break;
case Token.LT:
valBln = ScriptRuntime.cmp_LT(lhs, rhs);
break;
default:
throw Kit.codeBug();
}
}
stack[stackTop] = ScriptRuntime.wrapBoolean(valBln);
continue Loop;
}
case Token.IN :
case Token.INSTANCEOF : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
boolean valBln;
if (op == Token.IN) {
valBln = ScriptRuntime.in(lhs, rhs, cx);
} else {
valBln = ScriptRuntime.instanceOf(lhs, rhs, cx);
}
stack[stackTop] = ScriptRuntime.wrapBoolean(valBln);
continue Loop;
}
case Token.EQ :
case Token.NE : {
--stackTop;
boolean valBln;
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
if (rhs == DBL_MRK) {
if (lhs == DBL_MRK) {
valBln = (sDbl[stackTop] == sDbl[stackTop + 1]);
} else {
valBln = ScriptRuntime.eqNumber(sDbl[stackTop + 1], lhs);
}
} else {
if (lhs == DBL_MRK) {
valBln = ScriptRuntime.eqNumber(sDbl[stackTop], rhs);
} else {
valBln = ScriptRuntime.eq(lhs, rhs);
}
}
valBln ^= (op == Token.NE);
stack[stackTop] = ScriptRuntime.wrapBoolean(valBln);
continue Loop;
}
case Token.SHEQ :
case Token.SHNE : {
--stackTop;
boolean valBln = shallowEquals(stack, sDbl, stackTop);
valBln ^= (op == Token.SHNE);
stack[stackTop] = ScriptRuntime.wrapBoolean(valBln);
continue Loop;
}
case Token.IFNE :
if (stack_boolean(frame, stackTop--)) {
frame.pc += 2;
continue Loop;
}
break jumplessRun;
case Token.IFEQ :
if (!stack_boolean(frame, stackTop--)) {
frame.pc += 2;
continue Loop;
}
break jumplessRun;
case Icode_IFEQ_POP :
if (!stack_boolean(frame, stackTop--)) {
frame.pc += 2;
continue Loop;
}
stack[stackTop--] = null;
break jumplessRun;
case Token.GOTO :
break jumplessRun;
case Icode_GOSUB :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = frame.pc + 2;
break jumplessRun;
case Icode_STARTSUB :
if (stackTop == frame.emptyStackTop + 1) {
// Call from Icode_GOSUB: store return PC address in the local
indexReg += frame.localShift;
stack[indexReg] = stack[stackTop];
sDbl[indexReg] = sDbl[stackTop];
--stackTop;
} else {
// Call from exception handler: exception object is already stored
// in the local
if (stackTop != frame.emptyStackTop) Kit.codeBug();
}
continue Loop;
case Icode_RETSUB : {
// indexReg: local to store return address
if (instructionCounting) {
addInstructionCount(cx, frame, 0);
}
indexReg += frame.localShift;
Object value = stack[indexReg];
if (value != DBL_MRK) {
// Invocation from exception handler, restore object to rethrow
throwable = value;
break withoutExceptions;
}
// Normal return from GOSUB
frame.pc = (int)sDbl[indexReg];
if (instructionCounting) {
frame.pcPrevBranch = frame.pc;
}
continue Loop;
}
case Icode_POP :
stack[stackTop] = null;
stackTop--;
continue Loop;
case Icode_POP_RESULT :
frame.result = stack[stackTop];
frame.resultDbl = sDbl[stackTop];
stack[stackTop] = null;
--stackTop;
continue Loop;
case Icode_DUP :
stack[stackTop + 1] = stack[stackTop];
sDbl[stackTop + 1] = sDbl[stackTop];
stackTop++;
continue Loop;
case Icode_DUP2 :
stack[stackTop + 1] = stack[stackTop - 1];
sDbl[stackTop + 1] = sDbl[stackTop - 1];
stack[stackTop + 2] = stack[stackTop];
sDbl[stackTop + 2] = sDbl[stackTop];
stackTop += 2;
continue Loop;
case Icode_SWAP : {
Object o = stack[stackTop];
stack[stackTop] = stack[stackTop - 1];
stack[stackTop - 1] = o;
double d = sDbl[stackTop];
sDbl[stackTop] = sDbl[stackTop - 1];
sDbl[stackTop - 1] = d;
continue Loop;
}
case Token.RETURN :
frame.result = stack[stackTop];
frame.resultDbl = sDbl[stackTop];
--stackTop;
break Loop;
case Token.RETURN_RESULT :
break Loop;
case Icode_RETUNDEF :
frame.result = undefined;
break Loop;
case Token.BITNOT : {
int rIntValue = stack_int32(frame, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = ~rIntValue;
continue Loop;
}
case Token.BITAND :
case Token.BITOR :
case Token.BITXOR :
case Token.LSH :
case Token.RSH : {
int lIntValue = stack_int32(frame, stackTop-1);
int rIntValue = stack_int32(frame, stackTop);
stack[--stackTop] = DBL_MRK;
switch (op) {
case Token.BITAND:
lIntValue &= rIntValue;
break;
case Token.BITOR:
lIntValue |= rIntValue;
break;
case Token.BITXOR:
lIntValue ^= rIntValue;
break;
case Token.LSH:
lIntValue <<= rIntValue;
break;
case Token.RSH:
lIntValue >>= rIntValue;
break;
}
sDbl[stackTop] = lIntValue;
continue Loop;
}
case Token.URSH : {
double lDbl = stack_double(frame, stackTop-1);
int rIntValue = stack_int32(frame, stackTop) & 0x1F;
stack[--stackTop] = DBL_MRK;
sDbl[stackTop] = ScriptRuntime.toUint32(lDbl) >>> rIntValue;
continue Loop;
}
case Token.NEG :
case Token.POS : {
double rDbl = stack_double(frame, stackTop);
stack[stackTop] = DBL_MRK;
if (op == Token.NEG) {
rDbl = -rDbl;
}
sDbl[stackTop] = rDbl;
continue Loop;
}
case Token.ADD :
--stackTop;
do_add(stack, sDbl, stackTop, cx);
continue Loop;
case Token.SUB :
case Token.MUL :
case Token.DIV :
case Token.MOD : {
double rDbl = stack_double(frame, stackTop);
--stackTop;
double lDbl = stack_double(frame, stackTop);
stack[stackTop] = DBL_MRK;
switch (op) {
case Token.SUB:
lDbl -= rDbl;
break;
case Token.MUL:
lDbl *= rDbl;
break;
case Token.DIV:
lDbl /= rDbl;
break;
case Token.MOD:
lDbl %= rDbl;
break;
}
sDbl[stackTop] = lDbl;
continue Loop;
}
case Token.NOT :
stack[stackTop] = ScriptRuntime.wrapBoolean(
!stack_boolean(frame, stackTop));
continue Loop;
case Token.BINDNAME :
stack[++stackTop] = ScriptRuntime.bind(cx, frame.scope, stringReg);
continue Loop;
case Token.SETNAME : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Scriptable lhs = (Scriptable)stack[stackTop];
stack[stackTop] = ScriptRuntime.setName(lhs, rhs, cx,
frame.scope, stringReg);
continue Loop;
}
case Icode_SETCONST: {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Scriptable lhs = (Scriptable)stack[stackTop];
stack[stackTop] = ScriptRuntime.setConst(lhs, rhs, cx, stringReg);
continue Loop;
}
case Token.DELPROP : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.delete(lhs, rhs, cx);
continue Loop;
}
case Token.GETPROPNOWARN : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getObjectPropNoWarn(lhs, stringReg, cx);
continue Loop;
}
case Token.GETPROP : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getObjectProp(lhs, stringReg, cx);
continue Loop;
}
case Token.SETPROP : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.setObjectProp(lhs, stringReg, rhs,
cx);
continue Loop;
}
case Icode_PROP_INC_DEC : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.propIncrDecr(lhs, stringReg,
cx, iCode[frame.pc]);
++frame.pc;
continue Loop;
}
case Token.GETELEM : {
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) {
lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
}
Object value;
Object id = stack[stackTop + 1];
if (id != DBL_MRK) {
value = ScriptRuntime.getObjectElem(lhs, id, cx);
} else {
double d = sDbl[stackTop + 1];
value = ScriptRuntime.getObjectIndex(lhs, d, cx);
}
stack[stackTop] = value;
continue Loop;
}
case Token.SETELEM : {
stackTop -= 2;
Object rhs = stack[stackTop + 2];
if (rhs == DBL_MRK) {
rhs = ScriptRuntime.wrapNumber(sDbl[stackTop + 2]);
}
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) {
lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
}
Object value;
Object id = stack[stackTop + 1];
if (id != DBL_MRK) {
value = ScriptRuntime.setObjectElem(lhs, id, rhs, cx);
} else {
double d = sDbl[stackTop + 1];
value = ScriptRuntime.setObjectIndex(lhs, d, rhs, cx);
}
stack[stackTop] = value;
continue Loop;
}
case Icode_ELEM_INC_DEC: {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.elemIncrDecr(lhs, rhs, cx,
iCode[frame.pc]);
++frame.pc;
continue Loop;
}
case Token.GET_REF : {
Ref ref = (Ref)stack[stackTop];
stack[stackTop] = ScriptRuntime.refGet(ref, cx);
continue Loop;
}
case Token.SET_REF : {
Object value = stack[stackTop];
if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Ref ref = (Ref)stack[stackTop];
stack[stackTop] = ScriptRuntime.refSet(ref, value, cx);
continue Loop;
}
case Token.DEL_REF : {
Ref ref = (Ref)stack[stackTop];
stack[stackTop] = ScriptRuntime.refDel(ref, cx);
continue Loop;
}
case Icode_REF_INC_DEC : {
Ref ref = (Ref)stack[stackTop];
stack[stackTop] = ScriptRuntime.refIncrDecr(ref, cx, iCode[frame.pc]);
++frame.pc;
continue Loop;
}
case Token.LOCAL_LOAD :
++stackTop;
indexReg += frame.localShift;
stack[stackTop] = stack[indexReg];
sDbl[stackTop] = sDbl[indexReg];
continue Loop;
case Icode_LOCAL_CLEAR :
indexReg += frame.localShift;
stack[indexReg] = null;
continue Loop;
case Icode_NAME_AND_THIS :
// stringReg: name
++stackTop;
stack[stackTop] = ScriptRuntime.getNameFunctionAndThis(stringReg,
cx, frame.scope);
++stackTop;
stack[stackTop] = ScriptRuntime.lastStoredScriptable(cx);
continue Loop;
case Icode_PROP_AND_THIS: {
Object obj = stack[stackTop];
if (obj == DBL_MRK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop]);
// stringReg: property
stack[stackTop] = ScriptRuntime.getPropFunctionAndThis(obj, stringReg,
cx);
++stackTop;
stack[stackTop] = ScriptRuntime.lastStoredScriptable(cx);
continue Loop;
}
case Icode_ELEM_AND_THIS: {
Object obj = stack[stackTop - 1];
if (obj == DBL_MRK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop - 1]);
Object id = stack[stackTop];
if (id == DBL_MRK) id = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop - 1] = ScriptRuntime.getElemFunctionAndThis(obj, id, cx);
stack[stackTop] = ScriptRuntime.lastStoredScriptable(cx);
continue Loop;
}
case Icode_VALUE_AND_THIS : {
Object value = stack[stackTop];
if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getValueFunctionAndThis(value, cx);
++stackTop;
stack[stackTop] = ScriptRuntime.lastStoredScriptable(cx);
continue Loop;
}
case Icode_CALLSPECIAL : {
if (instructionCounting) {
cx.instructionCount += INVOCATION_COST;
}
int callType = iCode[frame.pc] & 0xFF;
boolean isNew = (iCode[frame.pc + 1] != 0);
int sourceLine = getIndex(iCode, frame.pc + 2);
// indexReg: number of arguments
if (isNew) {
// stack change: function arg0 .. argN -> newResult
stackTop -= indexReg;
Object function = stack[stackTop];
if (function == DBL_MRK)
function = ScriptRuntime.wrapNumber(sDbl[stackTop]);
Object[] outArgs = getArgsArray(
stack, sDbl, stackTop + 1, indexReg);
stack[stackTop] = ScriptRuntime.newSpecial(
cx, function, outArgs, frame.scope, callType);
} else {
// stack change: function thisObj arg0 .. argN -> result
stackTop -= 1 + indexReg;
// Call code generation ensure that stack here
// is ... Callable Scriptable
Scriptable functionThis = (Scriptable)stack[stackTop + 1];
Callable function = (Callable)stack[stackTop];
Object[] outArgs = getArgsArray(
stack, sDbl, stackTop + 2, indexReg);
stack[stackTop] = ScriptRuntime.callSpecial(
cx, function, functionThis, outArgs,
frame.scope, frame.thisObj, callType,
frame.idata.itsSourceFile, sourceLine);
}
frame.pc += 4;
continue Loop;
}
case Token.CALL :
case Icode_TAIL_CALL :
case Token.REF_CALL : {
if (instructionCounting) {
cx.instructionCount += INVOCATION_COST;
}
// stack change: function thisObj arg0 .. argN -> result
// indexReg: number of arguments
stackTop -= 1 + indexReg;
// CALL generation ensures that fun and funThisObj
// are already Scriptable and Callable objects respectively
Callable fun = (Callable)stack[stackTop];
Scriptable funThisObj = (Scriptable)stack[stackTop + 1];
if (op == Token.REF_CALL) {
Object[] outArgs = getArgsArray(stack, sDbl, stackTop + 2,
indexReg);
stack[stackTop] = ScriptRuntime.callRef(fun, funThisObj,
outArgs, cx);
continue Loop;
}
Scriptable calleeScope = frame.scope;
if (frame.useActivation) {
calleeScope = ScriptableObject.getTopLevelScope(frame.scope);
}
if (fun instanceof InterpretedFunction) {
InterpretedFunction ifun = (InterpretedFunction)fun;
if (frame.fnOrScript.securityDomain == ifun.securityDomain) {
CallFrame callParentFrame = frame;
CallFrame calleeFrame = new CallFrame();
if (op == Icode_TAIL_CALL) {
// In principle tail call can re-use the current
// frame and its stack arrays but it is hard to
// do properly. Any exceptions that can legally
// happen during frame re-initialization including
// StackOverflowException during innocent looking
// System.arraycopy may leave the current frame
// data corrupted leading to undefined behaviour
// in the catch code bellow that unwinds JS stack
// on exceptions. Then there is issue about frame release
// end exceptions there.
// To avoid frame allocation a released frame
// can be cached for re-use which would also benefit
// non-tail calls but it is not clear that this caching
// would gain in performance due to potentially
// bad interaction with GC.
callParentFrame = frame.parentFrame;
// Release the current frame. See Bug #344501 to see why
// it is being done here.
exitFrame(cx, frame, null);
}
initFrame(cx, calleeScope, funThisObj, stack, sDbl,
stackTop + 2, indexReg, ifun, callParentFrame,
calleeFrame);
if (op != Icode_TAIL_CALL) {
frame.savedStackTop = stackTop;
frame.savedCallOp = op;
}
frame = calleeFrame;
continue StateLoop;
}
}
if (fun instanceof NativeContinuation) {
// Jump to the captured continuation
ContinuationJump cjump;
cjump = new ContinuationJump((NativeContinuation)fun, frame);
// continuation result is the first argument if any
// of continuation call
if (indexReg == 0) {
cjump.result = undefined;
} else {
cjump.result = stack[stackTop + 2];
cjump.resultDbl = sDbl[stackTop + 2];
}
// Start the real unwind job
throwable = cjump;
break withoutExceptions;
}
if (fun instanceof IdFunctionObject) {
IdFunctionObject ifun = (IdFunctionObject)fun;
if (NativeContinuation.isContinuationConstructor(ifun)) {
frame.stack[stackTop] = captureContinuation(cx,
frame.parentFrame, false);
continue Loop;
}
// Bug 405654 -- make best effort to keep Function.apply and
// Function.call within this interpreter loop invocation
if (BaseFunction.isApplyOrCall(ifun)) {
Callable applyCallable = ScriptRuntime.getCallable(funThisObj);
if (applyCallable instanceof InterpretedFunction) {
InterpretedFunction iApplyCallable = (InterpretedFunction)applyCallable;
if (frame.fnOrScript.securityDomain == iApplyCallable.securityDomain) {
frame = initFrameForApplyOrCall(cx, frame, indexReg,
stack, sDbl, stackTop, op, calleeScope, ifun,
iApplyCallable);
continue StateLoop;
}
}
}
}
// Bug 447697 -- make best effort to keep __noSuchMethod__ within this
// interpreter loop invocation
if (fun instanceof NoSuchMethodShim) {
// get the shim and the actual method
NoSuchMethodShim noSuchMethodShim = (NoSuchMethodShim) fun;
Callable noSuchMethodMethod = noSuchMethodShim.noSuchMethodMethod;
// if the method is in fact an InterpretedFunction
if (noSuchMethodMethod instanceof InterpretedFunction) {
InterpretedFunction ifun = (InterpretedFunction) noSuchMethodMethod;
if (frame.fnOrScript.securityDomain == ifun.securityDomain) {
frame = initFrameForNoSuchMethod(cx, frame, indexReg, stack, sDbl,
stackTop, op, funThisObj, calleeScope,
noSuchMethodShim, ifun);
continue StateLoop;
}
}
}
cx.lastInterpreterFrame = frame;
frame.savedCallOp = op;
frame.savedStackTop = stackTop;
stack[stackTop] = fun.call(cx, calleeScope, funThisObj,
getArgsArray(stack, sDbl, stackTop + 2, indexReg));
cx.lastInterpreterFrame = null;
continue Loop;
}
case Token.NEW : {
if (instructionCounting) {
cx.instructionCount += INVOCATION_COST;
}
// stack change: function arg0 .. argN -> newResult
// indexReg: number of arguments
stackTop -= indexReg;
Object lhs = stack[stackTop];
if (lhs instanceof InterpretedFunction) {
InterpretedFunction f = (InterpretedFunction)lhs;
if (frame.fnOrScript.securityDomain == f.securityDomain) {
Scriptable newInstance = f.createObject(cx, frame.scope);
CallFrame calleeFrame = new CallFrame();
initFrame(cx, frame.scope, newInstance, stack, sDbl,
stackTop + 1, indexReg, f, frame,
calleeFrame);
stack[stackTop] = newInstance;
frame.savedStackTop = stackTop;
frame.savedCallOp = op;
frame = calleeFrame;
continue StateLoop;
}
}
if (!(lhs instanceof Function)) {
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
throw ScriptRuntime.notFunctionError(lhs);
}
Function fun = (Function)lhs;
if (fun instanceof IdFunctionObject) {
IdFunctionObject ifun = (IdFunctionObject)fun;
if (NativeContinuation.isContinuationConstructor(ifun)) {
frame.stack[stackTop] =
captureContinuation(cx, frame.parentFrame, false);
continue Loop;
}
}
Object[] outArgs = getArgsArray(stack, sDbl, stackTop + 1, indexReg);
stack[stackTop] = fun.construct(cx, frame.scope, outArgs);
continue Loop;
}
case Token.TYPEOF : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.typeof(lhs);
continue Loop;
}
case Icode_TYPEOFNAME :
stack[++stackTop] = ScriptRuntime.typeofName(frame.scope, stringReg);
continue Loop;
case Token.STRING :
stack[++stackTop] = stringReg;
continue Loop;
case Icode_SHORTNUMBER :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = getShort(iCode, frame.pc);
frame.pc += 2;
continue Loop;
case Icode_INTNUMBER :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = getInt(iCode, frame.pc);
frame.pc += 4;
continue Loop;
case Token.NUMBER :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = frame.idata.itsDoubleTable[indexReg];
continue Loop;
case Token.NAME :
stack[++stackTop] = ScriptRuntime.name(cx, frame.scope, stringReg);
continue Loop;
case Icode_NAME_INC_DEC :
stack[++stackTop] = ScriptRuntime.nameIncrDecr(frame.scope, stringReg,
cx, iCode[frame.pc]);
++frame.pc;
continue Loop;
case Icode_SETCONSTVAR1:
indexReg = iCode[frame.pc++];
// fallthrough
case Token.SETCONSTVAR :
if (!frame.useActivation) {
if ((varAttributes[indexReg] & ScriptableObject.READONLY) == 0) {
throw Context.reportRuntimeError1("msg.var.redecl",
frame.idata.argNames[indexReg]);
}
if ((varAttributes[indexReg] & ScriptableObject.UNINITIALIZED_CONST)
!= 0)
{
vars[indexReg] = stack[stackTop];
varAttributes[indexReg] &= ~ScriptableObject.UNINITIALIZED_CONST;
varDbls[indexReg] = sDbl[stackTop];
}
} else {
Object val = stack[stackTop];
if (val == DBL_MRK) val = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stringReg = frame.idata.argNames[indexReg];
if (frame.scope instanceof ConstProperties) {
ConstProperties cp = (ConstProperties)frame.scope;
cp.putConst(stringReg, frame.scope, val);
} else
throw Kit.codeBug();
}
continue Loop;
case Icode_SETVAR1:
indexReg = iCode[frame.pc++];
// fallthrough
case Token.SETVAR :
if (!frame.useActivation) {
if ((varAttributes[indexReg] & ScriptableObject.READONLY) == 0) {
vars[indexReg] = stack[stackTop];
varDbls[indexReg] = sDbl[stackTop];
}
} else {
Object val = stack[stackTop];
if (val == DBL_MRK) val = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stringReg = frame.idata.argNames[indexReg];
frame.scope.put(stringReg, frame.scope, val);
}
continue Loop;
case Icode_GETVAR1:
indexReg = iCode[frame.pc++];
// fallthrough
case Token.GETVAR :
++stackTop;
if (!frame.useActivation) {
stack[stackTop] = vars[indexReg];
sDbl[stackTop] = varDbls[indexReg];
} else {
stringReg = frame.idata.argNames[indexReg];
stack[stackTop] = frame.scope.get(stringReg, frame.scope);
}
continue Loop;
case Icode_VAR_INC_DEC : {
// indexReg : varindex
++stackTop;
int incrDecrMask = iCode[frame.pc];
if (!frame.useActivation) {
stack[stackTop] = DBL_MRK;
Object varValue = vars[indexReg];
double d;
if (varValue == DBL_MRK) {
d = varDbls[indexReg];
} else {
d = ScriptRuntime.toNumber(varValue);
vars[indexReg] = DBL_MRK;
}
double d2 = ((incrDecrMask & Node.DECR_FLAG) == 0)
? d + 1.0 : d - 1.0;
varDbls[indexReg] = d2;
sDbl[stackTop] = ((incrDecrMask & Node.POST_FLAG) == 0) ? d2 : d;
} else {
String varName = frame.idata.argNames[indexReg];
stack[stackTop] = ScriptRuntime.nameIncrDecr(frame.scope, varName,
cx, incrDecrMask);
}
++frame.pc;
continue Loop;
}
case Icode_ZERO :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = 0;
continue Loop;
case Icode_ONE :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = 1;
continue Loop;
case Token.NULL :
stack[++stackTop] = null;
continue Loop;
case Token.THIS :
stack[++stackTop] = frame.thisObj;
continue Loop;
case Token.THISFN :
stack[++stackTop] = frame.fnOrScript;
continue Loop;
case Token.FALSE :
stack[++stackTop] = Boolean.FALSE;
continue Loop;
case Token.TRUE :
stack[++stackTop] = Boolean.TRUE;
continue Loop;
case Icode_UNDEF :
stack[++stackTop] = undefined;
continue Loop;
case Token.ENTERWITH : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
frame.scope = ScriptRuntime.enterWith(lhs, cx, frame.scope);
continue Loop;
}
case Token.LEAVEWITH :
frame.scope = ScriptRuntime.leaveWith(frame.scope);
continue Loop;
case Token.CATCH_SCOPE : {
// stack top: exception object
// stringReg: name of exception variable
// indexReg: local for exception scope
--stackTop;
indexReg += frame.localShift;
boolean afterFirstScope = (frame.idata.itsICode[frame.pc] != 0);
Throwable caughtException = (Throwable)stack[stackTop + 1];
Scriptable lastCatchScope;
if (!afterFirstScope) {
lastCatchScope = null;
} else {
lastCatchScope = (Scriptable)stack[indexReg];
}
stack[indexReg] = ScriptRuntime.newCatchScope(caughtException,
lastCatchScope, stringReg,
cx, frame.scope);
++frame.pc;
continue Loop;
}
case Token.ENUM_INIT_KEYS :
case Token.ENUM_INIT_VALUES :
case Token.ENUM_INIT_ARRAY : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
indexReg += frame.localShift;
int enumType = op == Token.ENUM_INIT_KEYS
? ScriptRuntime.ENUMERATE_KEYS :
op == Token.ENUM_INIT_VALUES
? ScriptRuntime.ENUMERATE_VALUES :
ScriptRuntime.ENUMERATE_ARRAY;
stack[indexReg] = ScriptRuntime.enumInit(lhs, cx, enumType);
continue Loop;
}
case Token.ENUM_NEXT :
case Token.ENUM_ID : {
indexReg += frame.localShift;
Object val = stack[indexReg];
++stackTop;
stack[stackTop] = (op == Token.ENUM_NEXT)
? (Object)ScriptRuntime.enumNext(val)
: (Object)ScriptRuntime.enumId(val, cx);
continue Loop;
}
case Token.REF_SPECIAL : {
//stringReg: name of special property
Object obj = stack[stackTop];
if (obj == DBL_MRK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.specialRef(obj, stringReg, cx);
continue Loop;
}
case Token.REF_MEMBER: {
//indexReg: flags
Object elem = stack[stackTop];
if (elem == DBL_MRK) elem = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Object obj = stack[stackTop];
if (obj == DBL_MRK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.memberRef(obj, elem, cx, indexReg);
continue Loop;
}
case Token.REF_NS_MEMBER: {
//indexReg: flags
Object elem = stack[stackTop];
if (elem == DBL_MRK) elem = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Object ns = stack[stackTop];
if (ns == DBL_MRK) ns = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Object obj = stack[stackTop];
if (obj == DBL_MRK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.memberRef(obj, ns, elem, cx, indexReg);
continue Loop;
}
case Token.REF_NAME: {
//indexReg: flags
Object name = stack[stackTop];
if (name == DBL_MRK) name = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.nameRef(name, cx, frame.scope,
indexReg);
continue Loop;
}
case Token.REF_NS_NAME: {
//indexReg: flags
Object name = stack[stackTop];
if (name == DBL_MRK) name = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Object ns = stack[stackTop];
if (ns == DBL_MRK) ns = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.nameRef(ns, name, cx, frame.scope,
indexReg);
continue Loop;
}
case Icode_SCOPE_LOAD :
indexReg += frame.localShift;
frame.scope = (Scriptable)stack[indexReg];
continue Loop;
case Icode_SCOPE_SAVE :
indexReg += frame.localShift;
stack[indexReg] = frame.scope;
continue Loop;
case Icode_CLOSURE_EXPR :
stack[++stackTop] = InterpretedFunction.createFunction(cx, frame.scope,
frame.fnOrScript,
indexReg);
continue Loop;
case Icode_CLOSURE_STMT :
initFunction(cx, frame.scope, frame.fnOrScript, indexReg);
continue Loop;
case Token.REGEXP :
stack[++stackTop] = frame.scriptRegExps[indexReg];
continue Loop;
case Icode_LITERAL_NEW :
// indexReg: number of values in the literal
++stackTop;
stack[stackTop] = new int[indexReg];
++stackTop;
stack[stackTop] = new Object[indexReg];
sDbl[stackTop] = 0;
continue Loop;
case Icode_LITERAL_SET : {
Object value = stack[stackTop];
if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
int i = (int)sDbl[stackTop];
((Object[])stack[stackTop])[i] = value;
sDbl[stackTop] = i + 1;
continue Loop;
}
case Icode_LITERAL_GETTER : {
Object value = stack[stackTop];
--stackTop;
int i = (int)sDbl[stackTop];
((Object[])stack[stackTop])[i] = value;
((int[])stack[stackTop - 1])[i] = -1;
sDbl[stackTop] = i + 1;
continue Loop;
}
case Icode_LITERAL_SETTER : {
Object value = stack[stackTop];
--stackTop;
int i = (int)sDbl[stackTop];
((Object[])stack[stackTop])[i] = value;
((int[])stack[stackTop - 1])[i] = +1;
sDbl[stackTop] = i + 1;
continue Loop;
}
case Token.ARRAYLIT :
case Icode_SPARE_ARRAYLIT :
case Token.OBJECTLIT : {
Object[] data = (Object[])stack[stackTop];
--stackTop;
int[] getterSetters = (int[])stack[stackTop];
Object val;
if (op == Token.OBJECTLIT) {
Object[] ids = (Object[])frame.idata.literalIds[indexReg];
val = ScriptRuntime.newObjectLiteral(ids, data, getterSetters, cx,
frame.scope);
} else {
int[] skipIndexces = null;
if (op == Icode_SPARE_ARRAYLIT) {
skipIndexces = (int[])frame.idata.literalIds[indexReg];
}
val = ScriptRuntime.newArrayLiteral(data, skipIndexces, cx,
frame.scope);
}
stack[stackTop] = val;
continue Loop;
}
case Icode_ENTERDQ : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
frame.scope = ScriptRuntime.enterDotQuery(lhs, frame.scope);
continue Loop;
}
case Icode_LEAVEDQ : {
boolean valBln = stack_boolean(frame, stackTop);
Object x = ScriptRuntime.updateDotQuery(valBln, frame.scope);
if (x != null) {
stack[stackTop] = x;
frame.scope = ScriptRuntime.leaveDotQuery(frame.scope);
frame.pc += 2;
continue Loop;
}
// reset stack and PC to code after ENTERDQ
--stackTop;
break jumplessRun;
}
case Token.DEFAULTNAMESPACE : {
Object value = stack[stackTop];
if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.setDefaultNamespace(value, cx);
continue Loop;
}
case Token.ESCXMLATTR : {
Object value = stack[stackTop];
if (value != DBL_MRK) {
stack[stackTop] = ScriptRuntime.escapeAttributeValue(value, cx);
}
continue Loop;
}
case Token.ESCXMLTEXT : {
Object value = stack[stackTop];
if (value != DBL_MRK) {
stack[stackTop] = ScriptRuntime.escapeTextValue(value, cx);
}
continue Loop;
}
case Icode_DEBUGGER:
if (frame.debuggerFrame != null) {
frame.debuggerFrame.onDebuggerStatement(cx);
}
break Loop;
case Icode_LINE :
frame.pcSourceLineStart = frame.pc;
if (frame.debuggerFrame != null) {
int line = getIndex(iCode, frame.pc);
frame.debuggerFrame.onLineChange(cx, line);
}
frame.pc += 2;
continue Loop;
case Icode_REG_IND_C0:
indexReg = 0;
continue Loop;
case Icode_REG_IND_C1:
indexReg = 1;
continue Loop;
case Icode_REG_IND_C2:
indexReg = 2;
continue Loop;
case Icode_REG_IND_C3:
indexReg = 3;
continue Loop;
case Icode_REG_IND_C4:
indexReg = 4;
continue Loop;
case Icode_REG_IND_C5:
indexReg = 5;
continue Loop;
case Icode_REG_IND1:
indexReg = 0xFF & iCode[frame.pc];
++frame.pc;
continue Loop;
case Icode_REG_IND2:
indexReg = getIndex(iCode, frame.pc);
frame.pc += 2;
continue Loop;
case Icode_REG_IND4:
indexReg = getInt(iCode, frame.pc);
frame.pc += 4;
continue Loop;
case Icode_REG_STR_C0:
stringReg = strings[0];
continue Loop;
case Icode_REG_STR_C1:
stringReg = strings[1];
continue Loop;
case Icode_REG_STR_C2:
stringReg = strings[2];
continue Loop;
case Icode_REG_STR_C3:
stringReg = strings[3];
continue Loop;
case Icode_REG_STR1:
stringReg = strings[0xFF & iCode[frame.pc]];
++frame.pc;
continue Loop;
case Icode_REG_STR2:
stringReg = strings[getIndex(iCode, frame.pc)];
frame.pc += 2;
continue Loop;
case Icode_REG_STR4:
stringReg = strings[getInt(iCode, frame.pc)];
frame.pc += 4;
continue Loop;
default :
dumpICode(frame.idata);
throw new RuntimeException(
"Unknown icode : "+op+" @ pc : "+(frame.pc-1));
} // end of interpreter switch
} // end of jumplessRun label block
// This should be reachable only for jump implementation
// when pc points to encoded target offset
if (instructionCounting) {
addInstructionCount(cx, frame, 2);
}
int offset = getShort(iCode, frame.pc);
if (offset != 0) {
// -1 accounts for pc pointing to jump opcode + 1
frame.pc += offset - 1;
} else {
frame.pc = frame.idata.longJumps.
getExistingInt(frame.pc);
}
if (instructionCounting) {
frame.pcPrevBranch = frame.pc;
}
continue Loop;
} // end of Loop: for
exitFrame(cx, frame, null);
interpreterResult = frame.result;
interpreterResultDbl = frame.resultDbl;
if (frame.parentFrame != null) {
frame = frame.parentFrame;
if (frame.frozen) {
frame = frame.cloneFrozen();
}
setCallResult(
frame, interpreterResult, interpreterResultDbl);
interpreterResult = null; // Help GC
continue StateLoop;
}
break StateLoop;
} // end of interpreter withoutExceptions: try
catch (Throwable ex) {
if (throwable != null) {
// This is serious bug and it is better to track it ASAP
ex.printStackTrace(System.err);
throw new IllegalStateException();
}
throwable = ex;
}
// This should be reachable only after above catch or from
// finally when it needs to propagate exception or from
// explicit throw
if (throwable == null) Kit.codeBug();
// Exception type
final int EX_CATCH_STATE = 2; // Can execute JS catch
final int EX_FINALLY_STATE = 1; // Can execute JS finally
final int EX_NO_JS_STATE = 0; // Terminate JS execution
int exState;
ContinuationJump cjump = null;
if (generatorState != null &&
generatorState.operation == NativeGenerator.GENERATOR_CLOSE &&
throwable == generatorState.value)
{
exState = EX_FINALLY_STATE;
} else if (throwable instanceof JavaScriptException) {
exState = EX_CATCH_STATE;
} else if (throwable instanceof EcmaError) {
// an offical ECMA error object,
exState = EX_CATCH_STATE;
} else if (throwable instanceof EvaluatorException) {
exState = EX_CATCH_STATE;
} else if (throwable instanceof RuntimeException) {
exState = cx.hasFeature(Context.FEATURE_ENHANCED_JAVA_ACCESS)
? EX_CATCH_STATE
: EX_FINALLY_STATE;
} else if (throwable instanceof Error) {
exState = cx.hasFeature(Context.FEATURE_ENHANCED_JAVA_ACCESS)
? EX_CATCH_STATE
: EX_NO_JS_STATE;
} else if (throwable instanceof ContinuationJump) {
// It must be ContinuationJump
exState = EX_FINALLY_STATE;
cjump = (ContinuationJump)throwable;
} else {
exState = cx.hasFeature(Context.FEATURE_ENHANCED_JAVA_ACCESS)
? EX_CATCH_STATE
: EX_FINALLY_STATE;
}
if (instructionCounting) {
try {
addInstructionCount(cx, frame, EXCEPTION_COST);
} catch (RuntimeException ex) {
throwable = ex;
exState = EX_FINALLY_STATE;
} catch (Error ex) {
// Error from instruction counting
// => unconditionally terminate JS
throwable = ex;
cjump = null;
exState = EX_NO_JS_STATE;
}
}
if (frame.debuggerFrame != null
&& throwable instanceof RuntimeException)
{
// Call debugger only for RuntimeException
RuntimeException rex = (RuntimeException)throwable;
try {
frame.debuggerFrame.onExceptionThrown(cx, rex);
} catch (Throwable ex) {
// Any exception from debugger
// => unconditionally terminate JS
throwable = ex;
cjump = null;
exState = EX_NO_JS_STATE;
}
}
for (;;) {
if (exState != EX_NO_JS_STATE) {
boolean onlyFinally = (exState != EX_CATCH_STATE);
indexReg = getExceptionHandler(frame, onlyFinally);
if (indexReg >= 0) {
// We caught an exception, restart the loop
// with exception pending the processing at the loop
// start
continue StateLoop;
}
}
// No allowed exception handlers in this frame, unwind
// to parent and try to look there
exitFrame(cx, frame, throwable);
frame = frame.parentFrame;
if (frame == null) { break; }
if (cjump != null && cjump.branchFrame == frame) {
// Continuation branch point was hit,
// restart the state loop to reenter continuation
indexReg = -1;
continue StateLoop;
}
}
// No more frames, rethrow the exception or deal with continuation
if (cjump != null) {
if (cjump.branchFrame != null) {
// The above loop should locate the top frame
Kit.codeBug();
}
if (cjump.capturedFrame != null) {
// Restarting detached continuation
indexReg = -1;
continue StateLoop;
}
// Return continuation result to the caller
interpreterResult = cjump.result;
interpreterResultDbl = cjump.resultDbl;
throwable = null;
}
break StateLoop;
} // end of StateLoop: for(;;)
// Do cleanups/restorations before the final return or throw
if (cx.previousInterpreterInvocations != null
&& cx.previousInterpreterInvocations.size() != 0)
{
cx.lastInterpreterFrame
= cx.previousInterpreterInvocations.pop();
} else {
// It was the last interpreter frame on the stack
cx.lastInterpreterFrame = null;
// Force GC of the value cx.previousInterpreterInvocations
cx.previousInterpreterInvocations = null;
}
if (throwable != null) {
if (throwable instanceof RuntimeException) {
throw (RuntimeException)throwable;
} else {
// Must be instance of Error or code bug
throw (Error)throwable;
}
}
return (interpreterResult != DBL_MRK)
? interpreterResult
: ScriptRuntime.wrapNumber(interpreterResultDbl);
}
| private static Object interpretLoop(Context cx, CallFrame frame,
Object throwable)
{
// throwable holds exception object to rethrow or catch
// It is also used for continuation restart in which case
// it holds ContinuationJump
final Object DBL_MRK = UniqueTag.DOUBLE_MARK;
final Object undefined = Undefined.instance;
final boolean instructionCounting = (cx.instructionThreshold != 0);
// arbitrary number to add to instructionCount when calling
// other functions
final int INVOCATION_COST = 100;
// arbitrary exception cost for instruction counting
final int EXCEPTION_COST = 100;
String stringReg = null;
int indexReg = -1;
if (cx.lastInterpreterFrame != null) {
// save the top frame from the previous interpretLoop
// invocation on the stack
if (cx.previousInterpreterInvocations == null) {
cx.previousInterpreterInvocations = new ObjArray();
}
cx.previousInterpreterInvocations.push(cx.lastInterpreterFrame);
}
// When restarting continuation throwable is not null and to jump
// to the code that rewind continuation state indexReg should be set
// to -1.
// With the normal call throwable == null and indexReg == -1 allows to
// catch bugs with using indeReg to access array elements before
// initializing indexReg.
GeneratorState generatorState = null;
if (throwable != null) {
if (throwable instanceof GeneratorState) {
generatorState = (GeneratorState) throwable;
// reestablish this call frame
enterFrame(cx, frame, ScriptRuntime.emptyArgs, true);
throwable = null;
} else if (!(throwable instanceof ContinuationJump)) {
// It should be continuation
Kit.codeBug();
}
}
Object interpreterResult = null;
double interpreterResultDbl = 0.0;
StateLoop: for (;;) {
withoutExceptions: try {
if (throwable != null) {
// Need to return both 'frame' and 'throwable' from
// 'processThrowable', so just added a 'throwable'
// member in 'frame'.
frame = processThrowable(cx, throwable, frame, indexReg,
instructionCounting);
throwable = frame.throwable;
frame.throwable = null;
} else {
if (generatorState == null && frame.frozen) Kit.codeBug();
}
// Use local variables for constant values in frame
// for faster access
Object[] stack = frame.stack;
double[] sDbl = frame.sDbl;
Object[] vars = frame.varSource.stack;
double[] varDbls = frame.varSource.sDbl;
int[] varAttributes = frame.varSource.stackAttributes;
byte[] iCode = frame.idata.itsICode;
String[] strings = frame.idata.itsStringTable;
// Use local for stackTop as well. Since execption handlers
// can only exist at statement level where stack is empty,
// it is necessary to save/restore stackTop only across
// function calls and normal returns.
int stackTop = frame.savedStackTop;
// Store new frame in cx which is used for error reporting etc.
cx.lastInterpreterFrame = frame;
Loop: for (;;) {
// Exception handler assumes that PC is already incremented
// pass the instruction start when it searches the
// exception handler
int op = iCode[frame.pc++];
jumplessRun: {
// Back indent to ease implementation reading
switch (op) {
case Icode_GENERATOR: {
if (!frame.frozen) {
// First time encountering this opcode: create new generator
// object and return
frame.pc--; // we want to come back here when we resume
CallFrame generatorFrame = captureFrameForGenerator(frame);
generatorFrame.frozen = true;
NativeGenerator generator = new NativeGenerator(frame.scope,
generatorFrame.fnOrScript, generatorFrame);
frame.result = generator;
break Loop;
} else {
// We are now resuming execution. Fall through to YIELD case.
}
}
// fall through...
case Token.YIELD: {
if (!frame.frozen) {
return freezeGenerator(cx, frame, stackTop, generatorState);
} else {
Object obj = thawGenerator(frame, stackTop, generatorState, op);
if (obj != Scriptable.NOT_FOUND) {
throwable = obj;
break withoutExceptions;
}
continue Loop;
}
}
case Icode_GENERATOR_END: {
// throw StopIteration
frame.frozen = true;
int sourceLine = getIndex(iCode, frame.pc);
generatorState.returnedException = new JavaScriptException(
NativeIterator.getStopIterationObject(frame.scope),
frame.idata.itsSourceFile, sourceLine);
break Loop;
}
case Token.THROW: {
Object value = stack[stackTop];
if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
int sourceLine = getIndex(iCode, frame.pc);
throwable = new JavaScriptException(value,
frame.idata.itsSourceFile,
sourceLine);
break withoutExceptions;
}
case Token.RETHROW: {
indexReg += frame.localShift;
throwable = stack[indexReg];
break withoutExceptions;
}
case Token.GE :
case Token.LE :
case Token.GT :
case Token.LT : {
--stackTop;
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
boolean valBln;
object_compare:
{
number_compare:
{
double rDbl, lDbl;
if (rhs == DBL_MRK) {
rDbl = sDbl[stackTop + 1];
lDbl = stack_double(frame, stackTop);
} else if (lhs == DBL_MRK) {
rDbl = ScriptRuntime.toNumber(rhs);
lDbl = sDbl[stackTop];
} else {
break number_compare;
}
switch (op) {
case Token.GE:
valBln = (lDbl >= rDbl);
break object_compare;
case Token.LE:
valBln = (lDbl <= rDbl);
break object_compare;
case Token.GT:
valBln = (lDbl > rDbl);
break object_compare;
case Token.LT:
valBln = (lDbl < rDbl);
break object_compare;
default:
throw Kit.codeBug();
}
}
switch (op) {
case Token.GE:
valBln = ScriptRuntime.cmp_LE(rhs, lhs);
break;
case Token.LE:
valBln = ScriptRuntime.cmp_LE(lhs, rhs);
break;
case Token.GT:
valBln = ScriptRuntime.cmp_LT(rhs, lhs);
break;
case Token.LT:
valBln = ScriptRuntime.cmp_LT(lhs, rhs);
break;
default:
throw Kit.codeBug();
}
}
stack[stackTop] = ScriptRuntime.wrapBoolean(valBln);
continue Loop;
}
case Token.IN :
case Token.INSTANCEOF : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
boolean valBln;
if (op == Token.IN) {
valBln = ScriptRuntime.in(lhs, rhs, cx);
} else {
valBln = ScriptRuntime.instanceOf(lhs, rhs, cx);
}
stack[stackTop] = ScriptRuntime.wrapBoolean(valBln);
continue Loop;
}
case Token.EQ :
case Token.NE : {
--stackTop;
boolean valBln;
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
if (rhs == DBL_MRK) {
if (lhs == DBL_MRK) {
valBln = (sDbl[stackTop] == sDbl[stackTop + 1]);
} else {
valBln = ScriptRuntime.eqNumber(sDbl[stackTop + 1], lhs);
}
} else {
if (lhs == DBL_MRK) {
valBln = ScriptRuntime.eqNumber(sDbl[stackTop], rhs);
} else {
valBln = ScriptRuntime.eq(lhs, rhs);
}
}
valBln ^= (op == Token.NE);
stack[stackTop] = ScriptRuntime.wrapBoolean(valBln);
continue Loop;
}
case Token.SHEQ :
case Token.SHNE : {
--stackTop;
boolean valBln = shallowEquals(stack, sDbl, stackTop);
valBln ^= (op == Token.SHNE);
stack[stackTop] = ScriptRuntime.wrapBoolean(valBln);
continue Loop;
}
case Token.IFNE :
if (stack_boolean(frame, stackTop--)) {
frame.pc += 2;
continue Loop;
}
break jumplessRun;
case Token.IFEQ :
if (!stack_boolean(frame, stackTop--)) {
frame.pc += 2;
continue Loop;
}
break jumplessRun;
case Icode_IFEQ_POP :
if (!stack_boolean(frame, stackTop--)) {
frame.pc += 2;
continue Loop;
}
stack[stackTop--] = null;
break jumplessRun;
case Token.GOTO :
break jumplessRun;
case Icode_GOSUB :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = frame.pc + 2;
break jumplessRun;
case Icode_STARTSUB :
if (stackTop == frame.emptyStackTop + 1) {
// Call from Icode_GOSUB: store return PC address in the local
indexReg += frame.localShift;
stack[indexReg] = stack[stackTop];
sDbl[indexReg] = sDbl[stackTop];
--stackTop;
} else {
// Call from exception handler: exception object is already stored
// in the local
if (stackTop != frame.emptyStackTop) Kit.codeBug();
}
continue Loop;
case Icode_RETSUB : {
// indexReg: local to store return address
if (instructionCounting) {
addInstructionCount(cx, frame, 0);
}
indexReg += frame.localShift;
Object value = stack[indexReg];
if (value != DBL_MRK) {
// Invocation from exception handler, restore object to rethrow
throwable = value;
break withoutExceptions;
}
// Normal return from GOSUB
frame.pc = (int)sDbl[indexReg];
if (instructionCounting) {
frame.pcPrevBranch = frame.pc;
}
continue Loop;
}
case Icode_POP :
stack[stackTop] = null;
stackTop--;
continue Loop;
case Icode_POP_RESULT :
frame.result = stack[stackTop];
frame.resultDbl = sDbl[stackTop];
stack[stackTop] = null;
--stackTop;
continue Loop;
case Icode_DUP :
stack[stackTop + 1] = stack[stackTop];
sDbl[stackTop + 1] = sDbl[stackTop];
stackTop++;
continue Loop;
case Icode_DUP2 :
stack[stackTop + 1] = stack[stackTop - 1];
sDbl[stackTop + 1] = sDbl[stackTop - 1];
stack[stackTop + 2] = stack[stackTop];
sDbl[stackTop + 2] = sDbl[stackTop];
stackTop += 2;
continue Loop;
case Icode_SWAP : {
Object o = stack[stackTop];
stack[stackTop] = stack[stackTop - 1];
stack[stackTop - 1] = o;
double d = sDbl[stackTop];
sDbl[stackTop] = sDbl[stackTop - 1];
sDbl[stackTop - 1] = d;
continue Loop;
}
case Token.RETURN :
frame.result = stack[stackTop];
frame.resultDbl = sDbl[stackTop];
--stackTop;
break Loop;
case Token.RETURN_RESULT :
break Loop;
case Icode_RETUNDEF :
frame.result = undefined;
break Loop;
case Token.BITNOT : {
int rIntValue = stack_int32(frame, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = ~rIntValue;
continue Loop;
}
case Token.BITAND :
case Token.BITOR :
case Token.BITXOR :
case Token.LSH :
case Token.RSH : {
int lIntValue = stack_int32(frame, stackTop-1);
int rIntValue = stack_int32(frame, stackTop);
stack[--stackTop] = DBL_MRK;
switch (op) {
case Token.BITAND:
lIntValue &= rIntValue;
break;
case Token.BITOR:
lIntValue |= rIntValue;
break;
case Token.BITXOR:
lIntValue ^= rIntValue;
break;
case Token.LSH:
lIntValue <<= rIntValue;
break;
case Token.RSH:
lIntValue >>= rIntValue;
break;
}
sDbl[stackTop] = lIntValue;
continue Loop;
}
case Token.URSH : {
double lDbl = stack_double(frame, stackTop-1);
int rIntValue = stack_int32(frame, stackTop) & 0x1F;
stack[--stackTop] = DBL_MRK;
sDbl[stackTop] = ScriptRuntime.toUint32(lDbl) >>> rIntValue;
continue Loop;
}
case Token.NEG :
case Token.POS : {
double rDbl = stack_double(frame, stackTop);
stack[stackTop] = DBL_MRK;
if (op == Token.NEG) {
rDbl = -rDbl;
}
sDbl[stackTop] = rDbl;
continue Loop;
}
case Token.ADD :
--stackTop;
do_add(stack, sDbl, stackTop, cx);
continue Loop;
case Token.SUB :
case Token.MUL :
case Token.DIV :
case Token.MOD : {
double rDbl = stack_double(frame, stackTop);
--stackTop;
double lDbl = stack_double(frame, stackTop);
stack[stackTop] = DBL_MRK;
switch (op) {
case Token.SUB:
lDbl -= rDbl;
break;
case Token.MUL:
lDbl *= rDbl;
break;
case Token.DIV:
lDbl /= rDbl;
break;
case Token.MOD:
lDbl %= rDbl;
break;
}
sDbl[stackTop] = lDbl;
continue Loop;
}
case Token.NOT :
stack[stackTop] = ScriptRuntime.wrapBoolean(
!stack_boolean(frame, stackTop));
continue Loop;
case Token.BINDNAME :
stack[++stackTop] = ScriptRuntime.bind(cx, frame.scope, stringReg);
continue Loop;
case Token.SETNAME : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Scriptable lhs = (Scriptable)stack[stackTop];
stack[stackTop] = ScriptRuntime.setName(lhs, rhs, cx,
frame.scope, stringReg);
continue Loop;
}
case Icode_SETCONST: {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Scriptable lhs = (Scriptable)stack[stackTop];
stack[stackTop] = ScriptRuntime.setConst(lhs, rhs, cx, stringReg);
continue Loop;
}
case Token.DELPROP : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.delete(lhs, rhs, cx);
continue Loop;
}
case Token.GETPROPNOWARN : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getObjectPropNoWarn(lhs, stringReg, cx);
continue Loop;
}
case Token.GETPROP : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getObjectProp(lhs, stringReg, cx);
continue Loop;
}
case Token.SETPROP : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.setObjectProp(lhs, stringReg, rhs,
cx);
continue Loop;
}
case Icode_PROP_INC_DEC : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.propIncrDecr(lhs, stringReg,
cx, iCode[frame.pc]);
++frame.pc;
continue Loop;
}
case Token.GETELEM : {
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) {
lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
}
Object value;
Object id = stack[stackTop + 1];
if (id != DBL_MRK) {
value = ScriptRuntime.getObjectElem(lhs, id, cx);
} else {
double d = sDbl[stackTop + 1];
value = ScriptRuntime.getObjectIndex(lhs, d, cx);
}
stack[stackTop] = value;
continue Loop;
}
case Token.SETELEM : {
stackTop -= 2;
Object rhs = stack[stackTop + 2];
if (rhs == DBL_MRK) {
rhs = ScriptRuntime.wrapNumber(sDbl[stackTop + 2]);
}
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) {
lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
}
Object value;
Object id = stack[stackTop + 1];
if (id != DBL_MRK) {
value = ScriptRuntime.setObjectElem(lhs, id, rhs, cx);
} else {
double d = sDbl[stackTop + 1];
value = ScriptRuntime.setObjectIndex(lhs, d, rhs, cx);
}
stack[stackTop] = value;
continue Loop;
}
case Icode_ELEM_INC_DEC: {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.elemIncrDecr(lhs, rhs, cx,
iCode[frame.pc]);
++frame.pc;
continue Loop;
}
case Token.GET_REF : {
Ref ref = (Ref)stack[stackTop];
stack[stackTop] = ScriptRuntime.refGet(ref, cx);
continue Loop;
}
case Token.SET_REF : {
Object value = stack[stackTop];
if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Ref ref = (Ref)stack[stackTop];
stack[stackTop] = ScriptRuntime.refSet(ref, value, cx);
continue Loop;
}
case Token.DEL_REF : {
Ref ref = (Ref)stack[stackTop];
stack[stackTop] = ScriptRuntime.refDel(ref, cx);
continue Loop;
}
case Icode_REF_INC_DEC : {
Ref ref = (Ref)stack[stackTop];
stack[stackTop] = ScriptRuntime.refIncrDecr(ref, cx, iCode[frame.pc]);
++frame.pc;
continue Loop;
}
case Token.LOCAL_LOAD :
++stackTop;
indexReg += frame.localShift;
stack[stackTop] = stack[indexReg];
sDbl[stackTop] = sDbl[indexReg];
continue Loop;
case Icode_LOCAL_CLEAR :
indexReg += frame.localShift;
stack[indexReg] = null;
continue Loop;
case Icode_NAME_AND_THIS :
// stringReg: name
++stackTop;
stack[stackTop] = ScriptRuntime.getNameFunctionAndThis(stringReg,
cx, frame.scope);
++stackTop;
stack[stackTop] = ScriptRuntime.lastStoredScriptable(cx);
continue Loop;
case Icode_PROP_AND_THIS: {
Object obj = stack[stackTop];
if (obj == DBL_MRK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop]);
// stringReg: property
stack[stackTop] = ScriptRuntime.getPropFunctionAndThis(obj, stringReg,
cx);
++stackTop;
stack[stackTop] = ScriptRuntime.lastStoredScriptable(cx);
continue Loop;
}
case Icode_ELEM_AND_THIS: {
Object obj = stack[stackTop - 1];
if (obj == DBL_MRK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop - 1]);
Object id = stack[stackTop];
if (id == DBL_MRK) id = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop - 1] = ScriptRuntime.getElemFunctionAndThis(obj, id, cx);
stack[stackTop] = ScriptRuntime.lastStoredScriptable(cx);
continue Loop;
}
case Icode_VALUE_AND_THIS : {
Object value = stack[stackTop];
if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getValueFunctionAndThis(value, cx);
++stackTop;
stack[stackTop] = ScriptRuntime.lastStoredScriptable(cx);
continue Loop;
}
case Icode_CALLSPECIAL : {
if (instructionCounting) {
cx.instructionCount += INVOCATION_COST;
}
int callType = iCode[frame.pc] & 0xFF;
boolean isNew = (iCode[frame.pc + 1] != 0);
int sourceLine = getIndex(iCode, frame.pc + 2);
// indexReg: number of arguments
if (isNew) {
// stack change: function arg0 .. argN -> newResult
stackTop -= indexReg;
Object function = stack[stackTop];
if (function == DBL_MRK)
function = ScriptRuntime.wrapNumber(sDbl[stackTop]);
Object[] outArgs = getArgsArray(
stack, sDbl, stackTop + 1, indexReg);
stack[stackTop] = ScriptRuntime.newSpecial(
cx, function, outArgs, frame.scope, callType);
} else {
// stack change: function thisObj arg0 .. argN -> result
stackTop -= 1 + indexReg;
// Call code generation ensure that stack here
// is ... Callable Scriptable
Scriptable functionThis = (Scriptable)stack[stackTop + 1];
Callable function = (Callable)stack[stackTop];
Object[] outArgs = getArgsArray(
stack, sDbl, stackTop + 2, indexReg);
stack[stackTop] = ScriptRuntime.callSpecial(
cx, function, functionThis, outArgs,
frame.scope, frame.thisObj, callType,
frame.idata.itsSourceFile, sourceLine);
}
frame.pc += 4;
continue Loop;
}
case Token.CALL :
case Icode_TAIL_CALL :
case Token.REF_CALL : {
if (instructionCounting) {
cx.instructionCount += INVOCATION_COST;
}
// stack change: function thisObj arg0 .. argN -> result
// indexReg: number of arguments
stackTop -= 1 + indexReg;
// CALL generation ensures that fun and funThisObj
// are already Scriptable and Callable objects respectively
Callable fun = (Callable)stack[stackTop];
Scriptable funThisObj = (Scriptable)stack[stackTop + 1];
if (op == Token.REF_CALL) {
Object[] outArgs = getArgsArray(stack, sDbl, stackTop + 2,
indexReg);
stack[stackTop] = ScriptRuntime.callRef(fun, funThisObj,
outArgs, cx);
continue Loop;
}
Scriptable calleeScope = frame.scope;
if (frame.useActivation) {
calleeScope = ScriptableObject.getTopLevelScope(frame.scope);
}
if (fun instanceof InterpretedFunction) {
InterpretedFunction ifun = (InterpretedFunction)fun;
if (frame.fnOrScript.securityDomain == ifun.securityDomain) {
CallFrame callParentFrame = frame;
CallFrame calleeFrame = new CallFrame();
if (op == Icode_TAIL_CALL) {
// In principle tail call can re-use the current
// frame and its stack arrays but it is hard to
// do properly. Any exceptions that can legally
// happen during frame re-initialization including
// StackOverflowException during innocent looking
// System.arraycopy may leave the current frame
// data corrupted leading to undefined behaviour
// in the catch code bellow that unwinds JS stack
// on exceptions. Then there is issue about frame release
// end exceptions there.
// To avoid frame allocation a released frame
// can be cached for re-use which would also benefit
// non-tail calls but it is not clear that this caching
// would gain in performance due to potentially
// bad interaction with GC.
callParentFrame = frame.parentFrame;
// Release the current frame. See Bug #344501 to see why
// it is being done here.
exitFrame(cx, frame, null);
}
initFrame(cx, calleeScope, funThisObj, stack, sDbl,
stackTop + 2, indexReg, ifun, callParentFrame,
calleeFrame);
if (op != Icode_TAIL_CALL) {
frame.savedStackTop = stackTop;
frame.savedCallOp = op;
}
frame = calleeFrame;
continue StateLoop;
}
}
if (fun instanceof NativeContinuation) {
// Jump to the captured continuation
ContinuationJump cjump;
cjump = new ContinuationJump((NativeContinuation)fun, frame);
// continuation result is the first argument if any
// of continuation call
if (indexReg == 0) {
cjump.result = undefined;
} else {
cjump.result = stack[stackTop + 2];
cjump.resultDbl = sDbl[stackTop + 2];
}
// Start the real unwind job
throwable = cjump;
break withoutExceptions;
}
if (fun instanceof IdFunctionObject) {
IdFunctionObject ifun = (IdFunctionObject)fun;
if (NativeContinuation.isContinuationConstructor(ifun)) {
frame.stack[stackTop] = captureContinuation(cx,
frame.parentFrame, false);
continue Loop;
}
// Bug 405654 -- make best effort to keep Function.apply and
// Function.call within this interpreter loop invocation
if (BaseFunction.isApplyOrCall(ifun)) {
Callable applyCallable = ScriptRuntime.getCallable(funThisObj);
if (applyCallable instanceof InterpretedFunction) {
InterpretedFunction iApplyCallable = (InterpretedFunction)applyCallable;
if (frame.fnOrScript.securityDomain == iApplyCallable.securityDomain) {
frame = initFrameForApplyOrCall(cx, frame, indexReg,
stack, sDbl, stackTop, op, calleeScope, ifun,
iApplyCallable);
continue StateLoop;
}
}
}
}
// Bug 447697 -- make best effort to keep __noSuchMethod__ within this
// interpreter loop invocation
if (fun instanceof NoSuchMethodShim) {
// get the shim and the actual method
NoSuchMethodShim noSuchMethodShim = (NoSuchMethodShim) fun;
Callable noSuchMethodMethod = noSuchMethodShim.noSuchMethodMethod;
// if the method is in fact an InterpretedFunction
if (noSuchMethodMethod instanceof InterpretedFunction) {
InterpretedFunction ifun = (InterpretedFunction) noSuchMethodMethod;
if (frame.fnOrScript.securityDomain == ifun.securityDomain) {
frame = initFrameForNoSuchMethod(cx, frame, indexReg, stack, sDbl,
stackTop, op, funThisObj, calleeScope,
noSuchMethodShim, ifun);
continue StateLoop;
}
}
}
cx.lastInterpreterFrame = frame;
frame.savedCallOp = op;
frame.savedStackTop = stackTop;
stack[stackTop] = fun.call(cx, calleeScope, funThisObj,
getArgsArray(stack, sDbl, stackTop + 2, indexReg));
cx.lastInterpreterFrame = null;
continue Loop;
}
case Token.NEW : {
if (instructionCounting) {
cx.instructionCount += INVOCATION_COST;
}
// stack change: function arg0 .. argN -> newResult
// indexReg: number of arguments
stackTop -= indexReg;
Object lhs = stack[stackTop];
if (lhs instanceof InterpretedFunction) {
InterpretedFunction f = (InterpretedFunction)lhs;
if (frame.fnOrScript.securityDomain == f.securityDomain) {
Scriptable newInstance = f.createObject(cx, frame.scope);
CallFrame calleeFrame = new CallFrame();
initFrame(cx, frame.scope, newInstance, stack, sDbl,
stackTop + 1, indexReg, f, frame,
calleeFrame);
stack[stackTop] = newInstance;
frame.savedStackTop = stackTop;
frame.savedCallOp = op;
frame = calleeFrame;
continue StateLoop;
}
}
if (!(lhs instanceof Function)) {
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
throw ScriptRuntime.notFunctionError(lhs);
}
Function fun = (Function)lhs;
if (fun instanceof IdFunctionObject) {
IdFunctionObject ifun = (IdFunctionObject)fun;
if (NativeContinuation.isContinuationConstructor(ifun)) {
frame.stack[stackTop] =
captureContinuation(cx, frame.parentFrame, false);
continue Loop;
}
}
Object[] outArgs = getArgsArray(stack, sDbl, stackTop + 1, indexReg);
stack[stackTop] = fun.construct(cx, frame.scope, outArgs);
continue Loop;
}
case Token.TYPEOF : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.typeof(lhs);
continue Loop;
}
case Icode_TYPEOFNAME :
stack[++stackTop] = ScriptRuntime.typeofName(frame.scope, stringReg);
continue Loop;
case Token.STRING :
stack[++stackTop] = stringReg;
continue Loop;
case Icode_SHORTNUMBER :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = getShort(iCode, frame.pc);
frame.pc += 2;
continue Loop;
case Icode_INTNUMBER :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = getInt(iCode, frame.pc);
frame.pc += 4;
continue Loop;
case Token.NUMBER :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = frame.idata.itsDoubleTable[indexReg];
continue Loop;
case Token.NAME :
stack[++stackTop] = ScriptRuntime.name(cx, frame.scope, stringReg);
continue Loop;
case Icode_NAME_INC_DEC :
stack[++stackTop] = ScriptRuntime.nameIncrDecr(frame.scope, stringReg,
cx, iCode[frame.pc]);
++frame.pc;
continue Loop;
case Icode_SETCONSTVAR1:
indexReg = iCode[frame.pc++];
// fallthrough
case Token.SETCONSTVAR :
if (!frame.useActivation) {
if ((varAttributes[indexReg] & ScriptableObject.READONLY) == 0) {
throw Context.reportRuntimeError1("msg.var.redecl",
frame.idata.argNames[indexReg]);
}
if ((varAttributes[indexReg] & ScriptableObject.UNINITIALIZED_CONST)
!= 0)
{
vars[indexReg] = stack[stackTop];
varAttributes[indexReg] &= ~ScriptableObject.UNINITIALIZED_CONST;
varDbls[indexReg] = sDbl[stackTop];
}
} else {
Object val = stack[stackTop];
if (val == DBL_MRK) val = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stringReg = frame.idata.argNames[indexReg];
if (frame.scope instanceof ConstProperties) {
ConstProperties cp = (ConstProperties)frame.scope;
cp.putConst(stringReg, frame.scope, val);
} else
throw Kit.codeBug();
}
continue Loop;
case Icode_SETVAR1:
indexReg = iCode[frame.pc++];
// fallthrough
case Token.SETVAR :
if (!frame.useActivation) {
if ((varAttributes[indexReg] & ScriptableObject.READONLY) == 0) {
vars[indexReg] = stack[stackTop];
varDbls[indexReg] = sDbl[stackTop];
}
} else {
Object val = stack[stackTop];
if (val == DBL_MRK) val = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stringReg = frame.idata.argNames[indexReg];
frame.scope.put(stringReg, frame.scope, val);
}
continue Loop;
case Icode_GETVAR1:
indexReg = iCode[frame.pc++];
// fallthrough
case Token.GETVAR :
++stackTop;
if (!frame.useActivation) {
stack[stackTop] = vars[indexReg];
sDbl[stackTop] = varDbls[indexReg];
} else {
stringReg = frame.idata.argNames[indexReg];
stack[stackTop] = frame.scope.get(stringReg, frame.scope);
}
continue Loop;
case Icode_VAR_INC_DEC : {
// indexReg : varindex
++stackTop;
int incrDecrMask = iCode[frame.pc];
if (!frame.useActivation) {
stack[stackTop] = DBL_MRK;
Object varValue = vars[indexReg];
double d;
if (varValue == DBL_MRK) {
d = varDbls[indexReg];
} else {
d = ScriptRuntime.toNumber(varValue);
vars[indexReg] = DBL_MRK;
}
double d2 = ((incrDecrMask & Node.DECR_FLAG) == 0)
? d + 1.0 : d - 1.0;
varDbls[indexReg] = d2;
sDbl[stackTop] = ((incrDecrMask & Node.POST_FLAG) == 0) ? d2 : d;
} else {
String varName = frame.idata.argNames[indexReg];
stack[stackTop] = ScriptRuntime.nameIncrDecr(frame.scope, varName,
cx, incrDecrMask);
}
++frame.pc;
continue Loop;
}
case Icode_ZERO :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = 0;
continue Loop;
case Icode_ONE :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = 1;
continue Loop;
case Token.NULL :
stack[++stackTop] = null;
continue Loop;
case Token.THIS :
stack[++stackTop] = frame.thisObj;
continue Loop;
case Token.THISFN :
stack[++stackTop] = frame.fnOrScript;
continue Loop;
case Token.FALSE :
stack[++stackTop] = Boolean.FALSE;
continue Loop;
case Token.TRUE :
stack[++stackTop] = Boolean.TRUE;
continue Loop;
case Icode_UNDEF :
stack[++stackTop] = undefined;
continue Loop;
case Token.ENTERWITH : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
frame.scope = ScriptRuntime.enterWith(lhs, cx, frame.scope);
continue Loop;
}
case Token.LEAVEWITH :
frame.scope = ScriptRuntime.leaveWith(frame.scope);
continue Loop;
case Token.CATCH_SCOPE : {
// stack top: exception object
// stringReg: name of exception variable
// indexReg: local for exception scope
--stackTop;
indexReg += frame.localShift;
boolean afterFirstScope = (frame.idata.itsICode[frame.pc] != 0);
Throwable caughtException = (Throwable)stack[stackTop + 1];
Scriptable lastCatchScope;
if (!afterFirstScope) {
lastCatchScope = null;
} else {
lastCatchScope = (Scriptable)stack[indexReg];
}
stack[indexReg] = ScriptRuntime.newCatchScope(caughtException,
lastCatchScope, stringReg,
cx, frame.scope);
++frame.pc;
continue Loop;
}
case Token.ENUM_INIT_KEYS :
case Token.ENUM_INIT_VALUES :
case Token.ENUM_INIT_ARRAY : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
indexReg += frame.localShift;
int enumType = op == Token.ENUM_INIT_KEYS
? ScriptRuntime.ENUMERATE_KEYS :
op == Token.ENUM_INIT_VALUES
? ScriptRuntime.ENUMERATE_VALUES :
ScriptRuntime.ENUMERATE_ARRAY;
stack[indexReg] = ScriptRuntime.enumInit(lhs, cx, enumType);
continue Loop;
}
case Token.ENUM_NEXT :
case Token.ENUM_ID : {
indexReg += frame.localShift;
Object val = stack[indexReg];
++stackTop;
stack[stackTop] = (op == Token.ENUM_NEXT)
? (Object)ScriptRuntime.enumNext(val)
: (Object)ScriptRuntime.enumId(val, cx);
continue Loop;
}
case Token.REF_SPECIAL : {
//stringReg: name of special property
Object obj = stack[stackTop];
if (obj == DBL_MRK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.specialRef(obj, stringReg, cx);
continue Loop;
}
case Token.REF_MEMBER: {
//indexReg: flags
Object elem = stack[stackTop];
if (elem == DBL_MRK) elem = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Object obj = stack[stackTop];
if (obj == DBL_MRK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.memberRef(obj, elem, cx, indexReg);
continue Loop;
}
case Token.REF_NS_MEMBER: {
//indexReg: flags
Object elem = stack[stackTop];
if (elem == DBL_MRK) elem = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Object ns = stack[stackTop];
if (ns == DBL_MRK) ns = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Object obj = stack[stackTop];
if (obj == DBL_MRK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.memberRef(obj, ns, elem, cx, indexReg);
continue Loop;
}
case Token.REF_NAME: {
//indexReg: flags
Object name = stack[stackTop];
if (name == DBL_MRK) name = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.nameRef(name, cx, frame.scope,
indexReg);
continue Loop;
}
case Token.REF_NS_NAME: {
//indexReg: flags
Object name = stack[stackTop];
if (name == DBL_MRK) name = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
Object ns = stack[stackTop];
if (ns == DBL_MRK) ns = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.nameRef(ns, name, cx, frame.scope,
indexReg);
continue Loop;
}
case Icode_SCOPE_LOAD :
indexReg += frame.localShift;
frame.scope = (Scriptable)stack[indexReg];
continue Loop;
case Icode_SCOPE_SAVE :
indexReg += frame.localShift;
stack[indexReg] = frame.scope;
continue Loop;
case Icode_CLOSURE_EXPR :
stack[++stackTop] = InterpretedFunction.createFunction(cx, frame.scope,
frame.fnOrScript,
indexReg);
continue Loop;
case Icode_CLOSURE_STMT :
initFunction(cx, frame.scope, frame.fnOrScript, indexReg);
continue Loop;
case Token.REGEXP :
stack[++stackTop] = frame.scriptRegExps[indexReg];
continue Loop;
case Icode_LITERAL_NEW :
// indexReg: number of values in the literal
++stackTop;
stack[stackTop] = new int[indexReg];
++stackTop;
stack[stackTop] = new Object[indexReg];
sDbl[stackTop] = 0;
continue Loop;
case Icode_LITERAL_SET : {
Object value = stack[stackTop];
if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
int i = (int)sDbl[stackTop];
((Object[])stack[stackTop])[i] = value;
sDbl[stackTop] = i + 1;
continue Loop;
}
case Icode_LITERAL_GETTER : {
Object value = stack[stackTop];
--stackTop;
int i = (int)sDbl[stackTop];
((Object[])stack[stackTop])[i] = value;
((int[])stack[stackTop - 1])[i] = -1;
sDbl[stackTop] = i + 1;
continue Loop;
}
case Icode_LITERAL_SETTER : {
Object value = stack[stackTop];
--stackTop;
int i = (int)sDbl[stackTop];
((Object[])stack[stackTop])[i] = value;
((int[])stack[stackTop - 1])[i] = +1;
sDbl[stackTop] = i + 1;
continue Loop;
}
case Token.ARRAYLIT :
case Icode_SPARE_ARRAYLIT :
case Token.OBJECTLIT : {
Object[] data = (Object[])stack[stackTop];
--stackTop;
int[] getterSetters = (int[])stack[stackTop];
Object val;
if (op == Token.OBJECTLIT) {
Object[] ids = (Object[])frame.idata.literalIds[indexReg];
val = ScriptRuntime.newObjectLiteral(ids, data, getterSetters, cx,
frame.scope);
} else {
int[] skipIndexces = null;
if (op == Icode_SPARE_ARRAYLIT) {
skipIndexces = (int[])frame.idata.literalIds[indexReg];
}
val = ScriptRuntime.newArrayLiteral(data, skipIndexces, cx,
frame.scope);
}
stack[stackTop] = val;
continue Loop;
}
case Icode_ENTERDQ : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]);
--stackTop;
frame.scope = ScriptRuntime.enterDotQuery(lhs, frame.scope);
continue Loop;
}
case Icode_LEAVEDQ : {
boolean valBln = stack_boolean(frame, stackTop);
Object x = ScriptRuntime.updateDotQuery(valBln, frame.scope);
if (x != null) {
stack[stackTop] = x;
frame.scope = ScriptRuntime.leaveDotQuery(frame.scope);
frame.pc += 2;
continue Loop;
}
// reset stack and PC to code after ENTERDQ
--stackTop;
break jumplessRun;
}
case Token.DEFAULTNAMESPACE : {
Object value = stack[stackTop];
if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.setDefaultNamespace(value, cx);
continue Loop;
}
case Token.ESCXMLATTR : {
Object value = stack[stackTop];
if (value != DBL_MRK) {
stack[stackTop] = ScriptRuntime.escapeAttributeValue(value, cx);
}
continue Loop;
}
case Token.ESCXMLTEXT : {
Object value = stack[stackTop];
if (value != DBL_MRK) {
stack[stackTop] = ScriptRuntime.escapeTextValue(value, cx);
}
continue Loop;
}
case Icode_DEBUGGER:
if (frame.debuggerFrame != null) {
frame.debuggerFrame.onDebuggerStatement(cx);
}
continue Loop;
case Icode_LINE :
frame.pcSourceLineStart = frame.pc;
if (frame.debuggerFrame != null) {
int line = getIndex(iCode, frame.pc);
frame.debuggerFrame.onLineChange(cx, line);
}
frame.pc += 2;
continue Loop;
case Icode_REG_IND_C0:
indexReg = 0;
continue Loop;
case Icode_REG_IND_C1:
indexReg = 1;
continue Loop;
case Icode_REG_IND_C2:
indexReg = 2;
continue Loop;
case Icode_REG_IND_C3:
indexReg = 3;
continue Loop;
case Icode_REG_IND_C4:
indexReg = 4;
continue Loop;
case Icode_REG_IND_C5:
indexReg = 5;
continue Loop;
case Icode_REG_IND1:
indexReg = 0xFF & iCode[frame.pc];
++frame.pc;
continue Loop;
case Icode_REG_IND2:
indexReg = getIndex(iCode, frame.pc);
frame.pc += 2;
continue Loop;
case Icode_REG_IND4:
indexReg = getInt(iCode, frame.pc);
frame.pc += 4;
continue Loop;
case Icode_REG_STR_C0:
stringReg = strings[0];
continue Loop;
case Icode_REG_STR_C1:
stringReg = strings[1];
continue Loop;
case Icode_REG_STR_C2:
stringReg = strings[2];
continue Loop;
case Icode_REG_STR_C3:
stringReg = strings[3];
continue Loop;
case Icode_REG_STR1:
stringReg = strings[0xFF & iCode[frame.pc]];
++frame.pc;
continue Loop;
case Icode_REG_STR2:
stringReg = strings[getIndex(iCode, frame.pc)];
frame.pc += 2;
continue Loop;
case Icode_REG_STR4:
stringReg = strings[getInt(iCode, frame.pc)];
frame.pc += 4;
continue Loop;
default :
dumpICode(frame.idata);
throw new RuntimeException(
"Unknown icode : "+op+" @ pc : "+(frame.pc-1));
} // end of interpreter switch
} // end of jumplessRun label block
// This should be reachable only for jump implementation
// when pc points to encoded target offset
if (instructionCounting) {
addInstructionCount(cx, frame, 2);
}
int offset = getShort(iCode, frame.pc);
if (offset != 0) {
// -1 accounts for pc pointing to jump opcode + 1
frame.pc += offset - 1;
} else {
frame.pc = frame.idata.longJumps.
getExistingInt(frame.pc);
}
if (instructionCounting) {
frame.pcPrevBranch = frame.pc;
}
continue Loop;
} // end of Loop: for
exitFrame(cx, frame, null);
interpreterResult = frame.result;
interpreterResultDbl = frame.resultDbl;
if (frame.parentFrame != null) {
frame = frame.parentFrame;
if (frame.frozen) {
frame = frame.cloneFrozen();
}
setCallResult(
frame, interpreterResult, interpreterResultDbl);
interpreterResult = null; // Help GC
continue StateLoop;
}
break StateLoop;
} // end of interpreter withoutExceptions: try
catch (Throwable ex) {
if (throwable != null) {
// This is serious bug and it is better to track it ASAP
ex.printStackTrace(System.err);
throw new IllegalStateException();
}
throwable = ex;
}
// This should be reachable only after above catch or from
// finally when it needs to propagate exception or from
// explicit throw
if (throwable == null) Kit.codeBug();
// Exception type
final int EX_CATCH_STATE = 2; // Can execute JS catch
final int EX_FINALLY_STATE = 1; // Can execute JS finally
final int EX_NO_JS_STATE = 0; // Terminate JS execution
int exState;
ContinuationJump cjump = null;
if (generatorState != null &&
generatorState.operation == NativeGenerator.GENERATOR_CLOSE &&
throwable == generatorState.value)
{
exState = EX_FINALLY_STATE;
} else if (throwable instanceof JavaScriptException) {
exState = EX_CATCH_STATE;
} else if (throwable instanceof EcmaError) {
// an offical ECMA error object,
exState = EX_CATCH_STATE;
} else if (throwable instanceof EvaluatorException) {
exState = EX_CATCH_STATE;
} else if (throwable instanceof RuntimeException) {
exState = cx.hasFeature(Context.FEATURE_ENHANCED_JAVA_ACCESS)
? EX_CATCH_STATE
: EX_FINALLY_STATE;
} else if (throwable instanceof Error) {
exState = cx.hasFeature(Context.FEATURE_ENHANCED_JAVA_ACCESS)
? EX_CATCH_STATE
: EX_NO_JS_STATE;
} else if (throwable instanceof ContinuationJump) {
// It must be ContinuationJump
exState = EX_FINALLY_STATE;
cjump = (ContinuationJump)throwable;
} else {
exState = cx.hasFeature(Context.FEATURE_ENHANCED_JAVA_ACCESS)
? EX_CATCH_STATE
: EX_FINALLY_STATE;
}
if (instructionCounting) {
try {
addInstructionCount(cx, frame, EXCEPTION_COST);
} catch (RuntimeException ex) {
throwable = ex;
exState = EX_FINALLY_STATE;
} catch (Error ex) {
// Error from instruction counting
// => unconditionally terminate JS
throwable = ex;
cjump = null;
exState = EX_NO_JS_STATE;
}
}
if (frame.debuggerFrame != null
&& throwable instanceof RuntimeException)
{
// Call debugger only for RuntimeException
RuntimeException rex = (RuntimeException)throwable;
try {
frame.debuggerFrame.onExceptionThrown(cx, rex);
} catch (Throwable ex) {
// Any exception from debugger
// => unconditionally terminate JS
throwable = ex;
cjump = null;
exState = EX_NO_JS_STATE;
}
}
for (;;) {
if (exState != EX_NO_JS_STATE) {
boolean onlyFinally = (exState != EX_CATCH_STATE);
indexReg = getExceptionHandler(frame, onlyFinally);
if (indexReg >= 0) {
// We caught an exception, restart the loop
// with exception pending the processing at the loop
// start
continue StateLoop;
}
}
// No allowed exception handlers in this frame, unwind
// to parent and try to look there
exitFrame(cx, frame, throwable);
frame = frame.parentFrame;
if (frame == null) { break; }
if (cjump != null && cjump.branchFrame == frame) {
// Continuation branch point was hit,
// restart the state loop to reenter continuation
indexReg = -1;
continue StateLoop;
}
}
// No more frames, rethrow the exception or deal with continuation
if (cjump != null) {
if (cjump.branchFrame != null) {
// The above loop should locate the top frame
Kit.codeBug();
}
if (cjump.capturedFrame != null) {
// Restarting detached continuation
indexReg = -1;
continue StateLoop;
}
// Return continuation result to the caller
interpreterResult = cjump.result;
interpreterResultDbl = cjump.resultDbl;
throwable = null;
}
break StateLoop;
} // end of StateLoop: for(;;)
// Do cleanups/restorations before the final return or throw
if (cx.previousInterpreterInvocations != null
&& cx.previousInterpreterInvocations.size() != 0)
{
cx.lastInterpreterFrame
= cx.previousInterpreterInvocations.pop();
} else {
// It was the last interpreter frame on the stack
cx.lastInterpreterFrame = null;
// Force GC of the value cx.previousInterpreterInvocations
cx.previousInterpreterInvocations = null;
}
if (throwable != null) {
if (throwable instanceof RuntimeException) {
throw (RuntimeException)throwable;
} else {
// Must be instance of Error or code bug
throw (Error)throwable;
}
}
return (interpreterResult != DBL_MRK)
? interpreterResult
: ScriptRuntime.wrapNumber(interpreterResultDbl);
}
|
diff --git a/tests/org.jboss.tools.hibernate.ui.bot.test/src/org/jboss/tools/hb/ui/bot/test/console/CreateConsoleConfigurationTest.java b/tests/org.jboss.tools.hibernate.ui.bot.test/src/org/jboss/tools/hb/ui/bot/test/console/CreateConsoleConfigurationTest.java
index a10d803b..933d59eb 100644
--- a/tests/org.jboss.tools.hibernate.ui.bot.test/src/org/jboss/tools/hb/ui/bot/test/console/CreateConsoleConfigurationTest.java
+++ b/tests/org.jboss.tools.hibernate.ui.bot.test/src/org/jboss/tools/hb/ui/bot/test/console/CreateConsoleConfigurationTest.java
@@ -1,130 +1,130 @@
package org.jboss.tools.hb.ui.bot.test.console;
import static org.eclipse.swtbot.swt.finder.waits.Conditions.shellCloses;
import java.util.List;
import org.eclipse.swtbot.swt.finder.SWTBot;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotShell;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotTreeItem;
import org.jboss.tools.hb.ui.bot.common.ConfigurationFile;
import org.jboss.tools.hb.ui.bot.common.Tree;
import org.jboss.tools.hb.ui.bot.test.HibernateBaseTest;
import org.jboss.tools.ui.bot.ext.config.Annotations.DB;
import org.jboss.tools.ui.bot.ext.config.Annotations.Require;
import org.jboss.tools.ui.bot.ext.config.TestConfigurator;
import org.jboss.tools.ui.bot.ext.gen.ActionItem;
import org.jboss.tools.ui.bot.ext.helper.DatabaseHelper;
import org.jboss.tools.ui.bot.ext.types.EntityType;
import org.jboss.tools.ui.bot.ext.types.IDELabel;
import org.junit.Test;
/**
* Create Hibernate Console UI Bot Test
* @author jpeterka
*
*/
@Require(db = @DB, clearProjects = true)
public class CreateConsoleConfigurationTest extends HibernateBaseTest {
final String prjName = "configurationtest";
@Test
public void createConsoleConfigurationTest() {
emptyErrorLog();
importTestProject("/resources/prj/" + prjName);
createConfigurationFile();
createHibernateConsole();
expandDatabaseInConsole();
checkErrorLog();
}
private void createConfigurationFile() {
ConfigurationFile.create(new String[]{prjName,"src"},"hibernate.cfg.xml",false);
}
private void createHibernateConsole() {
open.viewOpen(ActionItem.View.GeneralProjectExplorer.LABEL);
eclipse.createNew(EntityType.HIBERNATE_CONSOLE);
// Hibernate Console Dialog has no title
SWTBotShell shell = bot.waitForShell("");
createMainTab(shell);
createOptionTab(shell);
createClasspathTab(shell);
createMappingsTab(shell);
createCommonTab(shell);
bot.button(IDELabel.Button.FINISH).click();
bot.waitUntil(shellCloses(shell));
util.waitForNonIgnoredJobs();
}
private void createMainTab(SWTBotShell shell) {
bot.cTabItem(IDELabel.HBConsoleWizard.MAIN_TAB).activate();
bot.textWithLabel("Name:").setText(prjName);
bot.textWithLabelInGroup("","Configuration file:").setText(prjName + "/src/hibernate.cfg.xml");
}
private void createOptionTab(SWTBotShell shell) {
shell.setFocus();
bot.cTabItem(IDELabel.HBConsoleWizard.OPTIONS_TAB).activate();
String dialect = DatabaseHelper.getDialect(TestConfigurator.currentConfig.getDB().dbType);
bot.comboBoxWithLabelInGroup("", IDELabel.HBConsoleWizard.DATABASE_DIALECT).setSelection(dialect);
}
private void createClasspathTab(SWTBotShell shell) {
- shell.activate();
+ shell.setFocus();
bot.cTabItem(IDELabel.HBConsoleWizard.CLASSPATH_TAB).activate();
}
private void createMappingsTab(SWTBotShell shell) {
- shell.activate();
+ shell.setFocus();
bot.cTabItem(IDELabel.HBConsoleWizard.MAPPINGS_TAB).activate();
}
private void createCommonTab(SWTBotShell shell) {
- shell.activate();
+ shell.setFocus();
bot.cTabItem(IDELabel.HBConsoleWizard.COMMON_TAB).activate();
}
private void expandDatabaseInConsole() {
SWTBot viewBot = open.viewOpen(ActionItem.View.HibernateHibernateConfigurations.LABEL).bot();
SWTBotTreeItem db = Tree.select(viewBot, prjName,"Database");
db.expand();
// expand PUBLIC node or whatever
SWTBotTreeItem pub = db.getItems()[0];
final int limit = 10; // 10s
final int sleep = 1000;
int counter = 0;
while(counter < limit) {
if (pub.widget.isDisposed()) {
pub = db.getItems()[0];
bot.sleep(sleep);
}
if (pub.getText().equals("<Reading schema error: Getting database metadata >")) {
fail("Can't load data, DB not accessible");
}
if (pub.getText().equals("Pending...") && counter < limit) {
bot.sleep(sleep);
counter++;
log.info("Waiting for database loading...");
}
else
{
log.info("DB loaded");
break;
}
}
List<String> tables = Tree.getSubNodes(viewBot, pub);
assertTrue("Table must contain tables", tables.size()> 0);
for (String s : tables) {
log.info("Table:" + s);
}
}
}
| false | true | private void createConfigurationFile() {
ConfigurationFile.create(new String[]{prjName,"src"},"hibernate.cfg.xml",false);
}
private void createHibernateConsole() {
open.viewOpen(ActionItem.View.GeneralProjectExplorer.LABEL);
eclipse.createNew(EntityType.HIBERNATE_CONSOLE);
// Hibernate Console Dialog has no title
SWTBotShell shell = bot.waitForShell("");
createMainTab(shell);
createOptionTab(shell);
createClasspathTab(shell);
createMappingsTab(shell);
createCommonTab(shell);
bot.button(IDELabel.Button.FINISH).click();
bot.waitUntil(shellCloses(shell));
util.waitForNonIgnoredJobs();
}
private void createMainTab(SWTBotShell shell) {
bot.cTabItem(IDELabel.HBConsoleWizard.MAIN_TAB).activate();
bot.textWithLabel("Name:").setText(prjName);
bot.textWithLabelInGroup("","Configuration file:").setText(prjName + "/src/hibernate.cfg.xml");
}
private void createOptionTab(SWTBotShell shell) {
shell.setFocus();
bot.cTabItem(IDELabel.HBConsoleWizard.OPTIONS_TAB).activate();
String dialect = DatabaseHelper.getDialect(TestConfigurator.currentConfig.getDB().dbType);
bot.comboBoxWithLabelInGroup("", IDELabel.HBConsoleWizard.DATABASE_DIALECT).setSelection(dialect);
}
private void createClasspathTab(SWTBotShell shell) {
shell.activate();
bot.cTabItem(IDELabel.HBConsoleWizard.CLASSPATH_TAB).activate();
}
private void createMappingsTab(SWTBotShell shell) {
shell.activate();
bot.cTabItem(IDELabel.HBConsoleWizard.MAPPINGS_TAB).activate();
}
private void createCommonTab(SWTBotShell shell) {
shell.activate();
bot.cTabItem(IDELabel.HBConsoleWizard.COMMON_TAB).activate();
}
private void expandDatabaseInConsole() {
SWTBot viewBot = open.viewOpen(ActionItem.View.HibernateHibernateConfigurations.LABEL).bot();
SWTBotTreeItem db = Tree.select(viewBot, prjName,"Database");
db.expand();
// expand PUBLIC node or whatever
SWTBotTreeItem pub = db.getItems()[0];
final int limit = 10; // 10s
final int sleep = 1000;
int counter = 0;
while(counter < limit) {
if (pub.widget.isDisposed()) {
pub = db.getItems()[0];
bot.sleep(sleep);
}
if (pub.getText().equals("<Reading schema error: Getting database metadata >")) {
fail("Can't load data, DB not accessible");
}
if (pub.getText().equals("Pending...") && counter < limit) {
bot.sleep(sleep);
counter++;
log.info("Waiting for database loading...");
}
else
{
log.info("DB loaded");
break;
}
}
List<String> tables = Tree.getSubNodes(viewBot, pub);
assertTrue("Table must contain tables", tables.size()> 0);
for (String s : tables) {
log.info("Table:" + s);
}
}
}
| private void createConfigurationFile() {
ConfigurationFile.create(new String[]{prjName,"src"},"hibernate.cfg.xml",false);
}
private void createHibernateConsole() {
open.viewOpen(ActionItem.View.GeneralProjectExplorer.LABEL);
eclipse.createNew(EntityType.HIBERNATE_CONSOLE);
// Hibernate Console Dialog has no title
SWTBotShell shell = bot.waitForShell("");
createMainTab(shell);
createOptionTab(shell);
createClasspathTab(shell);
createMappingsTab(shell);
createCommonTab(shell);
bot.button(IDELabel.Button.FINISH).click();
bot.waitUntil(shellCloses(shell));
util.waitForNonIgnoredJobs();
}
private void createMainTab(SWTBotShell shell) {
bot.cTabItem(IDELabel.HBConsoleWizard.MAIN_TAB).activate();
bot.textWithLabel("Name:").setText(prjName);
bot.textWithLabelInGroup("","Configuration file:").setText(prjName + "/src/hibernate.cfg.xml");
}
private void createOptionTab(SWTBotShell shell) {
shell.setFocus();
bot.cTabItem(IDELabel.HBConsoleWizard.OPTIONS_TAB).activate();
String dialect = DatabaseHelper.getDialect(TestConfigurator.currentConfig.getDB().dbType);
bot.comboBoxWithLabelInGroup("", IDELabel.HBConsoleWizard.DATABASE_DIALECT).setSelection(dialect);
}
private void createClasspathTab(SWTBotShell shell) {
shell.setFocus();
bot.cTabItem(IDELabel.HBConsoleWizard.CLASSPATH_TAB).activate();
}
private void createMappingsTab(SWTBotShell shell) {
shell.setFocus();
bot.cTabItem(IDELabel.HBConsoleWizard.MAPPINGS_TAB).activate();
}
private void createCommonTab(SWTBotShell shell) {
shell.setFocus();
bot.cTabItem(IDELabel.HBConsoleWizard.COMMON_TAB).activate();
}
private void expandDatabaseInConsole() {
SWTBot viewBot = open.viewOpen(ActionItem.View.HibernateHibernateConfigurations.LABEL).bot();
SWTBotTreeItem db = Tree.select(viewBot, prjName,"Database");
db.expand();
// expand PUBLIC node or whatever
SWTBotTreeItem pub = db.getItems()[0];
final int limit = 10; // 10s
final int sleep = 1000;
int counter = 0;
while(counter < limit) {
if (pub.widget.isDisposed()) {
pub = db.getItems()[0];
bot.sleep(sleep);
}
if (pub.getText().equals("<Reading schema error: Getting database metadata >")) {
fail("Can't load data, DB not accessible");
}
if (pub.getText().equals("Pending...") && counter < limit) {
bot.sleep(sleep);
counter++;
log.info("Waiting for database loading...");
}
else
{
log.info("DB loaded");
break;
}
}
List<String> tables = Tree.getSubNodes(viewBot, pub);
assertTrue("Table must contain tables", tables.size()> 0);
for (String s : tables) {
log.info("Table:" + s);
}
}
}
|
diff --git a/src/java/tajmi/src/tajmi/instances/som/NaiveFindBestMatchFunc.java b/src/java/tajmi/src/tajmi/instances/som/NaiveFindBestMatchFunc.java
index a5f9a15..b2c2650 100644
--- a/src/java/tajmi/src/tajmi/instances/som/NaiveFindBestMatchFunc.java
+++ b/src/java/tajmi/src/tajmi/instances/som/NaiveFindBestMatchFunc.java
@@ -1,40 +1,42 @@
package tajmi.instances.som;
import scala.Tuple2;
import tajmi.abstracts.DistanceFunc;
import tajmi.abstracts.som.FindBestMatchFunc;
import tajmi.som.Field;
import tajmi.som.Position;
/**
*
* @author badi
*/
public class NaiveFindBestMatchFunc extends FindBestMatchFunc {
public Tuple2<Position, Object> call() {
// setup
Field field = getField();
DistanceFunc distancef = getDistancef();
+ Object datum = getDatum();
/* implementation: */
double best_distance = Double.POSITIVE_INFINITY,
current_distance = Double.POSITIVE_INFINITY;
Tuple2<Position, Object> best = null;
for (Tuple2<Position, Object> elem : field) {
if (best == null) {
best = elem;
+ best_distance = distancef.params(datum, best._2()).call();
continue;
} else {
- current_distance = distancef.params(best._2(), elem._2()).call();
+ current_distance = distancef.params(datum, elem._2()).call();
if (current_distance < best_distance)
best = elem;
}
}
return best;
}
}
| false | true | public Tuple2<Position, Object> call() {
// setup
Field field = getField();
DistanceFunc distancef = getDistancef();
/* implementation: */
double best_distance = Double.POSITIVE_INFINITY,
current_distance = Double.POSITIVE_INFINITY;
Tuple2<Position, Object> best = null;
for (Tuple2<Position, Object> elem : field) {
if (best == null) {
best = elem;
continue;
} else {
current_distance = distancef.params(best._2(), elem._2()).call();
if (current_distance < best_distance)
best = elem;
}
}
return best;
}
| public Tuple2<Position, Object> call() {
// setup
Field field = getField();
DistanceFunc distancef = getDistancef();
Object datum = getDatum();
/* implementation: */
double best_distance = Double.POSITIVE_INFINITY,
current_distance = Double.POSITIVE_INFINITY;
Tuple2<Position, Object> best = null;
for (Tuple2<Position, Object> elem : field) {
if (best == null) {
best = elem;
best_distance = distancef.params(datum, best._2()).call();
continue;
} else {
current_distance = distancef.params(datum, elem._2()).call();
if (current_distance < best_distance)
best = elem;
}
}
return best;
}
|
diff --git a/src/main/us/exultant/ahs/terminal/Stty.java b/src/main/us/exultant/ahs/terminal/Stty.java
index a76c6cc..892c237 100644
--- a/src/main/us/exultant/ahs/terminal/Stty.java
+++ b/src/main/us/exultant/ahs/terminal/Stty.java
@@ -1,40 +1,42 @@
package us.exultant.ahs.terminal;
import us.exultant.ahs.util.*;
import us.exultant.ahs.io.*;
import java.io.*;
class Stty {
public static void getAngry() {
if (System.console() == null) throw new MajorBug("this program is not attached to a console, but is trying to set console modes");
// save the console settings from before we start mucking things up
final String $restoreStty = stty("-g");
+ System.err.println("restore:"+$restoreStty);
// Add a shutdown hook to restore console's state when we exit.
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
stty($restoreStty);
+ stty("echo"); // for some reason the restore string doesn't seem to do this (?@!??!)
System.console().printf(TermCodes.CSI+"f"+TermCodes.REND_RESET+TermCodes.CLEAR_SCREEN);
}
});
// muck things up
stty(
- "-icanon min 1" + // set the console to be character-buffered instead of line-buffered
- "-echo" // disable character echoing
+ "-icanon min 1 " + // set the console to be character-buffered instead of line-buffered
+ "-echo " // disable character echoing
); // raw iutf8 icrnl opost isig
}
private static String stty(final String $args) {
try {
Process $proc = Runtime.getRuntime().exec(new String[] { "sh", "-c", "stty " + $args + " < /dev/tty" });
$proc.waitFor();
return IOForge.readString($proc.getInputStream());
} catch (IOException $e) {
throw new Error("failed to control console mode", $e);
} catch (InterruptedException $e) {
throw new Error("failed to control console mode", $e);
}
}
}
| false | true | public static void getAngry() {
if (System.console() == null) throw new MajorBug("this program is not attached to a console, but is trying to set console modes");
// save the console settings from before we start mucking things up
final String $restoreStty = stty("-g");
// Add a shutdown hook to restore console's state when we exit.
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
stty($restoreStty);
System.console().printf(TermCodes.CSI+"f"+TermCodes.REND_RESET+TermCodes.CLEAR_SCREEN);
}
});
// muck things up
stty(
"-icanon min 1" + // set the console to be character-buffered instead of line-buffered
"-echo" // disable character echoing
); // raw iutf8 icrnl opost isig
}
| public static void getAngry() {
if (System.console() == null) throw new MajorBug("this program is not attached to a console, but is trying to set console modes");
// save the console settings from before we start mucking things up
final String $restoreStty = stty("-g");
System.err.println("restore:"+$restoreStty);
// Add a shutdown hook to restore console's state when we exit.
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
stty($restoreStty);
stty("echo"); // for some reason the restore string doesn't seem to do this (?@!??!)
System.console().printf(TermCodes.CSI+"f"+TermCodes.REND_RESET+TermCodes.CLEAR_SCREEN);
}
});
// muck things up
stty(
"-icanon min 1 " + // set the console to be character-buffered instead of line-buffered
"-echo " // disable character echoing
); // raw iutf8 icrnl opost isig
}
|
diff --git a/src/main/java/org/hey/HadoopInAction/ch401/MyJob.java b/src/main/java/org/hey/HadoopInAction/ch401/MyJob.java
index d16a5c6..3335ccc 100644
--- a/src/main/java/org/hey/HadoopInAction/ch401/MyJob.java
+++ b/src/main/java/org/hey/HadoopInAction/ch401/MyJob.java
@@ -1,84 +1,84 @@
package org.hey.HadoopInAction.ch401;
import java.io.IOException;
import java.util.Iterator;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
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.KeyValueTextInputFormat;
import org.apache.hadoop.mapred.MapReduceBase;
import org.apache.hadoop.mapred.Mapper;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.Reducer;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.mapred.TextOutputFormat;
import org.apache.hadoop.util.*;
public class MyJob extends Configured implements Tool{
public static class MapClass extends MapReduceBase implements Mapper<Text, Text, Text, Text> {
@Override
public void map(Text key, Text value, OutputCollector<Text, Text> output,
Reporter reporter) throws IOException {
output.collect(value, key);
}
}
public static class Reduce extends MapReduceBase implements Reducer<Text, Text, Text, IntWritable> {
@Override
public void reduce(Text key, Iterator<Text> values,
OutputCollector<Text, IntWritable> output, Reporter reporter)
throws IOException {
int count = 0;
while (values.hasNext())
{
values.next();
count++;
}
output.collect(key, new IntWritable(count));
}
}
@Override
public int run(String[] args) throws Exception {
Configuration conf = getConf();
JobConf job = new JobConf(conf, MyJob.class);
Path in = new Path(args[0]);
Path out = new Path(args[1]);
FileInputFormat.setInputPaths(job, in);
FileOutputFormat.setOutputPath(job, out);
job.setJobName("Yubo's patent Citation Job");
job.setMapperClass(MapClass.class);
job.setReducerClass(Reduce.class);
job.setInputFormat(KeyValueTextInputFormat.class);
job.setOutputFormat(TextOutputFormat.class);
job.setOutputKeyClass(Text.class);
- job.setOutputValueClass(IntWritable.class);
+ job.setOutputValueClass(Text.class);
job.set("key.value.separator.in.input.line", ",");
JobClient.runJob(job);
return 0;
}
public static void main(String[] args) throws Exception
{
int res = ToolRunner.run(new Configuration(), new MyJob(), args);
System.exit(res);
}
}
| true | true | public int run(String[] args) throws Exception {
Configuration conf = getConf();
JobConf job = new JobConf(conf, MyJob.class);
Path in = new Path(args[0]);
Path out = new Path(args[1]);
FileInputFormat.setInputPaths(job, in);
FileOutputFormat.setOutputPath(job, out);
job.setJobName("Yubo's patent Citation Job");
job.setMapperClass(MapClass.class);
job.setReducerClass(Reduce.class);
job.setInputFormat(KeyValueTextInputFormat.class);
job.setOutputFormat(TextOutputFormat.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
job.set("key.value.separator.in.input.line", ",");
JobClient.runJob(job);
return 0;
}
| public int run(String[] args) throws Exception {
Configuration conf = getConf();
JobConf job = new JobConf(conf, MyJob.class);
Path in = new Path(args[0]);
Path out = new Path(args[1]);
FileInputFormat.setInputPaths(job, in);
FileOutputFormat.setOutputPath(job, out);
job.setJobName("Yubo's patent Citation Job");
job.setMapperClass(MapClass.class);
job.setReducerClass(Reduce.class);
job.setInputFormat(KeyValueTextInputFormat.class);
job.setOutputFormat(TextOutputFormat.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Text.class);
job.set("key.value.separator.in.input.line", ",");
JobClient.runJob(job);
return 0;
}
|
diff --git a/biojava3-structure/src/main/java/org/biojava/bio/structure/io/LocalCacheStructureProvider.java b/biojava3-structure/src/main/java/org/biojava/bio/structure/io/LocalCacheStructureProvider.java
index 31635667c..c5b3df9ae 100644
--- a/biojava3-structure/src/main/java/org/biojava/bio/structure/io/LocalCacheStructureProvider.java
+++ b/biojava3-structure/src/main/java/org/biojava/bio/structure/io/LocalCacheStructureProvider.java
@@ -1,185 +1,186 @@
package org.biojava.bio.structure.io;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import org.biojava.bio.structure.Structure;
import org.biojava.bio.structure.StructureException;
import org.biojava.bio.structure.align.ce.AbstractUserArgumentProcessor;
/** Provides structures based on locally cached PDB files. The path where to cache this can be configured in FileParsingParameters
*
*
* @author Andreas Prlic
*
*/
public class LocalCacheStructureProvider implements StructureProvider{
FileParsingParameters params ;
String path;
public static final String lineSplit = System.getProperty("file.separator");
private static final boolean isSplit = true;
private static final String BIOL_DIR = "BIOL_UNITS";
public LocalCacheStructureProvider(){
params = new FileParsingParameters();
// set the path to cache files
String defaultPath = System.getProperty(AbstractUserArgumentProcessor.PDB_DIR);
if ( defaultPath == null) {
String property = "java.io.tmpdir";
defaultPath = System.getProperty(property);
}
setPath(defaultPath);
}
/** directory where to find PDB files */
public void setPath(String p){
System.setProperty(AbstractUserArgumentProcessor.PDB_DIR,p);
path = p ;
if ( !(path.endsWith(lineSplit) ) )
path = path + lineSplit;
}
/**
* Returns the path value.
* @return a String representing the path value
* @see #setPath
*
*/
public String getPath() {
return path ;
}
public Structure getStructureById(String pdbId) throws IOException {
PDBFileReader reader = getPdbFilereader();
return reader.getStructureById(pdbId);
}
private PDBFileReader getPdbFilereader(){
PDBFileReader reader = new PDBFileReader();
reader.setPath(path);
reader.setAutoFetch(true);
reader.setFileParsingParameters(params);
reader.setPdbDirectorySplit(isSplit);
return reader;
}
/** Returns the first available biological unit for the PDB ID.
* Note: the biological units are represented using multiple models.
* You need to work with all models to get the full set of atoms.
*
* @throws IOException
*
*/
public Structure getBiologicalUnit(String pdbId) throws StructureException, IOException {
if (pdbId == null || pdbId.length()< 4)
throw new StructureException("This does not look like a valid PDB ID! (" + pdbId + ")");
String middle = pdbId.substring(1,3).toLowerCase();
String dir = path + BIOL_DIR;
File tmp1 = new File(dir);
if ( ! tmp1.exists()){
tmp1.mkdir();
}
dir = dir+lineSplit+middle;
File directoryCheck = new File (dir);
if ( ! directoryCheck.exists()){
directoryCheck.mkdir();
}
File tempFile =new File(dir + lineSplit+"pdb"+ pdbId.toLowerCase()+".ent.gz");
if (! tempFile.exists()){
// we need to download the file
downloadBiolUnit(pdbId.toLowerCase(),tempFile);
}
PDBFileReader reader = getPdbFilereader();
return reader.getStructure(tempFile);
}
/** Download the biological unit file
*
* @param pdbId the PDB ID
* @param localFile where to store the file locally
*/
- private void downloadBiolUnit(String pdbId, File localFile){
+ private void downloadBiolUnit(String pdbId, File localFile) throws IOException{
String u = "http://www.rcsb.org/pdb/files/%s.pdb1.gz";
String ur = String.format(u,pdbId);
System.out.println("Fetching " + ur);
// prepare destination
System.out.println("writing to " + localFile);
try {
URL url = new URL(ur);
InputStream uStream = url.openStream();
InputStream conn = new GZIPInputStream(uStream);
FileOutputStream outPut = new FileOutputStream(localFile);
GZIPOutputStream gzOutPut = new GZIPOutputStream(outPut);
PrintWriter pw = new PrintWriter(gzOutPut);
BufferedReader fileBuffer = new BufferedReader(new InputStreamReader(conn));
String line;
while ((line = fileBuffer.readLine()) != null) {
pw.println(line);
}
pw.flush();
pw.close();
outPut.flush();
outPut.close();
conn.close();
uStream.close();
} catch (Exception e){
System.err.println("Problem while downloading PDB ID " + pdbId + " from FTP server." );
- e.printStackTrace();
+ //e.printStackTrace();
+ throw new IOException("Could not download biol. unit for PDB ID " + pdbId);
}
}
public void setFileParsingParameters(FileParsingParameters params) {
this.params = params;
}
public FileParsingParameters getFileParsingParameters() {
return params;
}
}
| false | true | private void downloadBiolUnit(String pdbId, File localFile){
String u = "http://www.rcsb.org/pdb/files/%s.pdb1.gz";
String ur = String.format(u,pdbId);
System.out.println("Fetching " + ur);
// prepare destination
System.out.println("writing to " + localFile);
try {
URL url = new URL(ur);
InputStream uStream = url.openStream();
InputStream conn = new GZIPInputStream(uStream);
FileOutputStream outPut = new FileOutputStream(localFile);
GZIPOutputStream gzOutPut = new GZIPOutputStream(outPut);
PrintWriter pw = new PrintWriter(gzOutPut);
BufferedReader fileBuffer = new BufferedReader(new InputStreamReader(conn));
String line;
while ((line = fileBuffer.readLine()) != null) {
pw.println(line);
}
pw.flush();
pw.close();
outPut.flush();
outPut.close();
conn.close();
uStream.close();
} catch (Exception e){
System.err.println("Problem while downloading PDB ID " + pdbId + " from FTP server." );
e.printStackTrace();
}
}
| private void downloadBiolUnit(String pdbId, File localFile) throws IOException{
String u = "http://www.rcsb.org/pdb/files/%s.pdb1.gz";
String ur = String.format(u,pdbId);
System.out.println("Fetching " + ur);
// prepare destination
System.out.println("writing to " + localFile);
try {
URL url = new URL(ur);
InputStream uStream = url.openStream();
InputStream conn = new GZIPInputStream(uStream);
FileOutputStream outPut = new FileOutputStream(localFile);
GZIPOutputStream gzOutPut = new GZIPOutputStream(outPut);
PrintWriter pw = new PrintWriter(gzOutPut);
BufferedReader fileBuffer = new BufferedReader(new InputStreamReader(conn));
String line;
while ((line = fileBuffer.readLine()) != null) {
pw.println(line);
}
pw.flush();
pw.close();
outPut.flush();
outPut.close();
conn.close();
uStream.close();
} catch (Exception e){
System.err.println("Problem while downloading PDB ID " + pdbId + " from FTP server." );
//e.printStackTrace();
throw new IOException("Could not download biol. unit for PDB ID " + pdbId);
}
}
|
diff --git a/apps/AppChooser/src/org/ros/android/app_chooser/AppChooser.java b/apps/AppChooser/src/org/ros/android/app_chooser/AppChooser.java
index fada199..f00ff9a 100644
--- a/apps/AppChooser/src/org/ros/android/app_chooser/AppChooser.java
+++ b/apps/AppChooser/src/org/ros/android/app_chooser/AppChooser.java
@@ -1,308 +1,308 @@
/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2011, Willow Garage, Inc.
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, 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.ros.android.app_chooser;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Button;
import org.ros.MessageListener;
import org.ros.Node;
import org.ros.exception.RosInitException;
import org.ros.message.app_manager.App;
import org.ros.message.app_manager.AppList;
import ros.android.activity.RosAppActivity;
import android.widget.LinearLayout;
import ros.android.util.Dashboard;
import android.app.AlertDialog;
import android.content.DialogInterface;
import org.ros.ServiceResponseListener;
import org.ros.message.app_manager.StatusCodes;
import org.ros.service.app_manager.StopApp;
import java.util.ArrayList;
/**
* Show a grid of applications that a given robot is capable of, and launch
* whichever is chosen.
*/
public class AppChooser extends RosAppActivity {
private ArrayList<App> availableAppsCache;
private ArrayList<App> runningAppsCache;
private long availableAppsCacheTime;
private Dashboard.DashboardInterface dashboard;
private TextView robotNameView;
private Button deactivate;
private Button stopApps;
public AppChooser() {
availableAppsCache = new ArrayList<App>();
availableAppsCacheTime = 0;
dashboard = null;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
robotNameView = (TextView) findViewById(R.id.robot_name_view);
deactivate = (Button) findViewById(R.id.deactivate_robot);
deactivate.setVisibility(deactivate.GONE);
stopApps = (Button) findViewById(R.id.stop_applications);
stopApps.setVisibility(stopApps.GONE);
}
@Override
protected void onResume() {
super.onResume();
setStatus("");
// TODO: start spinner
updateAppList(availableAppsCache, runningAppsCache);
}
/**
* Must be run in UI thread.
*
* @param apps
*/
protected void updateAppList(final ArrayList<App> apps, final ArrayList<App> runningApps) {
Log.i("RosAndroid", "updating gridview");
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new AppAdapter(AppChooser.this, apps, runningApps));
gridview.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
AppLauncher.launch(AppChooser.this, apps.get(position));
}
});
if (runningApps != null) {
if (runningApps.toArray().length != 0) {
stopApps.setVisibility(stopApps.VISIBLE);
} else {
stopApps.setVisibility(stopApps.GONE);
}
}
Log.i("RosAndroid", "gridview updated");
}
@Override
protected void onNodeCreate(Node node) {
Log.i("RosAndroid", "AppChooser.onNodeCreate");
try {
super.onNodeCreate(node);
} catch( Exception ex ) {
safeSetStatus("Failed: " + ex.getMessage());
node = null;
return;
}
runOnUiThread(new Runnable() {
@Override
public void run() {
robotNameView.setText(getCurrentRobot().getRobotName());
}});
if (dashboard != null) {
runOnUiThread(new Runnable() {
@Override
public void run() {
LinearLayout top = (LinearLayout)findViewById(R.id.top_bar);
top.removeView((View)dashboard);
dashboard = null;
}});
}
if (getCurrentRobot().getRobotId().getControlUri() != null) {
runOnUiThread(new Runnable() {
@Override
public void run() {
deactivate.setVisibility(deactivate.VISIBLE);
}});
}
dashboard = Dashboard.createDashboard(node, this);
if (dashboard != null) {
runOnUiThread(new Runnable() {
@Override
public void run() {
LinearLayout top = (LinearLayout)findViewById(R.id.top_bar);
LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
- Dashboard.DashboardInferface dash = dashboard;
+ Dashboard.DashboardInterface dash = dashboard;
if (dash != null) {
top.addView((View)dash, lparams);
}
}});
try {
dashboard.start(node);
} catch (RosInitException ex) {
safeSetStatus("Failed: " + ex.getMessage());
}
}
if (appManager == null) {
safeSetStatus("Robot not available");
return;
}
//Note, I've temporarily disabled caching.
if (System.currentTimeMillis() - availableAppsCacheTime >= 0 * 1000) {
Log.i("RosAndroid", "sending list apps request");
}
try {
appManager.addAppListCallback(new MessageListener<AppList>() {
@Override
public void onNewMessage(AppList message) {
availableAppsCache = message.available_apps;
runningAppsCache = message.running_apps;
Log.i("RosAndroid", "ListApps.Response: " + availableAppsCache.size() + " apps");
availableAppsCacheTime = System.currentTimeMillis();
runOnUiThread(new Runnable() {
@Override
public void run() {
updateAppList(availableAppsCache, runningAppsCache);
}
});
}
});
} catch (RosInitException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
protected void onNodeDestroy(Node node) {
Log.i("RosAndroid", "onNodeDestroy");
super.onNodeDestroy(node);
runOnUiThread(new Runnable() {
@Override
public void run() {
deactivate.setVisibility(deactivate.GONE);
}});
if (dashboard != null) {
dashboard.stop();
runOnUiThread(new Runnable() {
@Override
public void run() {
LinearLayout top = (LinearLayout)findViewById(R.id.top_bar);
top.removeView((View)dashboard);
}});
}
}
public void chooseNewMasterClicked(View view) {
chooseNewMaster();
}
public void deactivateRobotClicked(View view) {
new AlertDialog.Builder(this).setTitle("Deactivate Robot").setCancelable(false)
.setMessage("Are you sure you want to deactivate the robot? This will power down the"
+ " robot's arms and allow others to run custom software on it.")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) { terminateRobot(); }})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) { }})
.create().show();
}
public void stopApplicationsClicked(View view) {
appManager.stopApp("*", new ServiceResponseListener<StopApp.Response>() {
@Override
public void onSuccess(StopApp.Response message) {
if (message.stopped || message.error_code == StatusCodes.NOT_RUNNING) {
//safeSetStatus("Stopped.");
} else {
//safeSetStatus("ERROR: " + message.message);
}
}
@Override
public void onFailure(Exception e) {
//safeSetStatus("Failed: cannot contact robot!");
}
});
}
private void setStatus(String status_message) {
TextView statusView = (TextView) findViewById(R.id.status_view);
if (statusView != null) {
statusView.setText(status_message);
}
}
private void safeSetStatus(final String statusMessage) {
final TextView statusView = (TextView) findViewById(R.id.status_view);
if (statusView != null) {
statusView.post(new Runnable() {
@Override
public void run() {
statusView.setText(statusMessage);
}
});
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.app_chooser_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.kill:
android.os.Process.killProcess(android.os.Process.myPid());
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
| true | true | protected void onNodeCreate(Node node) {
Log.i("RosAndroid", "AppChooser.onNodeCreate");
try {
super.onNodeCreate(node);
} catch( Exception ex ) {
safeSetStatus("Failed: " + ex.getMessage());
node = null;
return;
}
runOnUiThread(new Runnable() {
@Override
public void run() {
robotNameView.setText(getCurrentRobot().getRobotName());
}});
if (dashboard != null) {
runOnUiThread(new Runnable() {
@Override
public void run() {
LinearLayout top = (LinearLayout)findViewById(R.id.top_bar);
top.removeView((View)dashboard);
dashboard = null;
}});
}
if (getCurrentRobot().getRobotId().getControlUri() != null) {
runOnUiThread(new Runnable() {
@Override
public void run() {
deactivate.setVisibility(deactivate.VISIBLE);
}});
}
dashboard = Dashboard.createDashboard(node, this);
if (dashboard != null) {
runOnUiThread(new Runnable() {
@Override
public void run() {
LinearLayout top = (LinearLayout)findViewById(R.id.top_bar);
LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
Dashboard.DashboardInferface dash = dashboard;
if (dash != null) {
top.addView((View)dash, lparams);
}
}});
try {
dashboard.start(node);
} catch (RosInitException ex) {
safeSetStatus("Failed: " + ex.getMessage());
}
}
if (appManager == null) {
safeSetStatus("Robot not available");
return;
}
//Note, I've temporarily disabled caching.
if (System.currentTimeMillis() - availableAppsCacheTime >= 0 * 1000) {
Log.i("RosAndroid", "sending list apps request");
}
try {
appManager.addAppListCallback(new MessageListener<AppList>() {
@Override
public void onNewMessage(AppList message) {
availableAppsCache = message.available_apps;
runningAppsCache = message.running_apps;
Log.i("RosAndroid", "ListApps.Response: " + availableAppsCache.size() + " apps");
availableAppsCacheTime = System.currentTimeMillis();
runOnUiThread(new Runnable() {
@Override
public void run() {
updateAppList(availableAppsCache, runningAppsCache);
}
});
}
});
} catch (RosInitException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
| protected void onNodeCreate(Node node) {
Log.i("RosAndroid", "AppChooser.onNodeCreate");
try {
super.onNodeCreate(node);
} catch( Exception ex ) {
safeSetStatus("Failed: " + ex.getMessage());
node = null;
return;
}
runOnUiThread(new Runnable() {
@Override
public void run() {
robotNameView.setText(getCurrentRobot().getRobotName());
}});
if (dashboard != null) {
runOnUiThread(new Runnable() {
@Override
public void run() {
LinearLayout top = (LinearLayout)findViewById(R.id.top_bar);
top.removeView((View)dashboard);
dashboard = null;
}});
}
if (getCurrentRobot().getRobotId().getControlUri() != null) {
runOnUiThread(new Runnable() {
@Override
public void run() {
deactivate.setVisibility(deactivate.VISIBLE);
}});
}
dashboard = Dashboard.createDashboard(node, this);
if (dashboard != null) {
runOnUiThread(new Runnable() {
@Override
public void run() {
LinearLayout top = (LinearLayout)findViewById(R.id.top_bar);
LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
Dashboard.DashboardInterface dash = dashboard;
if (dash != null) {
top.addView((View)dash, lparams);
}
}});
try {
dashboard.start(node);
} catch (RosInitException ex) {
safeSetStatus("Failed: " + ex.getMessage());
}
}
if (appManager == null) {
safeSetStatus("Robot not available");
return;
}
//Note, I've temporarily disabled caching.
if (System.currentTimeMillis() - availableAppsCacheTime >= 0 * 1000) {
Log.i("RosAndroid", "sending list apps request");
}
try {
appManager.addAppListCallback(new MessageListener<AppList>() {
@Override
public void onNewMessage(AppList message) {
availableAppsCache = message.available_apps;
runningAppsCache = message.running_apps;
Log.i("RosAndroid", "ListApps.Response: " + availableAppsCache.size() + " apps");
availableAppsCacheTime = System.currentTimeMillis();
runOnUiThread(new Runnable() {
@Override
public void run() {
updateAppList(availableAppsCache, runningAppsCache);
}
});
}
});
} catch (RosInitException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
|
diff --git a/nuxeo-launcher-commons/src/test/java/org/nuxeo/launcher/config/JBossConfiguratorTest.java b/nuxeo-launcher-commons/src/test/java/org/nuxeo/launcher/config/JBossConfiguratorTest.java
index 7a5f2d48..c8b0caf9 100644
--- a/nuxeo-launcher-commons/src/test/java/org/nuxeo/launcher/config/JBossConfiguratorTest.java
+++ b/nuxeo-launcher-commons/src/test/java/org/nuxeo/launcher/config/JBossConfiguratorTest.java
@@ -1,265 +1,265 @@
/*
* (C) Copyright 2010-2011 Nuxeo SAS (http://nuxeo.com/) and contributors.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl.html
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Contributors:
* Julien Carsique
*
* $Id$
*/
package org.nuxeo.launcher.config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Properties;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Before;
import org.junit.Test;
/**
* @author jcarsique
*
*/
public class JBossConfiguratorTest {
private static final Log log = LogFactory.getLog(JBossConfiguratorTest.class);
private ConfigurationGenerator configGenerator;
private ConfigurationGenerator configGenerator2;
private File nuxeoHome;
String propertyToGenerate;
String propertyToGenerate2;
@Before
public void setUp() throws Exception {
File nuxeoConf = getResourceFile("configurator/nuxeo.conf");
System.setProperty(ConfigurationGenerator.NUXEO_CONF,
nuxeoConf.getPath());
nuxeoHome = File.createTempFile("nuxeo", null);
nuxeoHome.delete();
nuxeoHome.mkdirs();
System.setProperty(ConfigurationGenerator.NUXEO_HOME,
nuxeoHome.getPath());
System.setProperty(Environment.NUXEO_DATA_DIR, new File(nuxeoHome,
"data").getPath());
propertyToGenerate = "<config-property name=\""
+ "property\" type=\"java.lang.String\">URL=jdbc:h2:"
+ System.getProperty(Environment.NUXEO_DATA_DIR)
+ File.separator + "h2" + File.separator
+ "testinclude;AUTO_SERVER=true</config-property>";
System.setProperty(Environment.NUXEO_LOG_DIR,
new File(nuxeoHome, "log").getPath());
// Windows path
propertyToGenerate2 = "<config-property name=\""
+ "property\" type=\"java.lang.String\">URL=jdbc:h2:"
- + "C:\\nuxeo-dm-5.4.2-SNAPSHOT-jboss\\server\\default\\data\\NXRuntime\\data"
+ + "C:\\nuxeo-dm-5.4.3-SNAPSHOT-jboss\\server\\default\\data\\NXRuntime\\data"
+ File.separator + "h2" + File.separator
+ "testinclude;AUTO_SERVER=true</config-property>";
FileUtils.copyDirectory(getResourceFile("templates/jboss"), new File(
nuxeoHome, "templates"));
System.setProperty("jboss.home.dir", nuxeoHome.getPath());
configGenerator = new ConfigurationGenerator();
nuxeoConf = getResourceFile("configurator/nuxeo.conf2");
System.setProperty(ConfigurationGenerator.NUXEO_CONF,
nuxeoConf.getPath());
configGenerator2 = new ConfigurationGenerator();
}
@Test
public void testConfiguration() throws Exception {
configGenerator.init();
assertTrue(configGenerator.isConfigurable());
log.debug(configGenerator.getIncludedTemplates());
Properties config = configGenerator.getUserConfig();
assertEquals("default,testinclude",
config.getProperty("nuxeo.templates"));
assertEquals("true", config.getProperty("test.nuxeo.conf"));
assertEquals("true", config.getProperty("test.nuxeo.defaults"));
assertEquals("true",
config.getProperty("test.nuxeo.defaults.template.1"));
assertEquals("true",
config.getProperty("test.nuxeo.defaults.template.2"));
assertEquals("true",
config.getProperty("test.nuxeo.conf.override.defaults"));
assertEquals(
"true",
config.getProperty("test.nuxeo.conf.override.defaults.template"));
assertEquals("testinclude", config.getProperty("nuxeo.db.name"));
assertEquals("sa", config.getProperty("nuxeo.db.user"));
}
@Test
public void testGenerateFiles() throws Exception {
configGenerator.run();
log.debug(configGenerator.getIncludedTemplates());
File configDir = new File(nuxeoHome, "server/"
+ JBossConfigurator.DEFAULT_CONFIGURATION
+ "/deploy/nuxeo.ear/config");
assertTrue(new File(configDir, "test2").exists());
File generatedFile = new File(configDir.getParentFile(),
"datasources/default-repository-ds.xml");
String generatedProperty = new BufferedReader(new FileReader(
generatedFile)).readLine();
assertEquals(generatedProperty, propertyToGenerate, generatedProperty);
// Check windows path parsing
generatedFile = new File(configDir.getParentFile(),
"datasources/default-repository-ds_2.xml");
generatedProperty = new BufferedReader(new FileReader(generatedFile)).readLine();
assertEquals(generatedProperty, propertyToGenerate2, generatedProperty);
// ignored extension must not be parsed
generatedFile = new File(configDir.getParentFile(),
"config/extension.ignored");
generatedProperty = new BufferedReader(new FileReader(generatedFile)).readLine();
String originalProperty = new BufferedReader(new FileReader(new File(
nuxeoHome, "templates/common/config/extension.ignored"))).readLine();
assertEquals(generatedProperty, originalProperty, generatedProperty);
// properly manage files containing accents
generatedFile = new File(configDir.getParentFile(),
"config/file-with-accents.xml");
generatedProperty = new BufferedReader(new FileReader(generatedFile)).readLine();
originalProperty = new BufferedReader(new FileReader(new File(
nuxeoHome, "templates/common/config/file-with-accents.xml"))).readLine();
assertEquals(generatedProperty, originalProperty, generatedProperty);
}
@Test
public void testGenerateFiles2() throws Exception {
configGenerator2.run();
log.debug(configGenerator2.getIncludedTemplates());
Properties config = configGenerator2.getUserConfig();
assertEquals("common,testinclude2",
config.getProperty("nuxeo.templates"));
assertEquals("true", config.getProperty("test.nuxeo.conf"));
assertEquals("true", config.getProperty("test.nuxeo.defaults"));
assertEquals("true",
config.getProperty("test.nuxeo.defaults.template.1"));
assertEquals("true",
config.getProperty("test.nuxeo.defaults.template.2"));
assertEquals("true",
config.getProperty("test.nuxeo.conf.override.defaults"));
assertEquals(
"true",
config.getProperty("test.nuxeo.conf.override.defaults.template"));
assertEquals("testinclude", config.getProperty("nuxeo.db.name"));
assertEquals("sa", config.getProperty("nuxeo.db.user"));
File configDir = new File(nuxeoHome, "server/"
+ JBossConfigurator.DEFAULT_CONFIGURATION
+ "/deploy/nuxeo.ear/config");
assertTrue(new File(configDir, "test2").exists());
File generatedFile = new File(configDir.getParentFile(),
"datasources/default-repository-ds.xml");
String generatedProperty = new BufferedReader(new FileReader(
generatedFile)).readLine();
assertEquals(generatedProperty, propertyToGenerate, generatedProperty);
}
@Test
public void testForceGeneration() throws ConfigurationException {
configGenerator2.run();
File testFile = new File(nuxeoHome, "server/"
+ JBossConfigurator.DEFAULT_CONFIGURATION
+ "/deploy/nuxeo.ear/config");
testFile = new File(testFile, "test2");
testFile.delete();
configGenerator2.setForceGeneration(true);
configGenerator2.run();
assertTrue(testFile.exists());
}
public File getResourceFile(String resource) {
URL url = getClass().getClassLoader().getResource(resource);
try {
return new File(URLDecoder.decode(url.getPath(), "UTF-8"));
} catch (UnsupportedEncodingException e) {
log.error(e);
return null;
}
}
@Test
public void testReplaceBackslashes() throws ConfigurationException,
IOException {
File windowsConf = getResourceFile("configurator/windows.conf");
File newWindowsConf = File.createTempFile("nuxeo", ".conf");
FileUtils.copyFile(windowsConf, newWindowsConf);
System.setProperty(ConfigurationGenerator.NUXEO_CONF,
newWindowsConf.getPath());
configGenerator = new ConfigurationGenerator();
configGenerator.replaceBackslashes();
BufferedReader br = new BufferedReader(new FileReader(newWindowsConf));
String generatedProperty = br.readLine();
propertyToGenerate = "nuxeo.log.dir=C:/ProgramData/path with space/nuxeo/log";
assertEquals(generatedProperty, propertyToGenerate, generatedProperty);
generatedProperty = br.readLine();
propertyToGenerate = "some.parameter=d\\u00e9connexion-${nuxeo.log.dir}";
assertEquals(generatedProperty, propertyToGenerate, generatedProperty);
}
@Test
public void testSaveFilteredConfiguration() throws ConfigurationException {
String propToSave1 = "nuxeo.notification.eMailSubjectPrefix";
String valueToSave1 = "[Nuxeo test]";
String propToSave2 = "mail.smtp.username";
String valueToSave2 = "tester";
configGenerator.init();
assertTrue(configGenerator.isConfigurable());
HashMap<String, String> parameters = new HashMap<String, String>();
parameters.put(propToSave1, valueToSave1);
configGenerator.saveFilteredConfiguration(parameters);
File nuxeoConf = getResourceFile("configurator/nuxeo.conf");
System.setProperty(ConfigurationGenerator.NUXEO_CONF,
nuxeoConf.getPath());
configGenerator = new ConfigurationGenerator();
configGenerator.init();
Properties userConfig = configGenerator.getUserConfig();
assertEquals("Save fail", valueToSave1,
userConfig.getProperty(propToSave1));
parameters.clear();
parameters.put(propToSave2, valueToSave2);
configGenerator.saveFilteredConfiguration(parameters);
configGenerator = new ConfigurationGenerator();
configGenerator.init();
userConfig = configGenerator.getUserConfig();
assertEquals("Save fail", valueToSave2,
userConfig.getProperty(propToSave2));
assertEquals("Save fail", valueToSave1,
userConfig.getProperty(propToSave1));
}
}
| true | true | public void setUp() throws Exception {
File nuxeoConf = getResourceFile("configurator/nuxeo.conf");
System.setProperty(ConfigurationGenerator.NUXEO_CONF,
nuxeoConf.getPath());
nuxeoHome = File.createTempFile("nuxeo", null);
nuxeoHome.delete();
nuxeoHome.mkdirs();
System.setProperty(ConfigurationGenerator.NUXEO_HOME,
nuxeoHome.getPath());
System.setProperty(Environment.NUXEO_DATA_DIR, new File(nuxeoHome,
"data").getPath());
propertyToGenerate = "<config-property name=\""
+ "property\" type=\"java.lang.String\">URL=jdbc:h2:"
+ System.getProperty(Environment.NUXEO_DATA_DIR)
+ File.separator + "h2" + File.separator
+ "testinclude;AUTO_SERVER=true</config-property>";
System.setProperty(Environment.NUXEO_LOG_DIR,
new File(nuxeoHome, "log").getPath());
// Windows path
propertyToGenerate2 = "<config-property name=\""
+ "property\" type=\"java.lang.String\">URL=jdbc:h2:"
+ "C:\\nuxeo-dm-5.4.2-SNAPSHOT-jboss\\server\\default\\data\\NXRuntime\\data"
+ File.separator + "h2" + File.separator
+ "testinclude;AUTO_SERVER=true</config-property>";
FileUtils.copyDirectory(getResourceFile("templates/jboss"), new File(
nuxeoHome, "templates"));
System.setProperty("jboss.home.dir", nuxeoHome.getPath());
configGenerator = new ConfigurationGenerator();
nuxeoConf = getResourceFile("configurator/nuxeo.conf2");
System.setProperty(ConfigurationGenerator.NUXEO_CONF,
nuxeoConf.getPath());
configGenerator2 = new ConfigurationGenerator();
}
| public void setUp() throws Exception {
File nuxeoConf = getResourceFile("configurator/nuxeo.conf");
System.setProperty(ConfigurationGenerator.NUXEO_CONF,
nuxeoConf.getPath());
nuxeoHome = File.createTempFile("nuxeo", null);
nuxeoHome.delete();
nuxeoHome.mkdirs();
System.setProperty(ConfigurationGenerator.NUXEO_HOME,
nuxeoHome.getPath());
System.setProperty(Environment.NUXEO_DATA_DIR, new File(nuxeoHome,
"data").getPath());
propertyToGenerate = "<config-property name=\""
+ "property\" type=\"java.lang.String\">URL=jdbc:h2:"
+ System.getProperty(Environment.NUXEO_DATA_DIR)
+ File.separator + "h2" + File.separator
+ "testinclude;AUTO_SERVER=true</config-property>";
System.setProperty(Environment.NUXEO_LOG_DIR,
new File(nuxeoHome, "log").getPath());
// Windows path
propertyToGenerate2 = "<config-property name=\""
+ "property\" type=\"java.lang.String\">URL=jdbc:h2:"
+ "C:\\nuxeo-dm-5.4.3-SNAPSHOT-jboss\\server\\default\\data\\NXRuntime\\data"
+ File.separator + "h2" + File.separator
+ "testinclude;AUTO_SERVER=true</config-property>";
FileUtils.copyDirectory(getResourceFile("templates/jboss"), new File(
nuxeoHome, "templates"));
System.setProperty("jboss.home.dir", nuxeoHome.getPath());
configGenerator = new ConfigurationGenerator();
nuxeoConf = getResourceFile("configurator/nuxeo.conf2");
System.setProperty(ConfigurationGenerator.NUXEO_CONF,
nuxeoConf.getPath());
configGenerator2 = new ConfigurationGenerator();
}
|
diff --git a/src/main/java/com/sankuai/meituan/hive/udf/D2d.java b/src/main/java/com/sankuai/meituan/hive/udf/D2d.java
index 3fde076..a3f7342 100644
--- a/src/main/java/com/sankuai/meituan/hive/udf/D2d.java
+++ b/src/main/java/com/sankuai/meituan/hive/udf/D2d.java
@@ -1,28 +1,27 @@
package com.sankuai.meituan.hive.udf;
import org.apache.hadoop.hive.ql.exec.UDF;
import java.util.Date;
import java.text.SimpleDateFormat;
/**
* Cast datekey to date, or otherwise
* datekey to date, eg : select dt, d2d(dt, "", "-") from log.blog where dt=20120909 and hour='01' limit 3;
* date to datekey, eg : select regdate, d2d(regdate, '-', '') from dim.user limit 3;
*/
public final class D2d extends UDF {
public String evaluate(final String s, final String sourceSep, final String targetSep) {
if (s == null) {
return null;
}
try {
Date d = new SimpleDateFormat("yyyy" + sourceSep + "MM" + sourceSep + "dd").parse(s);
return new SimpleDateFormat("yyyy" + targetSep + "MM" + targetSep + "dd").format(d);
} catch (Exception ex) {
- System.out.println("d2d Exception");
- System.exit(1);
+ System.out.println("d2d Exception:" + s + " parse error");
}
return null;
}
}
| true | true | public String evaluate(final String s, final String sourceSep, final String targetSep) {
if (s == null) {
return null;
}
try {
Date d = new SimpleDateFormat("yyyy" + sourceSep + "MM" + sourceSep + "dd").parse(s);
return new SimpleDateFormat("yyyy" + targetSep + "MM" + targetSep + "dd").format(d);
} catch (Exception ex) {
System.out.println("d2d Exception");
System.exit(1);
}
return null;
}
| public String evaluate(final String s, final String sourceSep, final String targetSep) {
if (s == null) {
return null;
}
try {
Date d = new SimpleDateFormat("yyyy" + sourceSep + "MM" + sourceSep + "dd").parse(s);
return new SimpleDateFormat("yyyy" + targetSep + "MM" + targetSep + "dd").format(d);
} catch (Exception ex) {
System.out.println("d2d Exception:" + s + " parse error");
}
return null;
}
|
diff --git a/src/org/openstreetmap/josm/gui/dialogs/SelectionListDialog.java b/src/org/openstreetmap/josm/gui/dialogs/SelectionListDialog.java
index dbe45d18..fa01db5b 100644
--- a/src/org/openstreetmap/josm/gui/dialogs/SelectionListDialog.java
+++ b/src/org/openstreetmap/josm/gui/dialogs/SelectionListDialog.java
@@ -1,121 +1,121 @@
// License: GPL. Copyright 2007 by Immanuel Scholz and others
package org.openstreetmap.josm.gui.dialogs;
import static org.openstreetmap.josm.tools.I18n.tr;
import static org.xnap.commons.i18n.I18n.marktr;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedList;
import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import org.openstreetmap.josm.Main;
import org.openstreetmap.josm.data.SelectionChangedListener;
import org.openstreetmap.josm.data.osm.DataSet;
import org.openstreetmap.josm.data.osm.OsmPrimitive;
import org.openstreetmap.josm.gui.OsmPrimitivRenderer;
import org.openstreetmap.josm.gui.SideButton;
/**
* A small tool dialog for displaying the current selection. The selection manager
* respects clicks into the selection list. Ctrl-click will remove entries from
* the list while single click will make the clicked entry the only selection.
*
* @author imi
*/
public class SelectionListDialog extends ToggleDialog implements SelectionChangedListener {
/**
* The selection's list data.
*/
private final DefaultListModel list = new DefaultListModel();
/**
* The display list.
*/
private JList displaylist = new JList(list);
public SelectionListDialog() {
- super(tr("Current Selection"), "selectionlist", tr("Open a selection list window."), KeyEvent.VK_E, 150);
+ super(tr("Current Selection"), "selectionlist", tr("Open a selection list window."), KeyEvent.VK_T, 150);
displaylist.setCellRenderer(new OsmPrimitivRenderer());
displaylist.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
displaylist.addMouseListener(new MouseAdapter(){
@Override public void mouseClicked(MouseEvent e) {
if (e.getClickCount() < 2)
return;
updateMap();
}
});
add(new JScrollPane(displaylist), BorderLayout.CENTER);
JPanel buttonPanel = new JPanel(new GridLayout(1,2));
buttonPanel.add(new SideButton(marktr("Select"), "select", "SelectionList",
tr("Set the selected elements on the map to the selected items in the list above."), new ActionListener(){
public void actionPerformed(ActionEvent e) {
updateMap();
}
}));
buttonPanel.add(new SideButton(marktr("Reload"), "refresh", "SelectionList", tr("Refresh the selection list."), new ActionListener(){
public void actionPerformed(ActionEvent e) {
selectionChanged(Main.ds.getSelected());
}
}));
buttonPanel.add(new SideButton(marktr("Search"), "search", "SelectionList", tr("Search for objects."), Main.main.menu.search));
add(buttonPanel, BorderLayout.SOUTH);
selectionChanged(Main.ds.getSelected());
DataSet.selListeners.add(this);
}
@Override public void setVisible(boolean b) {
super.setVisible(b);
if (b)
selectionChanged(Main.ds.getSelected());
}
/**
* Called when the selection in the dataset changed.
* @param newSelection The new selection array.
*/
public void selectionChanged(Collection<? extends OsmPrimitive> newSelection) {
if (list == null)
return; // selection changed may be received in base class constructor before init
if (!isVisible())
return;
OsmPrimitive[] selArr = new OsmPrimitive[newSelection.size()];
selArr = newSelection.toArray(selArr);
Arrays.sort(selArr);
list.setSize(selArr.length);
int i = 0;
for (OsmPrimitive osm : selArr)
list.setElementAt(osm, i++);
}
/**
* Sets the selection of the map to the current selected items.
*/
public void updateMap() {
Collection<OsmPrimitive> sel = new LinkedList<OsmPrimitive>();
for (int i = 0; i < list.getSize(); ++i)
if (displaylist.isSelectedIndex(i))
sel.add((OsmPrimitive)list.get(i));
Main.ds.setSelected(sel);
}
}
| true | true | public SelectionListDialog() {
super(tr("Current Selection"), "selectionlist", tr("Open a selection list window."), KeyEvent.VK_E, 150);
displaylist.setCellRenderer(new OsmPrimitivRenderer());
displaylist.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
displaylist.addMouseListener(new MouseAdapter(){
@Override public void mouseClicked(MouseEvent e) {
if (e.getClickCount() < 2)
return;
updateMap();
}
});
add(new JScrollPane(displaylist), BorderLayout.CENTER);
JPanel buttonPanel = new JPanel(new GridLayout(1,2));
buttonPanel.add(new SideButton(marktr("Select"), "select", "SelectionList",
tr("Set the selected elements on the map to the selected items in the list above."), new ActionListener(){
public void actionPerformed(ActionEvent e) {
updateMap();
}
}));
buttonPanel.add(new SideButton(marktr("Reload"), "refresh", "SelectionList", tr("Refresh the selection list."), new ActionListener(){
public void actionPerformed(ActionEvent e) {
selectionChanged(Main.ds.getSelected());
}
}));
buttonPanel.add(new SideButton(marktr("Search"), "search", "SelectionList", tr("Search for objects."), Main.main.menu.search));
add(buttonPanel, BorderLayout.SOUTH);
selectionChanged(Main.ds.getSelected());
DataSet.selListeners.add(this);
}
| public SelectionListDialog() {
super(tr("Current Selection"), "selectionlist", tr("Open a selection list window."), KeyEvent.VK_T, 150);
displaylist.setCellRenderer(new OsmPrimitivRenderer());
displaylist.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
displaylist.addMouseListener(new MouseAdapter(){
@Override public void mouseClicked(MouseEvent e) {
if (e.getClickCount() < 2)
return;
updateMap();
}
});
add(new JScrollPane(displaylist), BorderLayout.CENTER);
JPanel buttonPanel = new JPanel(new GridLayout(1,2));
buttonPanel.add(new SideButton(marktr("Select"), "select", "SelectionList",
tr("Set the selected elements on the map to the selected items in the list above."), new ActionListener(){
public void actionPerformed(ActionEvent e) {
updateMap();
}
}));
buttonPanel.add(new SideButton(marktr("Reload"), "refresh", "SelectionList", tr("Refresh the selection list."), new ActionListener(){
public void actionPerformed(ActionEvent e) {
selectionChanged(Main.ds.getSelected());
}
}));
buttonPanel.add(new SideButton(marktr("Search"), "search", "SelectionList", tr("Search for objects."), Main.main.menu.search));
add(buttonPanel, BorderLayout.SOUTH);
selectionChanged(Main.ds.getSelected());
DataSet.selListeners.add(this);
}
|
diff --git a/src/eu/bryants/anthony/toylanguage/compiler/ControlFlowChecker.java b/src/eu/bryants/anthony/toylanguage/compiler/ControlFlowChecker.java
index c3dcdcb..3d754a3 100644
--- a/src/eu/bryants/anthony/toylanguage/compiler/ControlFlowChecker.java
+++ b/src/eu/bryants/anthony/toylanguage/compiler/ControlFlowChecker.java
@@ -1,194 +1,205 @@
package eu.bryants.anthony.toylanguage.compiler;
import java.util.HashSet;
import java.util.Set;
import eu.bryants.anthony.toylanguage.ast.CompilationUnit;
import eu.bryants.anthony.toylanguage.ast.Function;
import eu.bryants.anthony.toylanguage.ast.Parameter;
import eu.bryants.anthony.toylanguage.ast.expression.AdditionExpression;
import eu.bryants.anthony.toylanguage.ast.expression.BooleanLiteralExpression;
import eu.bryants.anthony.toylanguage.ast.expression.BracketedExpression;
import eu.bryants.anthony.toylanguage.ast.expression.ComparisonExpression;
import eu.bryants.anthony.toylanguage.ast.expression.Expression;
import eu.bryants.anthony.toylanguage.ast.expression.FloatingLiteralExpression;
import eu.bryants.anthony.toylanguage.ast.expression.FunctionCallExpression;
import eu.bryants.anthony.toylanguage.ast.expression.IntegerLiteralExpression;
import eu.bryants.anthony.toylanguage.ast.expression.SubtractionExpression;
import eu.bryants.anthony.toylanguage.ast.expression.VariableExpression;
import eu.bryants.anthony.toylanguage.ast.metadata.Variable;
import eu.bryants.anthony.toylanguage.ast.statement.AssignStatement;
import eu.bryants.anthony.toylanguage.ast.statement.Block;
import eu.bryants.anthony.toylanguage.ast.statement.IfStatement;
import eu.bryants.anthony.toylanguage.ast.statement.ReturnStatement;
import eu.bryants.anthony.toylanguage.ast.statement.Statement;
import eu.bryants.anthony.toylanguage.ast.statement.VariableDefinition;
import eu.bryants.anthony.toylanguage.ast.statement.WhileStatement;
/*
* Created on 6 Apr 2012
*/
/**
* @author Anthony Bryant
*/
public class ControlFlowChecker
{
/**
* Checks that the control flow of the specified compilation unit is well defined.
* @param compilationUnit - the CompilationUnit to check
* @throws ConceptualException - if any control flow related errors are detected
*/
public static void checkControlFlow(CompilationUnit compilationUnit) throws ConceptualException
{
for (Function f : compilationUnit.getFunctions())
{
Set<Variable> initializedVariables = new HashSet<Variable>();
for (Parameter p : f.getParameters())
{
initializedVariables.add(p.getVariable());
}
boolean returned = checkControlFlow(f.getBlock(), initializedVariables);
if (!returned)
{
throw new ConceptualException("Function does not always return a value", f.getLexicalPhrase());
}
}
}
/**
* Checks that the control flow of the specified statement is well defined.
* @param statement - the statement to check
* @return true if the statement returns from its enclosing function, false if control flow continues after it
* @throws ConceptualException - if any unreachable code is detected
*/
private static boolean checkControlFlow(Statement statement, Set<Variable> initializedVariables) throws ConceptualException
{
if (statement instanceof AssignStatement)
{
AssignStatement assign = (AssignStatement) statement;
checkUninitializedVariables(assign.getExpression(), initializedVariables);
initializedVariables.add(assign.getResolvedVariable());
return false;
}
else if (statement instanceof Block)
{
boolean returned = false;
for (Statement s : ((Block) statement).getStatements())
{
if (returned)
{
throw new ConceptualException("Unreachable code", s.getLexicalPhrase());
}
returned = checkControlFlow(s, initializedVariables);
}
return returned;
}
else if (statement instanceof IfStatement)
{
IfStatement ifStatement = (IfStatement) statement;
checkUninitializedVariables(ifStatement.getExpression(), initializedVariables);
Statement thenClause = ifStatement.getThenClause();
Statement elseClause = ifStatement.getElseClause();
if (elseClause == null)
{
Set<Variable> thenClauseVariables = new HashSet<Variable>(initializedVariables);
checkControlFlow(thenClause, thenClauseVariables);
return false;
}
Set<Variable> thenClauseVariables = new HashSet<Variable>(initializedVariables);
Set<Variable> elseClauseVariables = new HashSet<Variable>(initializedVariables);
- // don't use a short circuit and ('&&') here, as it could cause elseClauseVariables not to be populated
- boolean returned = checkControlFlow(thenClause, thenClauseVariables) & checkControlFlow(elseClause, elseClauseVariables);
- for (Variable var : thenClauseVariables)
+ boolean thenReturned = checkControlFlow(thenClause, thenClauseVariables);
+ boolean elseReturned = checkControlFlow(elseClause, elseClauseVariables);
+ if (!thenReturned && !elseReturned)
{
- if (elseClauseVariables.contains(var))
+ for (Variable var : thenClauseVariables)
{
- initializedVariables.add(var);
+ if (elseClauseVariables.contains(var))
+ {
+ initializedVariables.add(var);
+ }
}
}
- return returned;
+ else if (!thenReturned && elseReturned)
+ {
+ initializedVariables.addAll(thenClauseVariables);
+ }
+ else if (thenReturned && !elseReturned)
+ {
+ initializedVariables.addAll(elseClauseVariables);
+ }
+ return thenReturned && elseReturned;
}
else if (statement instanceof ReturnStatement)
{
checkUninitializedVariables(((ReturnStatement) statement).getExpression(), initializedVariables);
return true;
}
else if (statement instanceof VariableDefinition)
{
VariableDefinition definition = (VariableDefinition) statement;
if (definition.getExpression() != null)
{
checkUninitializedVariables(definition.getExpression(), initializedVariables);
initializedVariables.add(definition.getVariable());
}
return false;
}
else if (statement instanceof WhileStatement)
{
WhileStatement whileStatement = (WhileStatement) statement;
checkUninitializedVariables(whileStatement.getExpression(), initializedVariables);
Set<Variable> loopVariables = new HashSet<Variable>(initializedVariables);
return checkControlFlow(whileStatement.getStatement(), loopVariables);
}
throw new ConceptualException("Internal control flow checking error: Unknown statement type", statement.getLexicalPhrase());
}
private static void checkUninitializedVariables(Expression expression, Set<Variable> initializedVariables) throws ConceptualException
{
if (expression instanceof AdditionExpression)
{
AdditionExpression additionExpression = (AdditionExpression) expression;
checkUninitializedVariables(additionExpression.getLeftSubExpression(), initializedVariables);
checkUninitializedVariables(additionExpression.getRightSubExpression(), initializedVariables);
}
else if (expression instanceof BooleanLiteralExpression)
{
// do nothing
}
else if (expression instanceof BracketedExpression)
{
checkUninitializedVariables(((BracketedExpression) expression).getExpression(), initializedVariables);
}
else if (expression instanceof ComparisonExpression)
{
ComparisonExpression comparisonExpression = (ComparisonExpression) expression;
checkUninitializedVariables(comparisonExpression.getLeftSubExpression(), initializedVariables);
checkUninitializedVariables(comparisonExpression.getRightSubExpression(), initializedVariables);
}
else if (expression instanceof FloatingLiteralExpression)
{
// do nothing
}
else if (expression instanceof FunctionCallExpression)
{
for (Expression e : ((FunctionCallExpression) expression).getArguments())
{
checkUninitializedVariables(e, initializedVariables);
}
}
else if (expression instanceof IntegerLiteralExpression)
{
// do nothing
}
else if (expression instanceof SubtractionExpression)
{
SubtractionExpression subtractionExpression = (SubtractionExpression) expression;
checkUninitializedVariables(subtractionExpression.getLeftSubExpression(), initializedVariables);
checkUninitializedVariables(subtractionExpression.getRightSubExpression(), initializedVariables);
}
else if (expression instanceof VariableExpression)
{
VariableExpression variableExpression = (VariableExpression) expression;
if (!initializedVariables.contains(variableExpression.getResolvedVariable()))
{
throw new ConceptualException("Variable '" + variableExpression.getName() + "' may not be initialized", variableExpression.getLexicalPhrase());
}
}
else
{
throw new ConceptualException("Internal control flow checking error: Unknown expression type", expression.getLexicalPhrase());
}
}
}
| false | true | private static boolean checkControlFlow(Statement statement, Set<Variable> initializedVariables) throws ConceptualException
{
if (statement instanceof AssignStatement)
{
AssignStatement assign = (AssignStatement) statement;
checkUninitializedVariables(assign.getExpression(), initializedVariables);
initializedVariables.add(assign.getResolvedVariable());
return false;
}
else if (statement instanceof Block)
{
boolean returned = false;
for (Statement s : ((Block) statement).getStatements())
{
if (returned)
{
throw new ConceptualException("Unreachable code", s.getLexicalPhrase());
}
returned = checkControlFlow(s, initializedVariables);
}
return returned;
}
else if (statement instanceof IfStatement)
{
IfStatement ifStatement = (IfStatement) statement;
checkUninitializedVariables(ifStatement.getExpression(), initializedVariables);
Statement thenClause = ifStatement.getThenClause();
Statement elseClause = ifStatement.getElseClause();
if (elseClause == null)
{
Set<Variable> thenClauseVariables = new HashSet<Variable>(initializedVariables);
checkControlFlow(thenClause, thenClauseVariables);
return false;
}
Set<Variable> thenClauseVariables = new HashSet<Variable>(initializedVariables);
Set<Variable> elseClauseVariables = new HashSet<Variable>(initializedVariables);
// don't use a short circuit and ('&&') here, as it could cause elseClauseVariables not to be populated
boolean returned = checkControlFlow(thenClause, thenClauseVariables) & checkControlFlow(elseClause, elseClauseVariables);
for (Variable var : thenClauseVariables)
{
if (elseClauseVariables.contains(var))
{
initializedVariables.add(var);
}
}
return returned;
}
else if (statement instanceof ReturnStatement)
{
checkUninitializedVariables(((ReturnStatement) statement).getExpression(), initializedVariables);
return true;
}
else if (statement instanceof VariableDefinition)
{
VariableDefinition definition = (VariableDefinition) statement;
if (definition.getExpression() != null)
{
checkUninitializedVariables(definition.getExpression(), initializedVariables);
initializedVariables.add(definition.getVariable());
}
return false;
}
else if (statement instanceof WhileStatement)
{
WhileStatement whileStatement = (WhileStatement) statement;
checkUninitializedVariables(whileStatement.getExpression(), initializedVariables);
Set<Variable> loopVariables = new HashSet<Variable>(initializedVariables);
return checkControlFlow(whileStatement.getStatement(), loopVariables);
}
throw new ConceptualException("Internal control flow checking error: Unknown statement type", statement.getLexicalPhrase());
}
| private static boolean checkControlFlow(Statement statement, Set<Variable> initializedVariables) throws ConceptualException
{
if (statement instanceof AssignStatement)
{
AssignStatement assign = (AssignStatement) statement;
checkUninitializedVariables(assign.getExpression(), initializedVariables);
initializedVariables.add(assign.getResolvedVariable());
return false;
}
else if (statement instanceof Block)
{
boolean returned = false;
for (Statement s : ((Block) statement).getStatements())
{
if (returned)
{
throw new ConceptualException("Unreachable code", s.getLexicalPhrase());
}
returned = checkControlFlow(s, initializedVariables);
}
return returned;
}
else if (statement instanceof IfStatement)
{
IfStatement ifStatement = (IfStatement) statement;
checkUninitializedVariables(ifStatement.getExpression(), initializedVariables);
Statement thenClause = ifStatement.getThenClause();
Statement elseClause = ifStatement.getElseClause();
if (elseClause == null)
{
Set<Variable> thenClauseVariables = new HashSet<Variable>(initializedVariables);
checkControlFlow(thenClause, thenClauseVariables);
return false;
}
Set<Variable> thenClauseVariables = new HashSet<Variable>(initializedVariables);
Set<Variable> elseClauseVariables = new HashSet<Variable>(initializedVariables);
boolean thenReturned = checkControlFlow(thenClause, thenClauseVariables);
boolean elseReturned = checkControlFlow(elseClause, elseClauseVariables);
if (!thenReturned && !elseReturned)
{
for (Variable var : thenClauseVariables)
{
if (elseClauseVariables.contains(var))
{
initializedVariables.add(var);
}
}
}
else if (!thenReturned && elseReturned)
{
initializedVariables.addAll(thenClauseVariables);
}
else if (thenReturned && !elseReturned)
{
initializedVariables.addAll(elseClauseVariables);
}
return thenReturned && elseReturned;
}
else if (statement instanceof ReturnStatement)
{
checkUninitializedVariables(((ReturnStatement) statement).getExpression(), initializedVariables);
return true;
}
else if (statement instanceof VariableDefinition)
{
VariableDefinition definition = (VariableDefinition) statement;
if (definition.getExpression() != null)
{
checkUninitializedVariables(definition.getExpression(), initializedVariables);
initializedVariables.add(definition.getVariable());
}
return false;
}
else if (statement instanceof WhileStatement)
{
WhileStatement whileStatement = (WhileStatement) statement;
checkUninitializedVariables(whileStatement.getExpression(), initializedVariables);
Set<Variable> loopVariables = new HashSet<Variable>(initializedVariables);
return checkControlFlow(whileStatement.getStatement(), loopVariables);
}
throw new ConceptualException("Internal control flow checking error: Unknown statement type", statement.getLexicalPhrase());
}
|
diff --git a/edu/mit/wi/haploview/association/PermutationTestSet.java b/edu/mit/wi/haploview/association/PermutationTestSet.java
index c4fb611..4bdcb74 100755
--- a/edu/mit/wi/haploview/association/PermutationTestSet.java
+++ b/edu/mit/wi/haploview/association/PermutationTestSet.java
@@ -1,350 +1,355 @@
package edu.mit.wi.haploview.association;
import edu.mit.wi.pedfile.PedFile;
import edu.mit.wi.pedfile.PedFileException;
import edu.mit.wi.pedfile.Individual;
import edu.mit.wi.haploview.*;
import java.util.*;
import java.io.File;
import java.io.IOException;
import java.io.BufferedWriter;
import java.io.FileWriter;
public class PermutationTestSet implements Constants{
public static final int SINGLE_ONLY = 0;
public static final int SINGLE_PLUS_BLOCKS = 1;
public static final int CUSTOM = 2;
private int permutationCount;
private int bestExceededCount;
private double bestObsChiSq;
private String bestObsName;
private PedFile pedFile;
private AssociationTestSet activeAssocTestSet, custAssocTestSet, defaultAssocTestSet;
private double[] permBestChiSq;
public boolean stopProcessing;
//this variable is updated as permutations are performed. Once
//this variable reaches the value of permutationCount, permutation tests have all completed.
private int permutationsPerformed;
private double permBestOverallChiSq;
private int selectionType;
public PermutationTestSet(int permCount, PedFile pf, AssociationTestSet cats, AssociationTestSet dats){
if(permCount > 0) {
permutationCount = permCount;
} else {
permCount = 0;
}
pedFile = pf;
custAssocTestSet = cats;
defaultAssocTestSet = dats;
if (custAssocTestSet != null){
activeAssocTestSet = custAssocTestSet;
}else{
activeAssocTestSet = defaultAssocTestSet;
}
}
public void doPermutations(int selection) {
selectionType = selection;
stopProcessing = false;
Vector curResults = null;
if (selectionType == CUSTOM){
activeAssocTestSet = custAssocTestSet;
}else{
activeAssocTestSet = defaultAssocTestSet;
}
double curBest = 0;
String curName = "";
for(int i=0;i<activeAssocTestSet.getFilteredResults().size();i++) {
AssociationResult tmpRes = (AssociationResult) activeAssocTestSet.getFilteredResults().get(i);
for (int j = 0; j < tmpRes.getAlleleCount(); j++){
if (tmpRes.getChiSquare(j) > curBest){
curName = tmpRes.getDisplayName(j);
curBest = tmpRes.getChiSquare(j);
}
}
}
bestObsChiSq = curBest;
bestObsName = curName;
Haplotype[][] haplotypes = new Haplotype[activeAssocTestSet.getHaplotypeAssociationResults().size()][];
Iterator hitr = activeAssocTestSet.getHaplotypeAssociationResults().iterator();
int count = 0;
while (hitr.hasNext()){
haplotypes[count] = ((HaplotypeAssociationResult)hitr.next()).getHaps();
count++;
}
Vector snpSet = new Vector();
Iterator sitr = activeAssocTestSet.getFilteredResults().iterator();
while (sitr.hasNext()){
Object o = sitr.next();
if (o instanceof MarkerAssociationResult){
SNP snp = ((MarkerAssociationResult)o).getSnp();
snpSet.add(snp);
}
}
//we need to make fake Haplotype objects so that we can use the getcounts() and getChiSq() methods of
//AssociationResult. kludgetastic!
Haplotype[][] fakeHaplos;
if(haplotypes != null) {
fakeHaplos = new Haplotype[haplotypes.length][];
for(int j=0;j<haplotypes.length;j++) {
fakeHaplos[j] = new Haplotype[haplotypes[j].length];
for(int k=0;k<haplotypes[j].length;k++) {
fakeHaplos[j][k] = new Haplotype(haplotypes[j][k].getGeno(),haplotypes[j][k].getPercentage(),
haplotypes[j][k].getMarkers(), haplotypes[j][k].getEM());
}
}
} else {
fakeHaplos = new Haplotype[0][0];
}
//need to use the same affected status for marker and haplotype association tests in case control,
//so affectedStatus stores the shuffled affected status
Vector affectedStatus = null;
if(Options.getAssocTest() == ASSOC_CC) {
Vector indList = pedFile.getUnrelatedIndividuals();
affectedStatus = new Vector();
for(int j=0;j<indList.size();j++) {
affectedStatus.add(new Integer(((Individual)indList.elementAt(j)).getAffectedStatus()));
}
}
//need to use the same coin toss for marker and haplotype association tests in trio tdt,
//so permuteInd stores whether each individual is permuted
- Vector permuteInd = new Vector(pedFile.getAllIndividuals().size());
+ //we start by creating a vector of the right size, but with a bunch of nulls
+ //since ea. permutation (below) will set the values in the vector
+ Vector permuteInd = new Vector();
+ for (int i = 0; i < pedFile.getAllIndividuals().size(); i++){
+ permuteInd.add(null);
+ }
permutationsPerformed = 0;
bestExceededCount = 0;
double[] chiSqs = new double[permutationCount];
permBestOverallChiSq = 0;
//start the permuting!
for(int i=0;i<permutationCount; i++) {
//this variable gets set by the thread we're running if it wants us to stop
if(stopProcessing) {
break;
}
//begin single marker association test
if (Options.getAssocTest() == ASSOC_TRIO){
try {
for(int j =0;j<pedFile.getAllIndividuals().size();j++) {
if(Math.random() < .5) {
permuteInd.set(j,Boolean.valueOf(true));
} else {
permuteInd.set(j,Boolean.valueOf(false));
}
}
curResults = new AssociationTestSet(pedFile, permuteInd, snpSet).getMarkerAssociationResults();
} catch(PedFileException pfe) {
}
}else if (Options.getAssocTest() == ASSOC_CC){
Collections.shuffle(affectedStatus);
try{
curResults = new AssociationTestSet(pedFile,affectedStatus, snpSet).getMarkerAssociationResults();
}catch (PedFileException pfe){
}
}
//end of marker association test
if (selectionType != SINGLE_ONLY){
//begin haplotype association test
if(Options.getAssocTest() == ASSOC_TRIO) {
for(int j=0;j<fakeHaplos.length;j++) {
EM curEM = fakeHaplos[j][0].getEM();
curEM.doAssociationTests(null,permuteInd);
for(int k=0;k<fakeHaplos[j].length;k++) {
fakeHaplos[j][k].setTransCount(curEM.getTransCount(k));
fakeHaplos[j][k].setUntransCount(curEM.getUntransCount(k));
}
}
} else if(Options.getAssocTest() == ASSOC_CC) {
for(int j=0;j<fakeHaplos.length;j++) {
EM curEM = fakeHaplos[j][0].getEM();
curEM.doAssociationTests(affectedStatus,null);
for(int k=0;k<fakeHaplos[j].length;k++) {
fakeHaplos[j][k].setCaseCount(curEM.getCaseCount(k));
fakeHaplos[j][k].setControlCount(curEM.getControlCount(k));
}
}
}
if(Options.getAssocTest() == ASSOC_TRIO || Options.getAssocTest() == ASSOC_CC) {
AssociationTestSet ats = null;
if (activeAssocTestSet.getFilterAlleles() == null){
ats = new AssociationTestSet(fakeHaplos, null);
}else{
try{
ats = new AssociationTestSet(fakeHaplos,null,activeAssocTestSet.getFilterAlleles());
}catch (HaploViewException hve){
}
}
curResults.addAll(ats.getResults());
}
//end of haplotype association test
}
//find the best chi square from all the tests
double tempBestChiSquare = 0;
for(int j=0; j<curResults.size();j++) {
AssociationResult tempResult = (AssociationResult) curResults.elementAt(j);
for (int k = 0; k < tempResult.getAlleleCount(); k++){
if(tempResult.getChiSquare(k) > tempBestChiSquare) {
tempBestChiSquare = tempResult.getChiSquare(k);
}
}
}
chiSqs[i] = tempBestChiSquare;
if (chiSqs[i] >= bestObsChiSq){
bestExceededCount++;
}
if(chiSqs[i] > permBestOverallChiSq){
permBestOverallChiSq = chiSqs[i];
}
permutationsPerformed++;
}
permBestChiSq = new double[permutationsPerformed];
for (int i = 0; i < permutationsPerformed; i++){
permBestChiSq[i] = chiSqs[i];
}
Arrays.sort(permBestChiSq);
}
public double getBestPermChiSquare() {
return permBestOverallChiSq;
}
public double getPermPValue(double obsChiSq) {
int observedExceeds =0;
for (int i = 0; i < permutationsPerformed; i++){
if (permBestChiSq[i] < obsChiSq){
observedExceeds++;
}else{
break;
}
}
return 1-((double)observedExceeds / (double)permutationsPerformed);
}
public int getPermutationsPerformed() {
return permutationsPerformed;
}
public void setPermutationCount(int c) {
if(c >= 0) {
permutationCount = c;
} else {
permutationCount = 0;
}
}
public int getPermutationCount() {
return permutationCount;
}
public double getBestObsChiSq(){
return bestObsChiSq;
}
public String getBestObsName(){
return bestObsName;
}
public Vector getResults() {
Vector results = new Vector();
//dont loop through if we haven't done any permutations yet
if(permutationsPerformed > 0) {
for(int i=0;i<activeAssocTestSet.getFilteredResults().size();i++) {
AssociationResult tmpRes = (AssociationResult) activeAssocTestSet.getFilteredResults().get(i);
if (selectionType == SINGLE_ONLY && tmpRes instanceof HaplotypeAssociationResult){
//if we're not permuting the haps in blocks, don't add them to the results vector.
continue;
}
for (int j = 0; j < tmpRes.getAlleleCount(); j++){
Vector fieldValues = new Vector();
fieldValues.add(tmpRes.getDisplayName(j));
fieldValues.add(String.valueOf(tmpRes.getChiSquare(j)));
fieldValues.add(Util.formatPValue(getPermPValue(tmpRes.getChiSquare(j))));
results.add(fieldValues);
if (tmpRes instanceof MarkerAssociationResult){
break;
}
}
}
Collections.sort(results,new SigResComparator());
}
return results;
}
public int getBestExceededCount() {
return bestExceededCount;
}
public double[] getPermBestChiSq() {
return permBestChiSq;
}
public void writeResultsToFile(File outFile) throws IOException {
Vector results = getResults();
BufferedWriter out = new BufferedWriter(new FileWriter(outFile));
out.write("#"+getPermutationsPerformed()+" permutations performed.");
out.newLine();
if (getPermutationsPerformed() > 0){
out.write("Name\tChi Square\tPermutation p-value");
out.newLine();
for(int i=0;i<results.size();i++) {
Vector tempRes = (Vector) results.get(i);
StringBuffer line = new StringBuffer();
for(int j=0;j<tempRes.size()-1;j++) {
line.append(tempRes.get(j));
line.append("\t");
}
line.append(tempRes.get(tempRes.size()-1));
out.write(line.toString());
out.newLine();
}
}
out.close();
}
public boolean isCustom() {
return activeAssocTestSet.isCustom();
}
class SigResComparator implements Comparator{
public int compare(Object o1, Object o2) {
Double d1 = Double.valueOf(((String)((Vector)o1).elementAt(2)));
Double d2 = Double.valueOf(((String)((Vector)o2).elementAt(2)));
return d1.compareTo(d2);
}
}
}
| true | true | public void doPermutations(int selection) {
selectionType = selection;
stopProcessing = false;
Vector curResults = null;
if (selectionType == CUSTOM){
activeAssocTestSet = custAssocTestSet;
}else{
activeAssocTestSet = defaultAssocTestSet;
}
double curBest = 0;
String curName = "";
for(int i=0;i<activeAssocTestSet.getFilteredResults().size();i++) {
AssociationResult tmpRes = (AssociationResult) activeAssocTestSet.getFilteredResults().get(i);
for (int j = 0; j < tmpRes.getAlleleCount(); j++){
if (tmpRes.getChiSquare(j) > curBest){
curName = tmpRes.getDisplayName(j);
curBest = tmpRes.getChiSquare(j);
}
}
}
bestObsChiSq = curBest;
bestObsName = curName;
Haplotype[][] haplotypes = new Haplotype[activeAssocTestSet.getHaplotypeAssociationResults().size()][];
Iterator hitr = activeAssocTestSet.getHaplotypeAssociationResults().iterator();
int count = 0;
while (hitr.hasNext()){
haplotypes[count] = ((HaplotypeAssociationResult)hitr.next()).getHaps();
count++;
}
Vector snpSet = new Vector();
Iterator sitr = activeAssocTestSet.getFilteredResults().iterator();
while (sitr.hasNext()){
Object o = sitr.next();
if (o instanceof MarkerAssociationResult){
SNP snp = ((MarkerAssociationResult)o).getSnp();
snpSet.add(snp);
}
}
//we need to make fake Haplotype objects so that we can use the getcounts() and getChiSq() methods of
//AssociationResult. kludgetastic!
Haplotype[][] fakeHaplos;
if(haplotypes != null) {
fakeHaplos = new Haplotype[haplotypes.length][];
for(int j=0;j<haplotypes.length;j++) {
fakeHaplos[j] = new Haplotype[haplotypes[j].length];
for(int k=0;k<haplotypes[j].length;k++) {
fakeHaplos[j][k] = new Haplotype(haplotypes[j][k].getGeno(),haplotypes[j][k].getPercentage(),
haplotypes[j][k].getMarkers(), haplotypes[j][k].getEM());
}
}
} else {
fakeHaplos = new Haplotype[0][0];
}
//need to use the same affected status for marker and haplotype association tests in case control,
//so affectedStatus stores the shuffled affected status
Vector affectedStatus = null;
if(Options.getAssocTest() == ASSOC_CC) {
Vector indList = pedFile.getUnrelatedIndividuals();
affectedStatus = new Vector();
for(int j=0;j<indList.size();j++) {
affectedStatus.add(new Integer(((Individual)indList.elementAt(j)).getAffectedStatus()));
}
}
//need to use the same coin toss for marker and haplotype association tests in trio tdt,
//so permuteInd stores whether each individual is permuted
Vector permuteInd = new Vector(pedFile.getAllIndividuals().size());
permutationsPerformed = 0;
bestExceededCount = 0;
double[] chiSqs = new double[permutationCount];
permBestOverallChiSq = 0;
//start the permuting!
for(int i=0;i<permutationCount; i++) {
//this variable gets set by the thread we're running if it wants us to stop
if(stopProcessing) {
break;
}
//begin single marker association test
if (Options.getAssocTest() == ASSOC_TRIO){
try {
for(int j =0;j<pedFile.getAllIndividuals().size();j++) {
if(Math.random() < .5) {
permuteInd.set(j,Boolean.valueOf(true));
} else {
permuteInd.set(j,Boolean.valueOf(false));
}
}
curResults = new AssociationTestSet(pedFile, permuteInd, snpSet).getMarkerAssociationResults();
} catch(PedFileException pfe) {
}
}else if (Options.getAssocTest() == ASSOC_CC){
Collections.shuffle(affectedStatus);
try{
curResults = new AssociationTestSet(pedFile,affectedStatus, snpSet).getMarkerAssociationResults();
}catch (PedFileException pfe){
}
}
//end of marker association test
if (selectionType != SINGLE_ONLY){
//begin haplotype association test
if(Options.getAssocTest() == ASSOC_TRIO) {
for(int j=0;j<fakeHaplos.length;j++) {
EM curEM = fakeHaplos[j][0].getEM();
curEM.doAssociationTests(null,permuteInd);
for(int k=0;k<fakeHaplos[j].length;k++) {
fakeHaplos[j][k].setTransCount(curEM.getTransCount(k));
fakeHaplos[j][k].setUntransCount(curEM.getUntransCount(k));
}
}
} else if(Options.getAssocTest() == ASSOC_CC) {
for(int j=0;j<fakeHaplos.length;j++) {
EM curEM = fakeHaplos[j][0].getEM();
curEM.doAssociationTests(affectedStatus,null);
for(int k=0;k<fakeHaplos[j].length;k++) {
fakeHaplos[j][k].setCaseCount(curEM.getCaseCount(k));
fakeHaplos[j][k].setControlCount(curEM.getControlCount(k));
}
}
}
if(Options.getAssocTest() == ASSOC_TRIO || Options.getAssocTest() == ASSOC_CC) {
AssociationTestSet ats = null;
if (activeAssocTestSet.getFilterAlleles() == null){
ats = new AssociationTestSet(fakeHaplos, null);
}else{
try{
ats = new AssociationTestSet(fakeHaplos,null,activeAssocTestSet.getFilterAlleles());
}catch (HaploViewException hve){
}
}
curResults.addAll(ats.getResults());
}
//end of haplotype association test
}
//find the best chi square from all the tests
double tempBestChiSquare = 0;
for(int j=0; j<curResults.size();j++) {
AssociationResult tempResult = (AssociationResult) curResults.elementAt(j);
for (int k = 0; k < tempResult.getAlleleCount(); k++){
if(tempResult.getChiSquare(k) > tempBestChiSquare) {
tempBestChiSquare = tempResult.getChiSquare(k);
}
}
}
chiSqs[i] = tempBestChiSquare;
if (chiSqs[i] >= bestObsChiSq){
bestExceededCount++;
}
if(chiSqs[i] > permBestOverallChiSq){
permBestOverallChiSq = chiSqs[i];
}
permutationsPerformed++;
}
permBestChiSq = new double[permutationsPerformed];
for (int i = 0; i < permutationsPerformed; i++){
permBestChiSq[i] = chiSqs[i];
}
Arrays.sort(permBestChiSq);
}
| public void doPermutations(int selection) {
selectionType = selection;
stopProcessing = false;
Vector curResults = null;
if (selectionType == CUSTOM){
activeAssocTestSet = custAssocTestSet;
}else{
activeAssocTestSet = defaultAssocTestSet;
}
double curBest = 0;
String curName = "";
for(int i=0;i<activeAssocTestSet.getFilteredResults().size();i++) {
AssociationResult tmpRes = (AssociationResult) activeAssocTestSet.getFilteredResults().get(i);
for (int j = 0; j < tmpRes.getAlleleCount(); j++){
if (tmpRes.getChiSquare(j) > curBest){
curName = tmpRes.getDisplayName(j);
curBest = tmpRes.getChiSquare(j);
}
}
}
bestObsChiSq = curBest;
bestObsName = curName;
Haplotype[][] haplotypes = new Haplotype[activeAssocTestSet.getHaplotypeAssociationResults().size()][];
Iterator hitr = activeAssocTestSet.getHaplotypeAssociationResults().iterator();
int count = 0;
while (hitr.hasNext()){
haplotypes[count] = ((HaplotypeAssociationResult)hitr.next()).getHaps();
count++;
}
Vector snpSet = new Vector();
Iterator sitr = activeAssocTestSet.getFilteredResults().iterator();
while (sitr.hasNext()){
Object o = sitr.next();
if (o instanceof MarkerAssociationResult){
SNP snp = ((MarkerAssociationResult)o).getSnp();
snpSet.add(snp);
}
}
//we need to make fake Haplotype objects so that we can use the getcounts() and getChiSq() methods of
//AssociationResult. kludgetastic!
Haplotype[][] fakeHaplos;
if(haplotypes != null) {
fakeHaplos = new Haplotype[haplotypes.length][];
for(int j=0;j<haplotypes.length;j++) {
fakeHaplos[j] = new Haplotype[haplotypes[j].length];
for(int k=0;k<haplotypes[j].length;k++) {
fakeHaplos[j][k] = new Haplotype(haplotypes[j][k].getGeno(),haplotypes[j][k].getPercentage(),
haplotypes[j][k].getMarkers(), haplotypes[j][k].getEM());
}
}
} else {
fakeHaplos = new Haplotype[0][0];
}
//need to use the same affected status for marker and haplotype association tests in case control,
//so affectedStatus stores the shuffled affected status
Vector affectedStatus = null;
if(Options.getAssocTest() == ASSOC_CC) {
Vector indList = pedFile.getUnrelatedIndividuals();
affectedStatus = new Vector();
for(int j=0;j<indList.size();j++) {
affectedStatus.add(new Integer(((Individual)indList.elementAt(j)).getAffectedStatus()));
}
}
//need to use the same coin toss for marker and haplotype association tests in trio tdt,
//so permuteInd stores whether each individual is permuted
//we start by creating a vector of the right size, but with a bunch of nulls
//since ea. permutation (below) will set the values in the vector
Vector permuteInd = new Vector();
for (int i = 0; i < pedFile.getAllIndividuals().size(); i++){
permuteInd.add(null);
}
permutationsPerformed = 0;
bestExceededCount = 0;
double[] chiSqs = new double[permutationCount];
permBestOverallChiSq = 0;
//start the permuting!
for(int i=0;i<permutationCount; i++) {
//this variable gets set by the thread we're running if it wants us to stop
if(stopProcessing) {
break;
}
//begin single marker association test
if (Options.getAssocTest() == ASSOC_TRIO){
try {
for(int j =0;j<pedFile.getAllIndividuals().size();j++) {
if(Math.random() < .5) {
permuteInd.set(j,Boolean.valueOf(true));
} else {
permuteInd.set(j,Boolean.valueOf(false));
}
}
curResults = new AssociationTestSet(pedFile, permuteInd, snpSet).getMarkerAssociationResults();
} catch(PedFileException pfe) {
}
}else if (Options.getAssocTest() == ASSOC_CC){
Collections.shuffle(affectedStatus);
try{
curResults = new AssociationTestSet(pedFile,affectedStatus, snpSet).getMarkerAssociationResults();
}catch (PedFileException pfe){
}
}
//end of marker association test
if (selectionType != SINGLE_ONLY){
//begin haplotype association test
if(Options.getAssocTest() == ASSOC_TRIO) {
for(int j=0;j<fakeHaplos.length;j++) {
EM curEM = fakeHaplos[j][0].getEM();
curEM.doAssociationTests(null,permuteInd);
for(int k=0;k<fakeHaplos[j].length;k++) {
fakeHaplos[j][k].setTransCount(curEM.getTransCount(k));
fakeHaplos[j][k].setUntransCount(curEM.getUntransCount(k));
}
}
} else if(Options.getAssocTest() == ASSOC_CC) {
for(int j=0;j<fakeHaplos.length;j++) {
EM curEM = fakeHaplos[j][0].getEM();
curEM.doAssociationTests(affectedStatus,null);
for(int k=0;k<fakeHaplos[j].length;k++) {
fakeHaplos[j][k].setCaseCount(curEM.getCaseCount(k));
fakeHaplos[j][k].setControlCount(curEM.getControlCount(k));
}
}
}
if(Options.getAssocTest() == ASSOC_TRIO || Options.getAssocTest() == ASSOC_CC) {
AssociationTestSet ats = null;
if (activeAssocTestSet.getFilterAlleles() == null){
ats = new AssociationTestSet(fakeHaplos, null);
}else{
try{
ats = new AssociationTestSet(fakeHaplos,null,activeAssocTestSet.getFilterAlleles());
}catch (HaploViewException hve){
}
}
curResults.addAll(ats.getResults());
}
//end of haplotype association test
}
//find the best chi square from all the tests
double tempBestChiSquare = 0;
for(int j=0; j<curResults.size();j++) {
AssociationResult tempResult = (AssociationResult) curResults.elementAt(j);
for (int k = 0; k < tempResult.getAlleleCount(); k++){
if(tempResult.getChiSquare(k) > tempBestChiSquare) {
tempBestChiSquare = tempResult.getChiSquare(k);
}
}
}
chiSqs[i] = tempBestChiSquare;
if (chiSqs[i] >= bestObsChiSq){
bestExceededCount++;
}
if(chiSqs[i] > permBestOverallChiSq){
permBestOverallChiSq = chiSqs[i];
}
permutationsPerformed++;
}
permBestChiSq = new double[permutationsPerformed];
for (int i = 0; i < permutationsPerformed; i++){
permBestChiSq[i] = chiSqs[i];
}
Arrays.sort(permBestChiSq);
}
|
diff --git a/providers/gogrid/src/test/java/org/jclouds/gogrid/compute/GoGridComputeServiceLiveTest.java b/providers/gogrid/src/test/java/org/jclouds/gogrid/compute/GoGridComputeServiceLiveTest.java
index fca45c383..5b648d666 100644
--- a/providers/gogrid/src/test/java/org/jclouds/gogrid/compute/GoGridComputeServiceLiveTest.java
+++ b/providers/gogrid/src/test/java/org/jclouds/gogrid/compute/GoGridComputeServiceLiveTest.java
@@ -1,48 +1,48 @@
/**
*
* Copyright (C) 2011 Cloud Conscious, LLC. <[email protected]>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.gogrid.compute;
import org.jclouds.compute.BaseComputeServiceLiveTest;
import org.jclouds.compute.domain.ExecResponse;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.sshj.config.SshjSshClientModule;
import org.testng.annotations.Test;
import com.google.inject.Module;
/**
* @author Oleksiy Yarmula
*/
//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire
@Test(groups = "live", singleThreaded = true, testName = "GoGridComputeServiceLiveTest")
public class GoGridComputeServiceLiveTest extends BaseComputeServiceLiveTest {
public GoGridComputeServiceLiveTest() {
provider = "gogrid";
}
@Override
protected Module getSshModule() {
return new SshjSshClientModule();
}
protected void checkResponseEqualsHostname(ExecResponse execResponse, NodeMetadata node1) {
// hostname is not completely predictable based on node metadata
- assert execResponse.getOutput().trim().startsWith(node1.getName());
+ assert execResponse.getOutput().trim().startsWith(node1.getName()) : execResponse + ": " + node1;
}
}
| true | true | protected void checkResponseEqualsHostname(ExecResponse execResponse, NodeMetadata node1) {
// hostname is not completely predictable based on node metadata
assert execResponse.getOutput().trim().startsWith(node1.getName());
}
| protected void checkResponseEqualsHostname(ExecResponse execResponse, NodeMetadata node1) {
// hostname is not completely predictable based on node metadata
assert execResponse.getOutput().trim().startsWith(node1.getName()) : execResponse + ": " + node1;
}
|
diff --git a/core/http/server/src/main/java/org/openrdf/http/server/filters/AcceptParamFilter.java b/core/http/server/src/main/java/org/openrdf/http/server/filters/AcceptParamFilter.java
index 7a4f6204d..ed1b63650 100644
--- a/core/http/server/src/main/java/org/openrdf/http/server/filters/AcceptParamFilter.java
+++ b/core/http/server/src/main/java/org/openrdf/http/server/filters/AcceptParamFilter.java
@@ -1,50 +1,49 @@
/*
* Copyright Aduna (http://www.aduna-software.com/) (c) 2009.
*
* Licensed under the Aduna BSD-style license.
*/
package org.openrdf.http.server.filters;
import org.restlet.Context;
import org.restlet.Request;
import org.restlet.Response;
import org.restlet.Restlet;
import org.restlet.data.ClientInfo;
import org.restlet.data.Form;
import org.restlet.engine.http.PreferenceUtils;
import org.restlet.routing.Filter;
import info.aduna.net.http.RequestHeaders;
/**
* Filter that stores any Accept request parameters in the request's headers,
* effectively overriding the existing Accept headers.
*
* @author Arjohn Kampman
*/
public class AcceptParamFilter extends Filter {
public AcceptParamFilter(Context context, Restlet next) {
super(context, next);
}
@Override
protected int beforeHandle(Request request, Response response) {
Form queryParams = request.getResourceRef().getQueryAsForm();
- // FIXME: process the Accept-parameter in a case-insensitive way
- String[] acceptValues = queryParams.getValuesArray(RequestHeaders.ACCEPT);
+ String[] acceptValues = queryParams.getValuesArray(RequestHeaders.ACCEPT, true);
if (acceptValues.length > 0) {
ClientInfo clientInfo = request.getClientInfo();
// Remove all existing media types, the parameter overrides them
clientInfo.getAcceptedMediaTypes().clear();
for (String value : acceptValues) {
PreferenceUtils.parseMediaTypes(value, clientInfo);
}
}
return Filter.CONTINUE;
}
}
| true | true | protected int beforeHandle(Request request, Response response) {
Form queryParams = request.getResourceRef().getQueryAsForm();
// FIXME: process the Accept-parameter in a case-insensitive way
String[] acceptValues = queryParams.getValuesArray(RequestHeaders.ACCEPT);
if (acceptValues.length > 0) {
ClientInfo clientInfo = request.getClientInfo();
// Remove all existing media types, the parameter overrides them
clientInfo.getAcceptedMediaTypes().clear();
for (String value : acceptValues) {
PreferenceUtils.parseMediaTypes(value, clientInfo);
}
}
return Filter.CONTINUE;
}
| protected int beforeHandle(Request request, Response response) {
Form queryParams = request.getResourceRef().getQueryAsForm();
String[] acceptValues = queryParams.getValuesArray(RequestHeaders.ACCEPT, true);
if (acceptValues.length > 0) {
ClientInfo clientInfo = request.getClientInfo();
// Remove all existing media types, the parameter overrides them
clientInfo.getAcceptedMediaTypes().clear();
for (String value : acceptValues) {
PreferenceUtils.parseMediaTypes(value, clientInfo);
}
}
return Filter.CONTINUE;
}
|
diff --git a/htroot/IndexCreateIndexingQueue_p.java b/htroot/IndexCreateIndexingQueue_p.java
index 26ca76446..f3a4e9010 100644
--- a/htroot/IndexCreateIndexingQueue_p.java
+++ b/htroot/IndexCreateIndexingQueue_p.java
@@ -1,208 +1,208 @@
// IndexCreateIndexingQueue_p.java
// -------------------------------
// part of the AnomicHTTPD caching proxy
// (C) by Michael Peter Christen; [email protected]
// first published on http://www.anomic.de
// Frankfurt, Germany, 2004, 2005
// last major change: 04.07.2005
//
// 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
//
// Using this software in any meaning (reading, learning, copying, compiling,
// running) means that you agree that the Author(s) is (are) not responsible
// for cost, loss of data or any harm that may be caused directly or indirectly
// by usage of this softare or this documentation. The usage of this software
// is on your own risk. The installation and usage (starting/running) of this
// software may allow other people or application to access your computer and
// any attached devices and is highly dependent on the configuration of the
// software which must be done by the user of the software; the author(s) is
// (are) also not responsible for proper configuration and usage of the
// software, even if provoked by documentation provided together with
// the software.
//
// Any changes to this file according to the GPL as documented in the file
// gpl.txt aside this file in the shipment you received can be done to the
// lines that follows this copyright notice here, but changes must not be
// done inside the copyright notive above. A re-distribution must contain
// the intact and unchanged copyright notice.
// Contributions and changes to the program code must be marked as such.
// You must compile this file with
// javac -classpath .:../classes IndexCreate_p.java
// if the shell's current path is HTROOT
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import de.anomic.http.httpHeader;
import de.anomic.plasma.plasmaCrawlZURL;
import de.anomic.plasma.plasmaHTCache;
import de.anomic.plasma.plasmaSwitchboard;
import de.anomic.plasma.plasmaSwitchboardQueue;
import de.anomic.server.serverMemory;
import de.anomic.server.serverObjects;
import de.anomic.server.serverSwitch;
import de.anomic.yacy.yacyCore;
import de.anomic.yacy.yacySeed;
import de.anomic.yacy.yacyURL;
public class IndexCreateIndexingQueue_p {
public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch env) {
// return variable that accumulates replacements
plasmaSwitchboard switchboard = (plasmaSwitchboard) env;
serverObjects prop = new serverObjects();
prop.put("rejected", "0");
int showRejectedCount = 100;
int showLimit = 100;
if (post != null) {
if (post.containsKey("limit")) {
try {
showLimit = Integer.valueOf((String)post.get("limit")).intValue();
} catch (NumberFormatException e) {}
}
if (post.containsKey("clearRejected")) {
switchboard.crawlQueues.errorURL.clearStack();
}
if (post.containsKey("moreRejected")) {
- showRejectedCount = Integer.parseInt(post.get("showRejected", "10"));
+ showRejectedCount = post.getInt("showRejected", 10);
}
if (post.containsKey("clearIndexingQueue")) {
try {
synchronized (switchboard.sbQueue) {
plasmaSwitchboardQueue.Entry entry = null;
while ((entry = switchboard.sbQueue.pop()) != null) {
if ((entry != null) && (entry.profile() != null) && (!(entry.profile().storeHTCache()))) {
plasmaHTCache.deleteURLfromCache(entry.url());
}
}
switchboard.sbQueue.clear(); // reset file to clean up content completely
}
} catch (Exception e) {}
} else if (post.containsKey("deleteEntry")) {
String urlHash = (String) post.get("deleteEntry");
try {
switchboard.sbQueue.remove(urlHash);
} catch (Exception e) {}
prop.put("LOCATION","");
return prop;
}
}
yacySeed initiator;
boolean dark;
if ((switchboard.sbQueue.size() == 0) && (switchboard.indexingTasksInProcess.size() == 0)) {
prop.put("indexing-queue", "0"); //is empty
} else {
prop.put("indexing-queue", "1"); // there are entries in the queue or in process
dark = true;
plasmaSwitchboardQueue.Entry pcentry;
int inProcessCount = 0, entryCount = 0, totalCount = 0;
long totalSize = 0;
ArrayList entryList = new ArrayList();
// getting all entries that are currently in process
synchronized (switchboard.indexingTasksInProcess) {
inProcessCount = switchboard.indexingTasksInProcess.size();
entryList.addAll(switchboard.indexingTasksInProcess.values());
}
// getting all enqueued entries
if ((switchboard.sbQueue.size() > 0)) {
Iterator i = switchboard.sbQueue.entryIterator(false);
while (i.hasNext()) entryList.add((plasmaSwitchboardQueue.Entry) i.next());
}
int count=entryList.size();
totalCount = count;
for (int i = 0; (i < count) && (entryCount < showLimit); i++) {
boolean inProcess = i < inProcessCount;
pcentry = (plasmaSwitchboardQueue.Entry) entryList.get(i);
if ((pcentry != null)&&(pcentry.url() != null)) {
long entrySize = pcentry.size();
totalSize += entrySize;
initiator = yacyCore.seedDB.getConnected(pcentry.initiator());
prop.put("indexing-queue_list_"+entryCount+"_dark", inProcess ? "2" : (dark ? "1" : "0"));
prop.put("indexing-queue_list_"+entryCount+"_initiator", ((initiator == null) ? "proxy" : initiator.getName()));
prop.put("indexing-queue_list_"+entryCount+"_depth", pcentry.depth());
prop.put("indexing-queue_list_"+entryCount+"_modified", pcentry.getModificationDate());
prop.putHTML("indexing-queue_list_"+entryCount+"_anchor", (pcentry.anchorName()==null)?"":pcentry.anchorName());
prop.put("indexing-queue_list_"+entryCount+"_url", pcentry.url().toNormalform(false, true));
prop.put("indexing-queue_list_"+entryCount+"_size", serverMemory.bytesToString(entrySize));
prop.put("indexing-queue_list_"+entryCount+"_inProcess", inProcess ? "1" :"0");
prop.put("indexing-queue_list_"+entryCount+"_inProcess_hash", pcentry.urlHash());
dark = !dark;
entryCount++;
}
}
prop.putNum("indexing-queue_show", entryCount);//show shown entries
prop.putNum("indexing-queue_num", totalCount); //num entries in queue
prop.put("indexing-queue_totalSize", serverMemory.bytesToString(totalSize));//num entries in queue
prop.putNum("indexing-queue_list", entryCount);
}
// failure cases
if (switchboard.crawlQueues.errorURL.stackSize() != 0) {
if (showRejectedCount > switchboard.crawlQueues.errorURL.stackSize()) showRejectedCount = switchboard.crawlQueues.errorURL.stackSize();
prop.put("rejected", "1");
prop.putNum("rejected_num", switchboard.crawlQueues.errorURL.stackSize());
if (showRejectedCount != switchboard.crawlQueues.errorURL.stackSize()) {
prop.put("rejected_only-latest", "1");
prop.putNum("rejected_only-latest_num", showRejectedCount);
- prop.putNum("rejected_only-latest_newnum", ((int) (showRejectedCount * 1.5)));
+ prop.put("rejected_only-latest_newnum", ((int) (showRejectedCount * 1.5)));
}else{
prop.put("rejected_only-latest", "0");
}
dark = true;
yacyURL url;
String initiatorHash, executorHash;
plasmaCrawlZURL.Entry entry;
yacySeed initiatorSeed, executorSeed;
int j=0;
for (int i = switchboard.crawlQueues.errorURL.stackSize() - 1; i >= (switchboard.crawlQueues.errorURL.stackSize() - showRejectedCount); i--) {
try {
entry = switchboard.crawlQueues.errorURL.top(i);
url = entry.url();
if (url == null) continue;
initiatorHash = entry.initiator();
executorHash = entry.executor();
initiatorSeed = yacyCore.seedDB.getConnected(initiatorHash);
executorSeed = yacyCore.seedDB.getConnected(executorHash);
prop.put("rejected_list_"+j+"_initiator", ((initiatorSeed == null) ? "proxy" : initiatorSeed.getName()));
prop.put("rejected_list_"+j+"_executor", ((executorSeed == null) ? "proxy" : executorSeed.getName()));
prop.put("rejected_list_"+j+"_url", url.toNormalform(false, true));
prop.putHTML("rejected_list_"+j+"_failreason", entry.anycause());
prop.put("rejected_list_"+j+"_dark", dark ? "1" : "0");
dark = !dark;
j++;
} catch (IOException e) {
e.printStackTrace();
}
}
prop.put("rejected_list", j);
}
// return rewrite properties
return prop;
}
}
| false | true | public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch env) {
// return variable that accumulates replacements
plasmaSwitchboard switchboard = (plasmaSwitchboard) env;
serverObjects prop = new serverObjects();
prop.put("rejected", "0");
int showRejectedCount = 100;
int showLimit = 100;
if (post != null) {
if (post.containsKey("limit")) {
try {
showLimit = Integer.valueOf((String)post.get("limit")).intValue();
} catch (NumberFormatException e) {}
}
if (post.containsKey("clearRejected")) {
switchboard.crawlQueues.errorURL.clearStack();
}
if (post.containsKey("moreRejected")) {
showRejectedCount = Integer.parseInt(post.get("showRejected", "10"));
}
if (post.containsKey("clearIndexingQueue")) {
try {
synchronized (switchboard.sbQueue) {
plasmaSwitchboardQueue.Entry entry = null;
while ((entry = switchboard.sbQueue.pop()) != null) {
if ((entry != null) && (entry.profile() != null) && (!(entry.profile().storeHTCache()))) {
plasmaHTCache.deleteURLfromCache(entry.url());
}
}
switchboard.sbQueue.clear(); // reset file to clean up content completely
}
} catch (Exception e) {}
} else if (post.containsKey("deleteEntry")) {
String urlHash = (String) post.get("deleteEntry");
try {
switchboard.sbQueue.remove(urlHash);
} catch (Exception e) {}
prop.put("LOCATION","");
return prop;
}
}
yacySeed initiator;
boolean dark;
if ((switchboard.sbQueue.size() == 0) && (switchboard.indexingTasksInProcess.size() == 0)) {
prop.put("indexing-queue", "0"); //is empty
} else {
prop.put("indexing-queue", "1"); // there are entries in the queue or in process
dark = true;
plasmaSwitchboardQueue.Entry pcentry;
int inProcessCount = 0, entryCount = 0, totalCount = 0;
long totalSize = 0;
ArrayList entryList = new ArrayList();
// getting all entries that are currently in process
synchronized (switchboard.indexingTasksInProcess) {
inProcessCount = switchboard.indexingTasksInProcess.size();
entryList.addAll(switchboard.indexingTasksInProcess.values());
}
// getting all enqueued entries
if ((switchboard.sbQueue.size() > 0)) {
Iterator i = switchboard.sbQueue.entryIterator(false);
while (i.hasNext()) entryList.add((plasmaSwitchboardQueue.Entry) i.next());
}
int count=entryList.size();
totalCount = count;
for (int i = 0; (i < count) && (entryCount < showLimit); i++) {
boolean inProcess = i < inProcessCount;
pcentry = (plasmaSwitchboardQueue.Entry) entryList.get(i);
if ((pcentry != null)&&(pcentry.url() != null)) {
long entrySize = pcentry.size();
totalSize += entrySize;
initiator = yacyCore.seedDB.getConnected(pcentry.initiator());
prop.put("indexing-queue_list_"+entryCount+"_dark", inProcess ? "2" : (dark ? "1" : "0"));
prop.put("indexing-queue_list_"+entryCount+"_initiator", ((initiator == null) ? "proxy" : initiator.getName()));
prop.put("indexing-queue_list_"+entryCount+"_depth", pcentry.depth());
prop.put("indexing-queue_list_"+entryCount+"_modified", pcentry.getModificationDate());
prop.putHTML("indexing-queue_list_"+entryCount+"_anchor", (pcentry.anchorName()==null)?"":pcentry.anchorName());
prop.put("indexing-queue_list_"+entryCount+"_url", pcentry.url().toNormalform(false, true));
prop.put("indexing-queue_list_"+entryCount+"_size", serverMemory.bytesToString(entrySize));
prop.put("indexing-queue_list_"+entryCount+"_inProcess", inProcess ? "1" :"0");
prop.put("indexing-queue_list_"+entryCount+"_inProcess_hash", pcentry.urlHash());
dark = !dark;
entryCount++;
}
}
prop.putNum("indexing-queue_show", entryCount);//show shown entries
prop.putNum("indexing-queue_num", totalCount); //num entries in queue
prop.put("indexing-queue_totalSize", serverMemory.bytesToString(totalSize));//num entries in queue
prop.putNum("indexing-queue_list", entryCount);
}
// failure cases
if (switchboard.crawlQueues.errorURL.stackSize() != 0) {
if (showRejectedCount > switchboard.crawlQueues.errorURL.stackSize()) showRejectedCount = switchboard.crawlQueues.errorURL.stackSize();
prop.put("rejected", "1");
prop.putNum("rejected_num", switchboard.crawlQueues.errorURL.stackSize());
if (showRejectedCount != switchboard.crawlQueues.errorURL.stackSize()) {
prop.put("rejected_only-latest", "1");
prop.putNum("rejected_only-latest_num", showRejectedCount);
prop.putNum("rejected_only-latest_newnum", ((int) (showRejectedCount * 1.5)));
}else{
prop.put("rejected_only-latest", "0");
}
dark = true;
yacyURL url;
String initiatorHash, executorHash;
plasmaCrawlZURL.Entry entry;
yacySeed initiatorSeed, executorSeed;
int j=0;
for (int i = switchboard.crawlQueues.errorURL.stackSize() - 1; i >= (switchboard.crawlQueues.errorURL.stackSize() - showRejectedCount); i--) {
try {
entry = switchboard.crawlQueues.errorURL.top(i);
url = entry.url();
if (url == null) continue;
initiatorHash = entry.initiator();
executorHash = entry.executor();
initiatorSeed = yacyCore.seedDB.getConnected(initiatorHash);
executorSeed = yacyCore.seedDB.getConnected(executorHash);
prop.put("rejected_list_"+j+"_initiator", ((initiatorSeed == null) ? "proxy" : initiatorSeed.getName()));
prop.put("rejected_list_"+j+"_executor", ((executorSeed == null) ? "proxy" : executorSeed.getName()));
prop.put("rejected_list_"+j+"_url", url.toNormalform(false, true));
prop.putHTML("rejected_list_"+j+"_failreason", entry.anycause());
prop.put("rejected_list_"+j+"_dark", dark ? "1" : "0");
dark = !dark;
j++;
} catch (IOException e) {
e.printStackTrace();
}
}
prop.put("rejected_list", j);
}
// return rewrite properties
return prop;
}
| public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch env) {
// return variable that accumulates replacements
plasmaSwitchboard switchboard = (plasmaSwitchboard) env;
serverObjects prop = new serverObjects();
prop.put("rejected", "0");
int showRejectedCount = 100;
int showLimit = 100;
if (post != null) {
if (post.containsKey("limit")) {
try {
showLimit = Integer.valueOf((String)post.get("limit")).intValue();
} catch (NumberFormatException e) {}
}
if (post.containsKey("clearRejected")) {
switchboard.crawlQueues.errorURL.clearStack();
}
if (post.containsKey("moreRejected")) {
showRejectedCount = post.getInt("showRejected", 10);
}
if (post.containsKey("clearIndexingQueue")) {
try {
synchronized (switchboard.sbQueue) {
plasmaSwitchboardQueue.Entry entry = null;
while ((entry = switchboard.sbQueue.pop()) != null) {
if ((entry != null) && (entry.profile() != null) && (!(entry.profile().storeHTCache()))) {
plasmaHTCache.deleteURLfromCache(entry.url());
}
}
switchboard.sbQueue.clear(); // reset file to clean up content completely
}
} catch (Exception e) {}
} else if (post.containsKey("deleteEntry")) {
String urlHash = (String) post.get("deleteEntry");
try {
switchboard.sbQueue.remove(urlHash);
} catch (Exception e) {}
prop.put("LOCATION","");
return prop;
}
}
yacySeed initiator;
boolean dark;
if ((switchboard.sbQueue.size() == 0) && (switchboard.indexingTasksInProcess.size() == 0)) {
prop.put("indexing-queue", "0"); //is empty
} else {
prop.put("indexing-queue", "1"); // there are entries in the queue or in process
dark = true;
plasmaSwitchboardQueue.Entry pcentry;
int inProcessCount = 0, entryCount = 0, totalCount = 0;
long totalSize = 0;
ArrayList entryList = new ArrayList();
// getting all entries that are currently in process
synchronized (switchboard.indexingTasksInProcess) {
inProcessCount = switchboard.indexingTasksInProcess.size();
entryList.addAll(switchboard.indexingTasksInProcess.values());
}
// getting all enqueued entries
if ((switchboard.sbQueue.size() > 0)) {
Iterator i = switchboard.sbQueue.entryIterator(false);
while (i.hasNext()) entryList.add((plasmaSwitchboardQueue.Entry) i.next());
}
int count=entryList.size();
totalCount = count;
for (int i = 0; (i < count) && (entryCount < showLimit); i++) {
boolean inProcess = i < inProcessCount;
pcentry = (plasmaSwitchboardQueue.Entry) entryList.get(i);
if ((pcentry != null)&&(pcentry.url() != null)) {
long entrySize = pcentry.size();
totalSize += entrySize;
initiator = yacyCore.seedDB.getConnected(pcentry.initiator());
prop.put("indexing-queue_list_"+entryCount+"_dark", inProcess ? "2" : (dark ? "1" : "0"));
prop.put("indexing-queue_list_"+entryCount+"_initiator", ((initiator == null) ? "proxy" : initiator.getName()));
prop.put("indexing-queue_list_"+entryCount+"_depth", pcentry.depth());
prop.put("indexing-queue_list_"+entryCount+"_modified", pcentry.getModificationDate());
prop.putHTML("indexing-queue_list_"+entryCount+"_anchor", (pcentry.anchorName()==null)?"":pcentry.anchorName());
prop.put("indexing-queue_list_"+entryCount+"_url", pcentry.url().toNormalform(false, true));
prop.put("indexing-queue_list_"+entryCount+"_size", serverMemory.bytesToString(entrySize));
prop.put("indexing-queue_list_"+entryCount+"_inProcess", inProcess ? "1" :"0");
prop.put("indexing-queue_list_"+entryCount+"_inProcess_hash", pcentry.urlHash());
dark = !dark;
entryCount++;
}
}
prop.putNum("indexing-queue_show", entryCount);//show shown entries
prop.putNum("indexing-queue_num", totalCount); //num entries in queue
prop.put("indexing-queue_totalSize", serverMemory.bytesToString(totalSize));//num entries in queue
prop.putNum("indexing-queue_list", entryCount);
}
// failure cases
if (switchboard.crawlQueues.errorURL.stackSize() != 0) {
if (showRejectedCount > switchboard.crawlQueues.errorURL.stackSize()) showRejectedCount = switchboard.crawlQueues.errorURL.stackSize();
prop.put("rejected", "1");
prop.putNum("rejected_num", switchboard.crawlQueues.errorURL.stackSize());
if (showRejectedCount != switchboard.crawlQueues.errorURL.stackSize()) {
prop.put("rejected_only-latest", "1");
prop.putNum("rejected_only-latest_num", showRejectedCount);
prop.put("rejected_only-latest_newnum", ((int) (showRejectedCount * 1.5)));
}else{
prop.put("rejected_only-latest", "0");
}
dark = true;
yacyURL url;
String initiatorHash, executorHash;
plasmaCrawlZURL.Entry entry;
yacySeed initiatorSeed, executorSeed;
int j=0;
for (int i = switchboard.crawlQueues.errorURL.stackSize() - 1; i >= (switchboard.crawlQueues.errorURL.stackSize() - showRejectedCount); i--) {
try {
entry = switchboard.crawlQueues.errorURL.top(i);
url = entry.url();
if (url == null) continue;
initiatorHash = entry.initiator();
executorHash = entry.executor();
initiatorSeed = yacyCore.seedDB.getConnected(initiatorHash);
executorSeed = yacyCore.seedDB.getConnected(executorHash);
prop.put("rejected_list_"+j+"_initiator", ((initiatorSeed == null) ? "proxy" : initiatorSeed.getName()));
prop.put("rejected_list_"+j+"_executor", ((executorSeed == null) ? "proxy" : executorSeed.getName()));
prop.put("rejected_list_"+j+"_url", url.toNormalform(false, true));
prop.putHTML("rejected_list_"+j+"_failreason", entry.anycause());
prop.put("rejected_list_"+j+"_dark", dark ? "1" : "0");
dark = !dark;
j++;
} catch (IOException e) {
e.printStackTrace();
}
}
prop.put("rejected_list", j);
}
// return rewrite properties
return prop;
}
|
diff --git a/javasrc/src/org/ccnx/ccn/profiles/nameenum/EnumeratedNameList.java b/javasrc/src/org/ccnx/ccn/profiles/nameenum/EnumeratedNameList.java
index e9ae02bf6..3aefe2dc5 100644
--- a/javasrc/src/org/ccnx/ccn/profiles/nameenum/EnumeratedNameList.java
+++ b/javasrc/src/org/ccnx/ccn/profiles/nameenum/EnumeratedNameList.java
@@ -1,730 +1,730 @@
/*
* Part of the CCNx Java Library.
*
* Copyright (C) 2008, 2009, 2010, 2012 Palo Alto Research Center, Inc.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 2.1
* as published by the Free Software Foundation.
* 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., 51 Franklin Street,
* Fifth Floor, Boston, MA 02110-1301 USA.
*/
package org.ccnx.ccn.profiles.nameenum;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.logging.Level;
import org.bouncycastle.util.Arrays;
import org.ccnx.ccn.CCNHandle;
import org.ccnx.ccn.config.ConfigurationException;
import org.ccnx.ccn.config.SystemConfiguration;
import org.ccnx.ccn.impl.support.Log;
import org.ccnx.ccn.profiles.VersioningProfile;
import org.ccnx.ccn.protocol.CCNTime;
import org.ccnx.ccn.protocol.Component;
import org.ccnx.ccn.protocol.ContentName;
import org.ccnx.ccn.protocol.ContentNameProvider;
/**
* Blocking and background interface to name enumeration. This allows a caller to specify a prefix
* under which to enumerate available children, and name enumeration to proceed in the background
* for as long as desired, providing updates whenever new data is published.
* Currently implemented as a wrapper around CCNNameEnumerator, will likely directly aggregate
* name enumeration responses in the future.
*
* @see CCNNameEnumerator
* @see BasicNameEnumeratorListener
*/
public class EnumeratedNameList implements BasicNameEnumeratorListener, ContentNameProvider {
protected ContentName _namePrefix;
protected CCNNameEnumerator _enumerator;
protected BasicNameEnumeratorListener callback;
// make these contain something other than content names when the enumerator has better data types
protected SortedSet<ContentName> _children = new TreeSet<ContentName>();
//protected SortedSet<ContentName> _newChildren = null;
protected Map<Long, NewChildrenByThread> _newChildrenByThread = new TreeMap<Long, NewChildrenByThread>();
protected Object _childLock = new Object();
protected CCNTime _lastUpdate = null;
protected boolean _enumerating = false;
protected boolean _shutdown = false;
private class NewChildrenByThread implements Comparable<NewChildrenByThread> {
private final Long _id; // If 0 this is in thread pool mode
private SortedSet<ContentName> _newChildren = null;
private NewChildrenByThread(Long id) {
this._id = id;
}
public int compareTo(NewChildrenByThread o) {
return _id.compareTo(o._id);
}
}
/**
* Keep track of whether we've ever done enumeration, so we can start it automatically
* if someone asks us for something not in our cache. This lets us relax the requirement
* that callers pre-enumerate just in case. Can't use hasChildren; there might not
* be any children but we might have tried enumeration already.
*/
protected boolean _hasEnumerated = false;
/**
* Creates an EnumeratedNameList object
*
* This constructor creates a new EnumeratedNameList object that will begin enumerating
* the children of the specified prefix. The new EnumeratedNameList will use the CCNHandle passed
* in to the constructor, or create a new one using CCNHandle#open() if it is null.
*
* @param namePrefix the ContentName whose children we wish to list.
* @param handle the CCNHandle object for sending interests and receiving content object responses.
*/
public EnumeratedNameList(ContentName namePrefix, CCNHandle handle) throws IOException {
this(namePrefix, true, handle);
}
public EnumeratedNameList(ContentName namePrefix, boolean startEnumerating, CCNHandle handle) throws IOException {
if (null == namePrefix) {
throw new IllegalArgumentException("namePrefix cannot be null!");
}
if (null == handle) {
try {
handle = CCNHandle.open();
} catch (ConfigurationException e) {
throw new IOException("ConfigurationException attempting to open a handle: " + e.getMessage());
}
}
_namePrefix = namePrefix;
if (startEnumerating) {
_enumerating = true;
_hasEnumerated = true;
_enumerator = new CCNNameEnumerator(namePrefix, handle, this);
} else {
_enumerator = new CCNNameEnumerator(handle, this);
}
}
/**
* Method to return the ContentName used for enumeration.
*
* @return ContentName returns the prefix under which we are enumerating children.
*/
public ContentName getName() { return _namePrefix; }
/**
* Cancels ongoing name enumeration. Previously-accumulated information about
* children of this name are still stored and available for use.
*
* @return void
* */
public synchronized void stopEnumerating() {
if (!_enumerating) {
if (Log.isLoggable(Log.FAC_SEARCH, Level.INFO)) {
Log.info(Log.FAC_SEARCH, "Enumerated name list: Not enumerating, so not canceling prefix.");
}
return;
}
_enumerator.cancelPrefix(_namePrefix);
_enumerating = false;
}
/**
* Starts enumeration, if we're not enumerating already.
* @throws IOException
*/
public synchronized void startEnumerating() throws IOException {
_enumerating = true;
_enumerator.registerPrefix(_namePrefix);
_hasEnumerated = true;
}
public boolean isEnumerating() { return _enumerating; }
public boolean hasEnumerated() { return _hasEnumerated; }
/**
* Shutdown anybody waiting for children on this list
*/
public void shutdown() {
_shutdown = true;
synchronized (_childLock) {
_childLock.notifyAll();
}
}
/**
* Interface to retrieve only new data from enumeration responses as it arrives.
* This method blocks and waits for data, but grabs the new data for processing.
* In threadPoolContext it will in effect remove the data from every other
* listener who is listening in threadPoolContext, in effect handing the new
* children to the first consumer to wake up and make the other ones go around again.
* There is currently no support for more than one simultaneous thread pool.
*
* @param threadPoolContext Are we getting data in threadPoolContext? (described above).
* @param timeout maximum amount of time to wait, 0 to wait forever.
* @return SortedSet<ContentName> Returns the array of single-component
* content name children that are new to us, or null if we reached the
* timeout before new data arrived
*/
public SortedSet<ContentName> getNewData(boolean threadPoolContext, long timeout) {
SortedSet<ContentName> childArray = null;
synchronized(_childLock) { // reentrant
Long id = threadPoolContext ? 0 : Thread.currentThread().getId();
NewChildrenByThread ncbt = _newChildrenByThread.get(id);
SortedSet<ContentName> newChildren = ncbt == null ? null : ncbt._newChildren;
while ((null == newChildren) || newChildren.size() == 0) {
waitForNewChildren(threadPoolContext, timeout);
ncbt = _newChildrenByThread.get(id);
newChildren = ncbt._newChildren;
if (timeout != SystemConfiguration.NO_TIMEOUT)
break;
}
if (Log.isLoggable(Log.FAC_SEARCH, Level.INFO)) {
Log.info(Log.FAC_SEARCH, "Waiting for new data on prefix: {0} got {1}.",
_namePrefix, ((null == newChildren) ? 0 : newChildren.size()));
}
if (null != newChildren) {
childArray = newChildren;
ncbt._newChildren = null;
}
}
return childArray;
}
/**
* Block and wait as long as it takes for new data to appear. See #getNewData(boolean, long).
* @return SortedSet<ContentName> Returns the array of single-component
* content name children that are new to us. Waits forever if no new data appears
*/
public SortedSet<ContentName> getNewData() {
return getNewData(false, SystemConfiguration.NO_TIMEOUT);
}
/**
* Block and wait for timeout or until new data appears. See #getNewData(boolean, long).
* @param timeout in ms
* @return SortedSet<ContentName> Returns the array of single-component
* content name children that are new to us, or null if we reached the
* timeout before new data arrived
*/
public SortedSet<ContentName> getNewData(long timeout) {
return getNewData(false, timeout);
}
/**
* Block and wait for timeout or until new data appears. See #getNewData(boolean, long).
* Different from getNewData in that new data is shared among all threads accessing this
* instance of EnumeratedNameList. So if another thread gets the data first, we won't get it.
* @param timeout in ms
* @return SortedSet<ContentName> Returns the array of single-component
* content name children that are new to the list instance if we got it first, or null if we
* reached the timeout before new data arrived
*/
public SortedSet<ContentName> getNewDataThreadPool(long timeout) {
return getNewData(true, timeout);
}
/**
* Returns single-component ContentName objects containing the name components of the children.
* @return SortedSet<ContentName> Returns the array of single-component
* content name children that have been retrieved so far, or null if no responses
* have yet been received. The latter may indicate either that no children of this prefix
* are known to any responders, or that they have not had time to respond.
*/
public SortedSet<ContentName> getChildren() {
if (!hasChildren())
return null;
return _children;
}
/**
* Returns true if the prefix has new names that have not been handled by the calling application.
* @return true if there are new children available to process
*/
public boolean hasNewData() {
NewChildrenByThread ncbt = getNcbt();
if (null == ncbt)
return false; // Never set up
return ((null != ncbt._newChildren) && (ncbt._newChildren.size() > 0));
}
/**
* Returns true if we have received any responses listing available child names.
* If no names have yet been received, this may mean either that responses
* have not had time to arrive, or there are know children known to available
* responders.
*
* @return true if we have child names received from enumeration responses
*/
public boolean hasChildren() {
return ((null != _children) && (_children.size() > 0));
}
/**
* Returns the number of children we have, or 0 if we have none.
*/
public int childCount() {
if (null == _children)
return 0;
return _children.size();
}
/**
* Returns true if we know the prefix has a child matching the given name component.
*
* @param childComponent name component to check for in the stored child names.
* @return true if that child is in our list of known children
*/
public boolean hasChild(byte [] childComponent) {
for (ContentName child : _children) {
if (Arrays.areEqual(childComponent, child.component(0))) {
return true;
}
}
return false;
}
/**
* Returns whether a child is present in the list of known children.
* <p>
*
* @param childName String version of a child name to look for
* @return boolean Returns true if the name is present in the list of known children.
* */
public boolean hasChild(String childName) {
return hasChild(Component.parseNative(childName));
}
/**
* Wait for new children to arrive.
*
* @param timeout Maximum time to wait for new data.
* @param threadPoolContext Are we waiting in threadPoolContext (i.e. other threads can grab children first)
* See #getNewData(boolean, long).
* @return a boolean value that indicates whether new data was found.
*/
public boolean waitForNewChildren(boolean threadPoolContext, long timeout) {
boolean foundNewData = false;
Long id = threadPoolContext ? 0 : Thread.currentThread().getId();
_newChildrenByThread.put(id, new NewChildrenByThread(id));
synchronized(_childLock) {
CCNTime lastUpdate = _lastUpdate;
long timeRemaining = timeout;
long startTime = System.currentTimeMillis();
while (((null == _lastUpdate) || ((null != lastUpdate) && !_lastUpdate.after(lastUpdate))) &&
((timeout == SystemConfiguration.NO_TIMEOUT) || (timeRemaining > 0))) {
if (_shutdown)
break;
try {
_childLock.wait((timeout != SystemConfiguration.NO_TIMEOUT) ? Math.min(timeRemaining, SystemConfiguration.CHILD_WAIT_INTERVAL) : SystemConfiguration.CHILD_WAIT_INTERVAL);
if (timeout != SystemConfiguration.NO_TIMEOUT) {
timeRemaining = timeout - (System.currentTimeMillis() - startTime);
}
} catch (InterruptedException e) {
}
if (Log.isLoggable(Log.FAC_SEARCH, Level.INFO)) {
SortedSet<ContentName> newChildren = _newChildrenByThread.get(id)._newChildren;
Log.info(Log.FAC_SEARCH, "Waiting for new data on prefix: {0}, updated {1}, our update {2}, have {3} children {4} new.",
_namePrefix, _lastUpdate, lastUpdate,
((null == _children) ? 0 : _children.size()),
((null == newChildren) ? 0 : newChildren.size()));
}
}
if ((null != _lastUpdate) && ((null == lastUpdate) || (_lastUpdate.after(lastUpdate)))) foundNewData = true;
}
return foundNewData;
}
/**
* Wait for new children to arrive.
* This method does not have a timeout and will wait forever.
*
* @return void
*/
public void waitForNewChildren() {
waitForNewChildren(false, SystemConfiguration.NO_TIMEOUT);
}
/**
* Wait for new children to arrive.
*
* @param timeout Maximum amount of time to wait, if 0, waits forever.
* @return a boolean value that indicates whether new data was found.
*/
public boolean waitForNewChildren(long timeout) {
return waitForNewChildren(false, timeout);
}
/**
* Wait for new children to arrive in thread pool context. See notes about this above.
* @param timeout Maximum amount of time to wait, if 0, waits forever.
* @return a boolean value that indicates whether new data was found.
*/
public boolean waitForNewChildrenThreadPool(long timeout) {
return waitForNewChildren(true, timeout);
}
/**
* Waits until there is any data at all. Right now, waits for the first response containing actual
* children, not just a name enumeration response. That means it could block
* forever if no children exist in a repository or there are not any applications responding to
* name enumeration requests. Once we have an initial set of children, this method
* returns immediately.
*
* @param timeout Maximum amount of time to wait, if 0, waits forever.
* @return void
*/
public void waitForChildren(long timeout) {
while ((null == _children) || _children.size() == 0) {
waitForNewChildren(false, timeout);
if (timeout != SystemConfiguration.NO_TIMEOUT)
break;
}
}
/**
* Wait (block) for initial data to arrive, possibly forever. See #waitForData(long).
*
* @return void
*
*/
public void waitForChildren() {
waitForChildren(SystemConfiguration.NO_TIMEOUT);
}
/**
* Wait for new children to arrive until there is a period of length timeout during which
* no new child arrives.
* @param timeout The maximum amount of time to wait between consecutive children arrivals.
*/
public void waitForNoUpdates(long timeout) {
if (Log.isLoggable(Log.FAC_SEARCH, Level.INFO))
Log.info(Log.FAC_SEARCH, "Waiting for updates on prefix {0} with max timeout of {1} ms between consecutive children arrivals.",
_namePrefix, timeout);
long startTime = System.currentTimeMillis();
while (waitForNewChildren(false, timeout)) {
if (Log.isLoggable(Log.FAC_SEARCH, Level.INFO))
Log.info(Log.FAC_SEARCH, "Child or children found on prefix {0}", _namePrefix);
}
if (Log.isLoggable(Log.FAC_SEARCH, Level.INFO))
Log.info(Log.FAC_SEARCH, "Quit waiting for updates on prefix {0} after waiting in total {1} ms.",
_namePrefix, (System.currentTimeMillis() - startTime));
}
/**
* Wait for new children to arrive until there is a period of length timeout during which
* no new child arrives, or the method hasResult() returns true. The expectation
* is that a subclass will monitor incoming updates in its processNewChildren() override
* method, and in that method, set some sort of flag that will be tested by hasResult().
* Note that this method does not currently stop enumeration -- enumeration results will
* continue to accumulate in the background (and request interests will continue to be sent);
* callers must call stopEnumerating() to actually terminate enumeration.
*/
public void waitForNoUpdatesOrResult(long timeout) {
if (Log.isLoggable(Log.FAC_SEARCH, Level.INFO))
Log.info(Log.FAC_SEARCH, "Waiting for updates on prefix {0} with max timeout of {1} ms between consecutive children arrivals.",
_namePrefix, timeout);
long startTime = System.currentTimeMillis();
if (hasResult()) {
return;
}
while (waitForNewChildren(false, timeout)) {
if (Log.isLoggable(Log.FAC_SEARCH, Level.INFO))
Log.info(Log.FAC_SEARCH, "Child or children found on prefix {0}. Have result? {1}", _namePrefix, hasResult());
if (hasResult()) break;
}
if (Log.isLoggable(Log.FAC_SEARCH, Level.INFO))
Log.info(Log.FAC_SEARCH, "Quit waiting for updates on prefix {0} after waiting in total {1} ms. Have desired result? {2}",
_namePrefix, (System.currentTimeMillis() - startTime), hasResult());
}
/**
* Subclasses should override this test to answer true if waiters should break out of a
* waitForNoUpdatesOrResult loop. Note that results must be cleared manually using clearResult.
* Default behavior always returns false. Subclasses probably want to set a variable in processNewChildren
* that will be read here.
*/
public boolean hasResult() {
return false;
}
/**
* Reset whatever state hasResult tests. Overridden by subclasses, default does nothing.
*/
public void clearResult() {
return;
}
/**
* Method to allow subclasses to do post-processing on incoming names
* before handing them to customers.
* Note that the set handed in here is not the set that will be handed
* out; only the name objects are the same.
*
* @param newChildren SortedSet of children available for processing
*
* @return void
*/
protected void processNewChildren(SortedSet<ContentName> newChildren) {
// default -- do nothing
}
/**
* If some or all of the children of this name are versions, returns the latest version
* among them.
*
* @return ContentName The latest version component
* */
public ContentName getLatestVersionChildName() {
// of the available names in _children that are version components,
// find the latest one (version-wise)
// names are sorted, so the last one that is a version should be the latest version
// ListIterator previous doesn't work unless you've somehow gotten it to point at the end...
ContentName theName = null;
ContentName latestName = null;
CCNTime latestTimestamp = null;
Iterator<ContentName> it = _children.iterator();
// TODO these are sorted -- we just need to iterate through them in reverse order. Having
// trouble finding something like C++'s reverse iterators to do that (linked list iterators
// can go backwards -- but you have to run them to the end first).
while (it.hasNext()) {
theName = it.next();
if (VersioningProfile.isVersionComponent(theName.component(0))) {
if (null == latestName) {
latestName = theName;
latestTimestamp = VersioningProfile.getVersionComponentAsTimestamp(theName.component(0));
} else {
CCNTime thisTimestamp = VersioningProfile.getVersionComponentAsTimestamp(theName.component(0));
if (thisTimestamp.after(latestTimestamp)) {
latestName = theName;
latestTimestamp = thisTimestamp;
}
}
}
}
return latestName;
}
/**
* Handle responses from CCNNameEnumerator that give us a list of single-component child
* names. Filter out the names new to us, add them to our list of known children, postprocess
* them with processNewChildren(SortedSet<ContentName>), and signal waiters if we
* have new data.
*
* @param prefix Prefix used for name enumeration.
* @param names The list of names returned in this name enumeration response.
*
* @return int
*/
@SuppressWarnings("unchecked")
public int handleNameEnumerator(ContentName prefix,
ArrayList<ContentName> names) {
if (Log.isLoggable(Log.FAC_SEARCH, Level.INFO)) {
if (!_enumerating) {
// Right now, just log if we get data out of enumeration, don't drop it on the floor;
// don't want to miss results in case we are started again.
Log.info(Log.FAC_SEARCH, "ENUMERATION STOPPED: but {0} new name enumeration results: our prefix: {1} returned prefix: {2}", names.size(), _namePrefix, prefix);
} else {
Log.info(Log.FAC_SEARCH, "{0} new name enumeration results: our prefix: {1} returned prefix: {2}", names.size(), _namePrefix, prefix);
}
}
if (!prefix.equals(_namePrefix)) {
Log.warning(Log.FAC_SEARCH, "Returned data doesn't match requested prefix!");
}
if (Log.isLoggable(Log.FAC_SEARCH, Level.INFO))
Log.info(Log.FAC_SEARCH, "Handling Name Iteration {0}, size is {1}", prefix, names.size());
// the name enumerator hands off names to us, we own it now
// DKS -- want to keep listed as new children we previously had
synchronized (_childLock) {
TreeSet<ContentName> thisRoundNew = new TreeSet<ContentName>();
thisRoundNew.addAll(names);
Iterator<ContentName> it = thisRoundNew.iterator();
while (it.hasNext()) {
ContentName name = it.next();
if (_children.contains(name)) {
it.remove();
}
}
if (!thisRoundNew.isEmpty()) {
for (NewChildrenByThread ncbt : _newChildrenByThread.values()) {
if (null != ncbt._newChildren) {
ncbt._newChildren.addAll(thisRoundNew);
} else {
ncbt._newChildren = (TreeSet<ContentName>)thisRoundNew.clone();
}
}
_children.addAll(thisRoundNew);
_lastUpdate = new CCNTime();
if (Log.isLoggable(Log.FAC_SEARCH, Level.INFO)) {
Log.info(Log.FAC_SEARCH, "New children found: at {0} {1} total children {2}", _lastUpdate, + thisRoundNew.size(), _children.size());
}
processNewChildren(thisRoundNew);
_childLock.notifyAll();
}
}
return 0;
}
/**
* Returns the latest version available under this prefix as a byte array.
*
* @return byte[] Latest child version as byte array
*/
public byte [] getLatestVersionChildNameComponent() {
ContentName latestVersionName = getLatestVersionChildName();
if (null == latestVersionName)
return null;
return latestVersionName.component(0);
}
/**
* Returns the latest version available under this prefix as a CCNTime object.
*
* @return CCNTime Latest child version as CCNTime
*/
public CCNTime getLatestVersionChildTime() {
ContentName latestVersion = getLatestVersionChildName();
if (null != latestVersion) {
return VersioningProfile.getVersionComponentAsTimestamp(latestVersion.component(0));
}
return null;
}
/**
* A static method that performs a one-shot call that returns the complete name of the latest
* version of content with the given prefix. An alternative route to finding the name of the
* latest version of a piece of content, rather than using methods in the VersioningProfile
* to retrieve an arbitrary block of content under that version. Useful when the data under
* a version is complex in structure.
*
* @param name ContentName to find the latest version of
* @param handle CCNHandle to use for enumeration
* @return ContentName The name supplied to the call with the latest version added.
* @throws IOException
*/
public static ContentName getLatestVersionName(ContentName name, CCNHandle handle) throws IOException {
EnumeratedNameList enl = new EnumeratedNameList(name, handle);
enl.waitForNoUpdates(SystemConfiguration.MAX_TIMEOUT);
ContentName childLatestVersion = enl.getLatestVersionChildName();
enl.stopEnumerating();
if (null != childLatestVersion) {
return new ContentName(name, childLatestVersion.component(0));
}
return null;
}
/**
* Static method that iterates down the namespace starting with the supplied prefix
* as a ContentName (prefixKnownToExist) to a specific child (childName). The method
* returns null if the name does not exist in a limited time iteration. If the child
* is found, this method returns the EnumeratedNameList object for the parent of the
* desired child in the namespace. The current implementation may time out before the
* desired name is found. Additionally, the current implementation does not loop on
* an enumeration attempt, so a child may be missed if it is not included in the first
* enumeration response.
*
* TODO Add loop to enumerate under a name multiple times to avoid missing a child name
* TODO Handle timeouts better to avoid missing children. (Note: We could modify the
* name enumeration protocol to return empty responses if we query for an unknown name,
* but that adds semantic complications.)
*
* @param childName ContentName for the child we are looking for under (does not have
* to be directly under) a given prefix.
* @param prefixKnownToExist ContentName prefix to enumerate to look for a given child.
* @param handle CCNHandle for sending and receiving interests and content objects.
*
* @return EnumeratedNameList Returns the parent EnumeratedNameList for the desired child,
* if one is found. Returns null if the child is not found.
*
* @throws IOException
*/
public static EnumeratedNameList exists(ContentName childName, ContentName prefixKnownToExist, CCNHandle handle) throws IOException {
if (Log.isLoggable(Log.FAC_SEARCH, Level.INFO))
Log.info(Log.FAC_SEARCH, "EnumeratedNameList.exists: the prefix known to exist is {0} and we are looking for childName {1}", prefixKnownToExist, childName);
if ((null == prefixKnownToExist) || (null == childName) || (!prefixKnownToExist.isPrefixOf(childName))) {
if (Log.isLoggable(Log.FAC_SEARCH, Level.INFO))
Log.info(Log.FAC_SEARCH, "EnumeratedNameList.exists: Child {0} must be prefixed by name {1}", childName, prefixKnownToExist);
throw new IllegalArgumentException("Child " + childName + " must be prefixed by name " + prefixKnownToExist);
}
if (childName.count() == prefixKnownToExist.count()) {
// we're already there
if (Log.isLoggable(Log.FAC_SEARCH, Level.INFO))
Log.info(Log.FAC_SEARCH, "EnumeratedNameList.exists: we're already there.");
return new EnumeratedNameList(childName, handle);
}
ContentName parentName = prefixKnownToExist;
int childIndex = parentName.count();
EnumeratedNameList parentEnumerator = null;
while (childIndex < childName.count()) {
byte[] childNameComponent = childName.component(childIndex);
parentEnumerator = new EnumeratedNameList(parentName, handle);
if (Log.isLoggable(Log.FAC_SEARCH, Level.INFO))
Log.info(Log.FAC_SEARCH, "EnumeratedNameList.exists: enumerating the parent name {0}", parentName);
parentEnumerator.waitForChildren(SystemConfiguration.MAX_TIMEOUT);
while (! parentEnumerator.hasChild(childNameComponent)) {
if (! parentEnumerator.waitForNewChildren(false, SystemConfiguration.MAX_TIMEOUT)) break;
}
if (parentEnumerator.hasChild(childNameComponent)) {
- if (Log.isLoggable(Level.INFO)) {
- Log.info("EnumeratedNameList.exists: we have a matching child to {0} and the parent enumerator {1} has {2} children.",
+ if (Log.isLoggable(Log.FAC_SEARCH, Level.INFO)) {
+ Log.info(Log.FAC_SEARCH, "EnumeratedNameList.exists: we have a matching child to {0} and the parent enumerator {1} has {2} children.",
Component.printURI(childNameComponent), parentName, parentEnumerator.childCount());
}
childIndex++;
if (childIndex == childName.count()) {
if (Log.isLoggable(Log.FAC_SEARCH, Level.INFO))
Log.info(Log.FAC_SEARCH, "EnumeratedNameList.exists: we found the childName we were looking for: {0}", childName);
return parentEnumerator;
}
parentEnumerator.stopEnumerating();
parentName = new ContentName(parentName, childNameComponent);
continue;
} else {
if (Log.isLoggable(Level.INFO)) {
Log.info("EnumeratedNameList.exists: the parent enumerator {0} has {1} children but none of them are {2}.",
parentName, parentEnumerator.childCount(), Component.printURI(childNameComponent));
}
break;
}
}
if (Log.isLoggable(Log.FAC_SEARCH, Level.INFO))
Log.info(Log.FAC_SEARCH, "EnumeratedNameList.exists: returning null for search of {0}", childName);
return null;
}
private NewChildrenByThread getNcbt() {
Long id = Thread.currentThread().getId();
NewChildrenByThread ncbt = _newChildrenByThread.get(id);
if (null == ncbt)
ncbt = _newChildrenByThread.get(0); // Thread pool
return ncbt;
}
/**
* Enables an EnumeratedNameList to be used directly in a ContentName builder.
* @return Gets the ContentName of the prefix being enumerated
* @see ContentNameProvider
* @see ContentName#builder(org.ccnx.ccn.protocol.ContentName.StringParser, Object[])
*/
public ContentName getContentName() {
return _namePrefix;
}
}
| true | true | public static EnumeratedNameList exists(ContentName childName, ContentName prefixKnownToExist, CCNHandle handle) throws IOException {
if (Log.isLoggable(Log.FAC_SEARCH, Level.INFO))
Log.info(Log.FAC_SEARCH, "EnumeratedNameList.exists: the prefix known to exist is {0} and we are looking for childName {1}", prefixKnownToExist, childName);
if ((null == prefixKnownToExist) || (null == childName) || (!prefixKnownToExist.isPrefixOf(childName))) {
if (Log.isLoggable(Log.FAC_SEARCH, Level.INFO))
Log.info(Log.FAC_SEARCH, "EnumeratedNameList.exists: Child {0} must be prefixed by name {1}", childName, prefixKnownToExist);
throw new IllegalArgumentException("Child " + childName + " must be prefixed by name " + prefixKnownToExist);
}
if (childName.count() == prefixKnownToExist.count()) {
// we're already there
if (Log.isLoggable(Log.FAC_SEARCH, Level.INFO))
Log.info(Log.FAC_SEARCH, "EnumeratedNameList.exists: we're already there.");
return new EnumeratedNameList(childName, handle);
}
ContentName parentName = prefixKnownToExist;
int childIndex = parentName.count();
EnumeratedNameList parentEnumerator = null;
while (childIndex < childName.count()) {
byte[] childNameComponent = childName.component(childIndex);
parentEnumerator = new EnumeratedNameList(parentName, handle);
if (Log.isLoggable(Log.FAC_SEARCH, Level.INFO))
Log.info(Log.FAC_SEARCH, "EnumeratedNameList.exists: enumerating the parent name {0}", parentName);
parentEnumerator.waitForChildren(SystemConfiguration.MAX_TIMEOUT);
while (! parentEnumerator.hasChild(childNameComponent)) {
if (! parentEnumerator.waitForNewChildren(false, SystemConfiguration.MAX_TIMEOUT)) break;
}
if (parentEnumerator.hasChild(childNameComponent)) {
if (Log.isLoggable(Level.INFO)) {
Log.info("EnumeratedNameList.exists: we have a matching child to {0} and the parent enumerator {1} has {2} children.",
Component.printURI(childNameComponent), parentName, parentEnumerator.childCount());
}
childIndex++;
if (childIndex == childName.count()) {
if (Log.isLoggable(Log.FAC_SEARCH, Level.INFO))
Log.info(Log.FAC_SEARCH, "EnumeratedNameList.exists: we found the childName we were looking for: {0}", childName);
return parentEnumerator;
}
parentEnumerator.stopEnumerating();
parentName = new ContentName(parentName, childNameComponent);
continue;
} else {
if (Log.isLoggable(Level.INFO)) {
Log.info("EnumeratedNameList.exists: the parent enumerator {0} has {1} children but none of them are {2}.",
parentName, parentEnumerator.childCount(), Component.printURI(childNameComponent));
}
break;
}
}
if (Log.isLoggable(Log.FAC_SEARCH, Level.INFO))
Log.info(Log.FAC_SEARCH, "EnumeratedNameList.exists: returning null for search of {0}", childName);
return null;
}
| public static EnumeratedNameList exists(ContentName childName, ContentName prefixKnownToExist, CCNHandle handle) throws IOException {
if (Log.isLoggable(Log.FAC_SEARCH, Level.INFO))
Log.info(Log.FAC_SEARCH, "EnumeratedNameList.exists: the prefix known to exist is {0} and we are looking for childName {1}", prefixKnownToExist, childName);
if ((null == prefixKnownToExist) || (null == childName) || (!prefixKnownToExist.isPrefixOf(childName))) {
if (Log.isLoggable(Log.FAC_SEARCH, Level.INFO))
Log.info(Log.FAC_SEARCH, "EnumeratedNameList.exists: Child {0} must be prefixed by name {1}", childName, prefixKnownToExist);
throw new IllegalArgumentException("Child " + childName + " must be prefixed by name " + prefixKnownToExist);
}
if (childName.count() == prefixKnownToExist.count()) {
// we're already there
if (Log.isLoggable(Log.FAC_SEARCH, Level.INFO))
Log.info(Log.FAC_SEARCH, "EnumeratedNameList.exists: we're already there.");
return new EnumeratedNameList(childName, handle);
}
ContentName parentName = prefixKnownToExist;
int childIndex = parentName.count();
EnumeratedNameList parentEnumerator = null;
while (childIndex < childName.count()) {
byte[] childNameComponent = childName.component(childIndex);
parentEnumerator = new EnumeratedNameList(parentName, handle);
if (Log.isLoggable(Log.FAC_SEARCH, Level.INFO))
Log.info(Log.FAC_SEARCH, "EnumeratedNameList.exists: enumerating the parent name {0}", parentName);
parentEnumerator.waitForChildren(SystemConfiguration.MAX_TIMEOUT);
while (! parentEnumerator.hasChild(childNameComponent)) {
if (! parentEnumerator.waitForNewChildren(false, SystemConfiguration.MAX_TIMEOUT)) break;
}
if (parentEnumerator.hasChild(childNameComponent)) {
if (Log.isLoggable(Log.FAC_SEARCH, Level.INFO)) {
Log.info(Log.FAC_SEARCH, "EnumeratedNameList.exists: we have a matching child to {0} and the parent enumerator {1} has {2} children.",
Component.printURI(childNameComponent), parentName, parentEnumerator.childCount());
}
childIndex++;
if (childIndex == childName.count()) {
if (Log.isLoggable(Log.FAC_SEARCH, Level.INFO))
Log.info(Log.FAC_SEARCH, "EnumeratedNameList.exists: we found the childName we were looking for: {0}", childName);
return parentEnumerator;
}
parentEnumerator.stopEnumerating();
parentName = new ContentName(parentName, childNameComponent);
continue;
} else {
if (Log.isLoggable(Level.INFO)) {
Log.info("EnumeratedNameList.exists: the parent enumerator {0} has {1} children but none of them are {2}.",
parentName, parentEnumerator.childCount(), Component.printURI(childNameComponent));
}
break;
}
}
if (Log.isLoggable(Log.FAC_SEARCH, Level.INFO))
Log.info(Log.FAC_SEARCH, "EnumeratedNameList.exists: returning null for search of {0}", childName);
return null;
}
|
diff --git a/android/src/org/coolreader/crengine/Engine.java b/android/src/org/coolreader/crengine/Engine.java
index c1fc2d6d..52023b41 100644
--- a/android/src/org/coolreader/crengine/Engine.java
+++ b/android/src/org/coolreader/crengine/Engine.java
@@ -1,842 +1,842 @@
package org.coolreader.crengine;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.coolreader.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.util.Log;
/**
* CoolReader Engine class.
*
* Only one instance is allowed.
*/
public class Engine {
private final Activity mActivity;
private final BackgroundThread mBackgroundThread;
//private final View mMainView;
//private final ExecutorService mExecutor = Executors.newFixedThreadPool(1);
/**
* Get storage root directories.
* @return array of r/w storage roots
*/
public static File[] getStorageDirectories( boolean writableOnly ) {
ArrayList<File> res = new ArrayList<File>(2);
File dir = Environment.getExternalStorageDirectory();
if ( dir.isDirectory() && (!writableOnly || dir.canWrite()) )
res.add(dir);
File dir2 = new File("/system/media/sdcard");
if ( dir2.isDirectory() && (!writableOnly || dir2.canWrite()))
res.add(dir2);
File dir22 = new File("/sdcard2");
if ( dir22.isDirectory() && (!writableOnly || dir22.canWrite()))
res.add(dir22);
File dir3 = new File("/nand");
if ( dir3.isDirectory() && (!writableOnly || dir3.canWrite()))
res.add(dir3);
File dir4 = new File("/PocketBook701");
if ( dir4.isDirectory() && (!writableOnly || dir4.canWrite()))
res.add(dir4);
return res.toArray( new File[] {});
}
/**
* Get or create writable subdirectory for specified base directory
* @param dir is base directory
* @param subdir is subdirectory name, null to use base directory
* @param createIfNotExists is true to force directory creation
* @return writable directory, null if not exist or not writable
*/
public static File getSubdir( File dir, String subdir, boolean createIfNotExists, boolean writableOnly )
{
if ( dir==null )
return null;
File dataDir = dir;
if ( subdir!=null ) {
dataDir = new File( dataDir, subdir );
if ( !dataDir.isDirectory() && createIfNotExists )
dataDir.mkdir();
}
if ( dataDir.isDirectory() && (!writableOnly || dataDir.canWrite()) )
return dataDir;
return null;
}
/**
* Returns array of writable data directories on external storage
* @param subdir
* @param createIfNotExists
* @return
*/
public static File[] getDataDirectories( String subdir, boolean createIfNotExists, boolean writableOnly ) {
File[] roots = getStorageDirectories(writableOnly);
ArrayList<File> res = new ArrayList<File>(roots.length);
for ( File dir : roots ) {
File dataDir = getSubdir( dir, ".cr3", createIfNotExists, writableOnly );
if ( subdir!=null )
dataDir = getSubdir( dataDir, subdir, createIfNotExists, writableOnly );
if ( dataDir!=null )
res.add(dataDir);
}
return res.toArray(new File[] {});
}
public interface EngineTask {
public void work() throws Exception;
public void done();
public void fail( Exception e );
}
// public static class FatalError extends RuntimeException {
// private Engine engine;
// private String msg;
// public FatalError( Engine engine, String msg )
// {
// this.engine = engine;
// this.msg = msg;
// }
// public void handle()
// {
// engine.fatalError(msg);
// }
// }
public final static boolean LOG_ENGINE_TASKS = false;
private class TaskHandler implements Runnable {
final EngineTask task;
public TaskHandler( EngineTask task )
{
this.task = task;
}
public String toString() {
return "[handler for " + this.task.toString() + "]";
}
public void run() {
try {
if ( LOG_ENGINE_TASKS )
Log.i("cr3", "running task.work() " + task.getClass().getName());
if ( !initialized )
throw new IllegalStateException("Engine not initialized");
// run task
task.work();
if ( LOG_ENGINE_TASKS )
Log.i("cr3", "exited task.work() " + task.getClass().getName());
// post success callback
mBackgroundThread.postGUI(new Runnable() {
public void run() {
if ( LOG_ENGINE_TASKS )
Log.i("cr3", "running task.done() " + task.getClass().getName() + " in gui thread");
task.done();
}
});
// } catch ( final FatalError e ) {
//TODO:
// Handler h = view.getHandler();
//
// if ( h==null ) {
// View root = view.getRootView();
// h = root.getHandler();
// }
// if ( h==null ) {
// //
// e.handle();
// } else {
// h.postAtFrontOfQueue(new Runnable() {
// public void run() {
// e.handle();
// }
// });
// }
} catch ( final Exception e ) {
Log.e("cr3", "exception while running task " + task.getClass().getName(), e);
// post error callback
mBackgroundThread.postGUI(new Runnable() {
public void run() {
Log.e("cr3", "running task.fail("+e.getMessage()+") " + task.getClass().getSimpleName() + " in gui thread ");
task.fail(e);
}
});
}
}
}
/**
* Execute task in Engine thread
* @param task is task to execute
*/
public void execute( final EngineTask task )
{
if ( LOG_ENGINE_TASKS )
Log.d("cr3", "executing task " + task.getClass().getSimpleName());
TaskHandler taskHandler = new TaskHandler( task );
mBackgroundThread.executeBackground( taskHandler );
}
/**
* Schedule task for execution in Engine thread
* @param task is task to execute
*/
public void post( final EngineTask task )
{
if ( LOG_ENGINE_TASKS )
Log.d("cr3", "executing task " + task.getClass().getSimpleName());
TaskHandler taskHandler = new TaskHandler( task );
mBackgroundThread.postBackground( taskHandler );
}
/**
* Schedule Runnable for execution in GUI thread after all current Engine queue tasks done.
* @param task
*/
public void runInGUI( final Runnable task )
{
execute( new EngineTask() {
public void done() {
mBackgroundThread.postGUI(task);
}
public void fail(Exception e) {
// do nothing
}
public void work() throws Exception {
// do nothing
}
});
}
public void fatalError( String msg)
{
AlertDialog dlg = new AlertDialog.Builder(mActivity).setMessage(msg).setTitle("CoolReader fatal error").show();
try {
Thread.sleep(10);
} catch ( InterruptedException e ) {
// do nothing
}
dlg.dismiss();
mActivity.finish();
}
private ProgressDialog mProgress;
private boolean enable_progress = true;
private boolean progressShown = false;
private static int PROGRESS_STYLE = ProgressDialog.STYLE_HORIZONTAL;
private Drawable progressIcon = null;
// public void setProgressDrawable( final BitmapDrawable drawable )
// {
// if ( enable_progress ) {
// mBackgroundThread.executeGUI( new Runnable() {
// public void run() {
// // show progress
// Log.v("cr3", "showProgress() - in GUI thread");
// if ( mProgress!=null && progressShown ) {
// hideProgress();
// progressIcon = drawable;
// showProgress(mProgressPos, mProgressMessage);
// //mProgress.setIcon(drawable);
// }
// }
// });
// }
// }
public void showProgress( final int mainProgress, final int resourceId )
{
showProgress( mainProgress, mActivity.getResources().getString(resourceId) );
}
private String mProgressMessage = null;
private int mProgressPos = 0;
private volatile int nextProgressId = 0;
private void showProgress( final int mainProgress, final String msg )
{
final int progressId = ++nextProgressId;
mProgressMessage = msg;
mProgressPos = mainProgress;
if ( mainProgress==10000 ) {
Log.v("cr3", "mainProgress==10000 : calling hideProgress");
hideProgress();
return;
}
Log.v("cr3", "showProgress(" + mainProgress + ", \"" + msg + "\") is called : " + Thread.currentThread().getName());
if ( enable_progress ) {
mBackgroundThread.executeGUI( new Runnable() {
public void run() {
// show progress
Log.v("cr3", "showProgress() - in GUI thread");
if ( progressId!= nextProgressId ) {
Log.v("cr3", "showProgress() - skipping duplicate progress event");
return;
}
if ( mProgress==null ) {
Log.v("cr3", "showProgress() - in GUI thread : creating progress window");
if ( PROGRESS_STYLE == ProgressDialog.STYLE_HORIZONTAL ) {
mProgress = new ProgressDialog(mActivity);
mProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
if ( progressIcon!=null )
mProgress.setIcon(progressIcon);
else
- mProgress.setIcon(R.drawable.cr3_logo_small);
+ mProgress.setIcon(R.drawable.cr3_logo);
mProgress.setMax(10000);
mProgress.setCancelable(false);
mProgress.setProgress(mainProgress);
mProgress.setTitle(mActivity.getResources().getString(R.string.progress_please_wait));
mProgress.setMessage(msg);
mProgress.show();
} else {
mProgress = ProgressDialog.show(mActivity, "Please Wait", msg);
mProgress.setCancelable(false);
mProgress.setProgress(mainProgress);
}
progressShown = true;
} else {
mProgress.setProgress(mainProgress);
mProgress.setMessage(msg);
if ( !mProgress.isShowing() ) {
mProgress.show();
progressShown = true;
}
}
}
});
}
}
public void hideProgress()
{
final int progressId = ++nextProgressId;
Log.v("cr3", "hideProgress() - is called : " + Thread.currentThread().getName());
//Log.v("cr3", "hideProgress() is called");
mBackgroundThread.executeGUI( new Runnable() {
public void run() {
// hide progress
Log.v("cr3", "hideProgress() - in GUI thread");
if ( progressId!= nextProgressId ) {
Log.v("cr3", "hideProgress() - skipping duplicate progress event");
return;
}
if ( mProgress!=null ) {
// if ( mProgress.isShowing() )
// mProgress.hide();
progressShown = false;
progressIcon = null;
mProgress.dismiss();
mProgress = null;
Log.v("cr3", "hideProgress() - in GUI thread, finished");
}
}
});
}
public boolean isProgressShown()
{
return progressShown;
}
public String loadFileUtf8( File file )
{
try {
InputStream is = new FileInputStream(file);
return loadResourceUtf8(is);
} catch ( Exception e ) {
Log.e("cr3", "cannot load resource from file " + file);
return null;
}
}
public String loadResourceUtf8( int id )
{
try {
InputStream is = this.mActivity.getResources().openRawResource( id );
return loadResourceUtf8(is);
} catch ( Exception e ) {
Log.e("cr3", "cannot load resource " + id);
return null;
}
}
public String loadResourceUtf8( InputStream is )
{
try {
int available = is.available();
if ( available<=0 )
return null;
byte buf[] = new byte[available];
if ( is.read(buf)!=available )
throw new IOException("Resource not read fully");
is.close();
String utf8 = new String(buf, 0, available, "UTF8");
return utf8;
} catch ( Exception e ) {
Log.e("cr3", "cannot load resource");
return null;
}
}
public byte[] loadResourceBytes( int id )
{
try {
InputStream is = this.mActivity.getResources().openRawResource( id );
return loadResourceBytes(is);
} catch ( Exception e ) {
Log.e("cr3", "cannot load resource");
return null;
}
}
public static byte[] loadResourceBytes( File f )
{
if ( f==null || !f.isFile() || !f.exists() )
return null;
FileInputStream is = null;
try {
is = new FileInputStream(f);
byte[] res = loadResourceBytes( is );
return res;
} catch ( IOException e ) {
Log.e("cr3", "Cannot open file " + f);
}
return null;
}
public static byte[] loadResourceBytes( InputStream is )
{
try {
int available = is.available();
if ( available<=0 )
return null;
byte buf[] = new byte[available];
if ( is.read(buf)!=available )
throw new IOException("Resource not read fully");
is.close();
return buf;
} catch ( Exception e ) {
Log.e("cr3", "cannot load resource");
return null;
}
}
/**
* Initialize CoolReader Engine
* @param fontList is array of .ttf font pathnames to load
*/
public Engine( Activity activity, BackgroundThread backgroundThread )
{
this.mActivity = activity;
this.mBackgroundThread = backgroundThread;
//this.mMainView = mainView;
Log.i("cr3", "Engine() : scheduling init task");
mBackgroundThread.executeBackground( new Runnable() {
public void run()
{
try {
Log.i("cr3", "Engine() : running init() in engine thread");
init();
// android.view.ViewRoot.getRunQueue().post(new Runnable() {
// public void run() {
//
// }
// });
} catch ( final Exception e ) {
Log.e("cr3", "Exception while initializing Engine", e);
// handler.post(new Runnable() {
// public void run() {
// // TODO: fatal error
// }
// });
}
}
});
}
private native boolean initInternal( String[] fontList );
private native void uninitInternal();
private native String[] getFontFaceListInternal();
private native String[] getArchiveItemsInternal( String arcName ); // pairs: pathname, size
private native boolean setCacheDirectoryInternal( String dir, int size );
private native boolean scanBookPropertiesInternal( FileInfo info );
private static final int HYPH_NONE = 0;
private static final int HYPH_ALGO = 1;
private static final int HYPH_DICT = 2;
private native boolean setHyphenationMethod( int type, byte[] dictData );
public ArrayList<ZipEntry> getArchiveItems( String zipFileName )
{
final int itemsPerEntry = 2;
String[] in = getArchiveItemsInternal( zipFileName );
ArrayList<ZipEntry> list = new ArrayList<ZipEntry>();
for ( int i=0; i<=in.length-itemsPerEntry; i+=itemsPerEntry ) {
ZipEntry e = new ZipEntry(in[i]);
e.setSize(Integer.valueOf(in[i+1]));
e.setCompressedSize(Integer.valueOf(in[i+1]));
list.add(e);
}
return list;
}
public enum HyphDict {
NONE(HYPH_NONE, 0, "[None]"),
ALGORITHM(HYPH_ALGO,0, "[Algorythmic]"),
RUSSIAN(HYPH_DICT,R.raw.russian_enus_hyphen, "Russian"),
ENGLISH(HYPH_DICT,R.raw.english_us_hyphen, "English US"),
GERMAN(HYPH_DICT,R.raw.german_hyphen, "German"),
UKRAINIAN(HYPH_DICT,R.raw.ukrain_hyphen, "Ukrainian"),
SPANISH(HYPH_DICT,R.raw.spanish_hyphen, "Spanish"),
FRENCH(HYPH_DICT,R.raw.french_hyphen, "French"),
BULGARIAN(HYPH_DICT,R.raw.bulgarian_hyphen, "Bulgarian"),
SWEDISH(HYPH_DICT,R.raw.swedish_hyphen, "Swedish"),
POLISH(HYPH_DICT,R.raw.polish_hyphen, "Polish"),
;
public final int type;
public final int resource;
public final String name;
private HyphDict( int type, int resource, String name ) {
this.type = type;
this.resource = resource;
this.name = name;
}
public static HyphDict byCode( String code )
{
for ( HyphDict dict : values() )
if ( dict.toString().equals(code) )
return dict;
return NONE;
}
};
private HyphDict currentHyphDict = HyphDict.NONE;
public boolean setHyphenationDictionary( final HyphDict dict )
{
Log.i("cr3", "setHyphenationDictionary( " + dict + " ) is called");
if ( currentHyphDict==dict )
return false;
currentHyphDict = dict;
//byte[] image = loadResourceBytes(R.drawable.tx_old_book);
BackgroundThread.backgroundExecutor.execute( new Runnable() {
public void run() {
byte[] data = null;
if ( dict.type==HYPH_DICT && dict.resource!=0 ) {
data = loadResourceBytes( dict.resource );
}
Log.i("cr3", "Setting engine's hyphenation dictionary to " + dict);
setHyphenationMethod(dict.type, data);
}
});
return true;
}
public boolean scanBookProperties(FileInfo info)
{
if ( !initialized )
throw new IllegalStateException("CREngine is not initialized");
return scanBookPropertiesInternal( info );
}
public String[] getFontFaceList()
{
if ( !initialized )
throw new IllegalStateException("CREngine is not initialized");
return getFontFaceListInternal();
}
final int CACHE_DIR_SIZE = 32000000;
private String createCacheDir( File baseDir, String subDir )
{
String cacheDirName = null;
if ( baseDir.isDirectory() ) {
if ( baseDir.canWrite() ) {
if ( subDir!=null ) {
baseDir = new File(baseDir, subDir);
baseDir.mkdir();
}
if ( baseDir.exists() && baseDir.canWrite() ) {
File cacheDir = new File(baseDir, ".cache");
if ( cacheDir.exists() || cacheDir.mkdirs() ) {
if ( cacheDir.canWrite() ) {
cacheDirName = cacheDir.getAbsolutePath();
}
}
}
} else {
Log.i("cr3", baseDir.toString() + " is read only");
}
} else {
Log.i("cr3", baseDir.toString() + " is not found");
}
return cacheDirName;
}
private void initCacheDirectory()
{
String cacheDirName = null;
// SD card
cacheDirName = createCacheDir( Environment.getExternalStorageDirectory(), "Books" );
// internal SD card on Nook
if ( cacheDirName==null )
cacheDirName = createCacheDir( new File("/system/media/sdcard"), "Books" );
// internal flash
if ( cacheDirName==null ) {
File cacheDir = mActivity.getCacheDir();
if ( !cacheDir.isDirectory() )
cacheDir.mkdir();
//File cacheDir = mActivity.getDir("cache", Context.MODE_PRIVATE);
if ( cacheDir.isDirectory() && cacheDir.canWrite() )
cacheDirName = cacheDir.getAbsolutePath();
}
// set cache directory for engine
if ( cacheDirName!=null ) {
Log.i("cr3", cacheDirName + " will be used for cache, maxCacheSize=" + CACHE_DIR_SIZE);
setCacheDirectoryInternal(cacheDirName, CACHE_DIR_SIZE);
}
}
private void init() throws IOException
{
if ( initialized )
throw new IllegalStateException("Already initialized");
installLibrary();
String[] fonts = findFonts();
if ( !initInternal( fonts ) )
throw new IOException("Cannot initialize CREngine JNI");
// Initialization of cache directory
initCacheDirectory();
initialized = true;
}
// public void waitTasksCompletion()
// {
// Log.i("cr3", "waiting for engine tasks completion");
// try {
// mExecutor.awaitTermination(0, TimeUnit.SECONDS);
// } catch (InterruptedException e) {
// // ignore
// }
// }
/**
* Uninitialize engine.
*/
public void uninit()
{
Log.i("cr3", "Engine.uninit() is called");
BackgroundThread.backgroundExecutor.execute(new Runnable() {
public void run() {
Log.i("cr3", "Engine.uninit() : in background thread");
if ( initialized ) {
uninitInternal();
initialized = false;
}
}
});
//TODO:
//waitTasksCompletion();
}
protected void finalize() throws Throwable
{
Log.i("cr3", "Engine.finalize() is called");
// if ( initialized ) {
// //uninitInternal();
// initialized = false;
// }
}
static private boolean initialized = false;
private String[] findFonts()
{
ArrayList<File> dirs = new ArrayList<File>();
File[] dataDirs = getDataDirectories("fonts", false, false);
for ( File dir : dataDirs )
dirs.add(dir);
File[] rootDirs = getStorageDirectories(false);
for ( File dir : rootDirs )
dirs.add(new File(dir, "fonts") );
dirs.add(new File( Environment.getRootDirectory(), "fonts"));
ArrayList<String> fontPaths = new ArrayList<String>();
for ( File fontDir : dirs ) {
if ( fontDir.isDirectory() ) {
Log.v("cr3", "Scanning directory " + fontDir.getAbsolutePath() + " for font files");
// get font names
String[] fileList = fontDir.list(
new FilenameFilter() {
public boolean accept(File dir, String filename)
{
return filename.toLowerCase().endsWith(".ttf") && !filename.endsWith("Fallback.ttf");
}
});
// append path
for ( int i=0; i<fileList.length; i++ ) {
String pathName = new File(fontDir, fileList[i]).getAbsolutePath();
fontPaths.add( pathName );
Log.v("cr3", "found font: " + pathName);
}
}
}
return fontPaths.toArray(new String[] {});
}
private boolean force_install_library = false;
private void installLibrary()
{
try {
if ( force_install_library )
throw new Exception("forcing install");
// try loading library w/o manual installation
Log.i("cr3", "trying to load library cr3engine w/o installation");
System.loadLibrary("cr3engine");
Log.i("cr3", "cr3engine loaded successfully");
} catch ( Exception ee ) {
Log.i("cr3", "cr3engine not found using standard paths, will install manually");
File sopath = mActivity.getDir("libs", Context.MODE_PRIVATE);
File soname = new File(sopath, "libcr3engine.so");
try {
sopath.mkdirs();
File zip = new File(mActivity.getPackageCodePath());
ZipFile zipfile = new ZipFile(zip);
ZipEntry zipentry = zipfile.getEntry("lib/armeabi/libcr3engine.so");
if ( !soname.exists() || zipentry.getSize()!=soname.length() ) {
InputStream is = zipfile.getInputStream(zipentry);
OutputStream os = new FileOutputStream(soname);
Log.i("cr3", "Installing JNI library " + soname.getAbsolutePath());
final int BUF_SIZE = 0x10000;
byte[] buf = new byte[BUF_SIZE];
int n;
while ((n = is.read(buf)) > 0)
os.write(buf, 0, n);
is.close();
os.close();
} else {
Log.i("cr3", "JNI library " + soname.getAbsolutePath() + " is up to date");
}
System.load(soname.getAbsolutePath());
} catch ( Exception e ) {
Log.e("cr3", "cannot install cr3engine library", e);
}
}
}
public static final BackgroundTextureInfo NO_TEXTURE = new BackgroundTextureInfo(BackgroundTextureInfo.NO_TEXTURE_ID, "(SOLID COLOR)", 0);
private static final BackgroundTextureInfo[] internalTextures = {
NO_TEXTURE,
new BackgroundTextureInfo("bg_paper1", "Paper 1", R.drawable.bg_paper1),
new BackgroundTextureInfo("bg_paper1_dark", "Paper 1 (dark)", R.drawable.bg_paper1_dark),
new BackgroundTextureInfo("tx_wood_dark", "Wood (dark)", R.drawable.tx_wood_dark),
new BackgroundTextureInfo("tx_wood", "Wood", R.drawable.tx_wood),
new BackgroundTextureInfo("tx_wood_dark", "Wood (dark)", R.drawable.tx_wood_dark),
new BackgroundTextureInfo("tx_fabric", "Fabric", R.drawable.tx_fabric),
new BackgroundTextureInfo("tx_fabric_dark", "Fabric (dark)", R.drawable.tx_fabric_dark),
new BackgroundTextureInfo("tx_fabric_indigo_fibre", "Fabric fibre", R.drawable.tx_fabric_indigo_fibre),
new BackgroundTextureInfo("tx_fabric_indigo_fibre_dark", "Fabric fibre (dark)", R.drawable.tx_fabric_indigo_fibre_dark),
new BackgroundTextureInfo("tx_gray_sand", "Gray sand", R.drawable.tx_gray_sand),
new BackgroundTextureInfo("tx_gray_sand_dark", "Gray sand (dark)", R.drawable.tx_gray_sand_dark),
new BackgroundTextureInfo("tx_green_wall", "Green wall", R.drawable.tx_green_wall),
new BackgroundTextureInfo("tx_green_wall_dark", "Green wall (dark)", R.drawable.tx_green_wall_dark),
new BackgroundTextureInfo("tx_metal_red_light", "Metall red", R.drawable.tx_metal_red_light),
new BackgroundTextureInfo("tx_metal_red_dark", "Metall red (dark)", R.drawable.tx_metal_red_dark),
new BackgroundTextureInfo("tx_metall_copper", "Metall copper", R.drawable.tx_metall_copper),
new BackgroundTextureInfo("tx_metall_copper_dark", "Metall copper (dark)", R.drawable.tx_metall_copper_dark),
new BackgroundTextureInfo("tx_metall_old_blue", "Metall blue", R.drawable.tx_metall_old_blue),
new BackgroundTextureInfo("tx_metall_old_blue_dark", "Metall blue (dark)", R.drawable.tx_metall_old_blue_dark),
new BackgroundTextureInfo("tx_old_book", "Old book", R.drawable.tx_old_book),
new BackgroundTextureInfo("tx_old_book_dark", "Old book (dark)", R.drawable.tx_old_book_dark),
new BackgroundTextureInfo("tx_old_paper", "Old paper", R.drawable.tx_old_paper),
new BackgroundTextureInfo("tx_old_paper_dark", "Old paper (dark)", R.drawable.tx_old_paper_dark),
new BackgroundTextureInfo("tx_paper", "Paper", R.drawable.tx_paper),
new BackgroundTextureInfo("tx_paper_dark", "Paper (dark)", R.drawable.tx_paper_dark),
new BackgroundTextureInfo("tx_rust", "Rust", R.drawable.tx_rust),
new BackgroundTextureInfo("tx_rust_dark", "Rust (dark)", R.drawable.tx_rust_dark),
new BackgroundTextureInfo("tx_sand", "Sand", R.drawable.tx_sand),
new BackgroundTextureInfo("tx_sand_dark", "Sand (dark)", R.drawable.tx_sand_dark),
new BackgroundTextureInfo("tx_stones", "Stones", R.drawable.tx_stones),
new BackgroundTextureInfo("tx_stones_dark", "Stones (dark)", R.drawable.tx_stones_dark),
};
public static final String DEF_DAY_BACKGROUND_TEXTURE = "tx_fabric";
public static final String DEF_NIGHT_BACKGROUND_TEXTURE = "tx_metall_old_blue_dark";
public BackgroundTextureInfo[] getAvailableTextures() {
ArrayList<BackgroundTextureInfo> list = new ArrayList<BackgroundTextureInfo>(internalTextures.length);
list.add(NO_TEXTURE);
findExternalTextures( list );
for ( int i=1; i<internalTextures.length; i++ )
list.add(internalTextures[i]);
return list.toArray( new BackgroundTextureInfo[] {});
}
public void findTexturesFromDirectory( File dir, Collection<BackgroundTextureInfo> listToAppend )
{
for ( File f : dir.listFiles() ) {
if ( !f.isDirectory() ) {
BackgroundTextureInfo item = BackgroundTextureInfo.fromFile(f.getAbsolutePath());
if (item!=null )
listToAppend.add(item);
}
}
}
public void findExternalTextures( Collection<BackgroundTextureInfo> listToAppend )
{
for ( File d : getStorageDirectories(false) ) {
File base = new File(d, ".cr3");
if ( !base.isDirectory() )
base = new File(d, "cr3");
if ( !base.isDirectory() )
continue;
File subdirTextures = new File(base, "textures");
File subdirBackgrounds = new File(base, "backgrounds");
if ( subdirTextures.isDirectory() )
findTexturesFromDirectory( subdirTextures, listToAppend );
if ( subdirBackgrounds.isDirectory() )
findTexturesFromDirectory( subdirBackgrounds, listToAppend );
}
}
public byte[] getImageData( BackgroundTextureInfo texture ) {
if ( texture.isNone() )
return null;
if ( texture.resourceId!=0 ) {
byte[] data = loadResourceBytes(texture.resourceId);
return data;
} else if (texture.id!=null && texture.id.startsWith("/") ) {
File f = new File(texture.id);
byte[] data = loadResourceBytes(f);
return data;
}
return null;
}
public BackgroundTextureInfo getTextureInfoById( String id ) {
if ( id==null )
return NO_TEXTURE;
if ( id.startsWith("/") ) {
BackgroundTextureInfo item = BackgroundTextureInfo.fromFile(id);
if ( item!=null )
return item;
} else {
for ( BackgroundTextureInfo item : internalTextures )
if ( item.id.equals(id))
return item;
}
return NO_TEXTURE;
}
}
| true | true | private void showProgress( final int mainProgress, final String msg )
{
final int progressId = ++nextProgressId;
mProgressMessage = msg;
mProgressPos = mainProgress;
if ( mainProgress==10000 ) {
Log.v("cr3", "mainProgress==10000 : calling hideProgress");
hideProgress();
return;
}
Log.v("cr3", "showProgress(" + mainProgress + ", \"" + msg + "\") is called : " + Thread.currentThread().getName());
if ( enable_progress ) {
mBackgroundThread.executeGUI( new Runnable() {
public void run() {
// show progress
Log.v("cr3", "showProgress() - in GUI thread");
if ( progressId!= nextProgressId ) {
Log.v("cr3", "showProgress() - skipping duplicate progress event");
return;
}
if ( mProgress==null ) {
Log.v("cr3", "showProgress() - in GUI thread : creating progress window");
if ( PROGRESS_STYLE == ProgressDialog.STYLE_HORIZONTAL ) {
mProgress = new ProgressDialog(mActivity);
mProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
if ( progressIcon!=null )
mProgress.setIcon(progressIcon);
else
mProgress.setIcon(R.drawable.cr3_logo_small);
mProgress.setMax(10000);
mProgress.setCancelable(false);
mProgress.setProgress(mainProgress);
mProgress.setTitle(mActivity.getResources().getString(R.string.progress_please_wait));
mProgress.setMessage(msg);
mProgress.show();
} else {
mProgress = ProgressDialog.show(mActivity, "Please Wait", msg);
mProgress.setCancelable(false);
mProgress.setProgress(mainProgress);
}
progressShown = true;
} else {
mProgress.setProgress(mainProgress);
mProgress.setMessage(msg);
if ( !mProgress.isShowing() ) {
mProgress.show();
progressShown = true;
}
}
}
});
}
}
| private void showProgress( final int mainProgress, final String msg )
{
final int progressId = ++nextProgressId;
mProgressMessage = msg;
mProgressPos = mainProgress;
if ( mainProgress==10000 ) {
Log.v("cr3", "mainProgress==10000 : calling hideProgress");
hideProgress();
return;
}
Log.v("cr3", "showProgress(" + mainProgress + ", \"" + msg + "\") is called : " + Thread.currentThread().getName());
if ( enable_progress ) {
mBackgroundThread.executeGUI( new Runnable() {
public void run() {
// show progress
Log.v("cr3", "showProgress() - in GUI thread");
if ( progressId!= nextProgressId ) {
Log.v("cr3", "showProgress() - skipping duplicate progress event");
return;
}
if ( mProgress==null ) {
Log.v("cr3", "showProgress() - in GUI thread : creating progress window");
if ( PROGRESS_STYLE == ProgressDialog.STYLE_HORIZONTAL ) {
mProgress = new ProgressDialog(mActivity);
mProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
if ( progressIcon!=null )
mProgress.setIcon(progressIcon);
else
mProgress.setIcon(R.drawable.cr3_logo);
mProgress.setMax(10000);
mProgress.setCancelable(false);
mProgress.setProgress(mainProgress);
mProgress.setTitle(mActivity.getResources().getString(R.string.progress_please_wait));
mProgress.setMessage(msg);
mProgress.show();
} else {
mProgress = ProgressDialog.show(mActivity, "Please Wait", msg);
mProgress.setCancelable(false);
mProgress.setProgress(mainProgress);
}
progressShown = true;
} else {
mProgress.setProgress(mainProgress);
mProgress.setMessage(msg);
if ( !mProgress.isShowing() ) {
mProgress.show();
progressShown = true;
}
}
}
});
}
}
|
diff --git a/TingJpct7/scene/com/ting/scene/Scene.java b/TingJpct7/scene/com/ting/scene/Scene.java
index 1b7bbc2..7303d8b 100644
--- a/TingJpct7/scene/com/ting/scene/Scene.java
+++ b/TingJpct7/scene/com/ting/scene/Scene.java
@@ -1,45 +1,45 @@
package com.ting.scene;
import com.threed.jpct.Light;
import com.threed.jpct.Object3D;
import com.threed.jpct.RGBColor;
import com.threed.jpct.SimpleVector;
public class Scene extends BaseScene {
public RGBColor background = new RGBColor(20, 120, 20);
public RGBColor ambient = new RGBColor(0, 255, 0);
Object3D shape;
SimpleVector lightOffset = new SimpleVector(-100, -100, -75);
public Scene() {
//world.setAmbientLight(ambient.getRed(), ambient.getGreen(), ambient.getBlue());
- shape = loadOBJ("BMan_02", 3);
+ shape = loadOBJ("BMan_02", 6);
// shape.calcTextureWrapSpherical();
shape.setTexture(addTexture("BMan_02.png"));
shape.build();
world.addObject(shape);
- world.getCamera().setPosition(50, -20, -5);
+ world.getCamera().setPosition(50, -40, -15);
world.getCamera().lookAt(shape.getTransformedCenter());
Light light = new Light(world);
light.setIntensity(250, 250, 250);
light.setPosition(shape.getTransformedCenter().calcAdd(lightOffset));
}
public void loop() {
shape.rotateY(0.01f);
}
public void move(float dx, float dy) {
if (dx != 0) {
shape.rotateY(dx/-100f);
}
if (dy != 0) {
shape.rotateX(dy/-100f);
}
}
}
| false | true | public Scene() {
//world.setAmbientLight(ambient.getRed(), ambient.getGreen(), ambient.getBlue());
shape = loadOBJ("BMan_02", 3);
// shape.calcTextureWrapSpherical();
shape.setTexture(addTexture("BMan_02.png"));
shape.build();
world.addObject(shape);
world.getCamera().setPosition(50, -20, -5);
world.getCamera().lookAt(shape.getTransformedCenter());
Light light = new Light(world);
light.setIntensity(250, 250, 250);
light.setPosition(shape.getTransformedCenter().calcAdd(lightOffset));
}
| public Scene() {
//world.setAmbientLight(ambient.getRed(), ambient.getGreen(), ambient.getBlue());
shape = loadOBJ("BMan_02", 6);
// shape.calcTextureWrapSpherical();
shape.setTexture(addTexture("BMan_02.png"));
shape.build();
world.addObject(shape);
world.getCamera().setPosition(50, -40, -15);
world.getCamera().lookAt(shape.getTransformedCenter());
Light light = new Light(world);
light.setIntensity(250, 250, 250);
light.setPosition(shape.getTransformedCenter().calcAdd(lightOffset));
}
|
diff --git a/src/newbieprotect/Storage.java b/src/newbieprotect/Storage.java
index 60f314a..28507a1 100644
--- a/src/newbieprotect/Storage.java
+++ b/src/newbieprotect/Storage.java
@@ -1,106 +1,106 @@
package newbieprotect;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import org.bukkit.Bukkit;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import com.sk89q.worldguard.bukkit.BukkitUtil;
import com.sk89q.worldguard.bukkit.WGBukkit;
public class Storage {
private Nprotect plugin;
private Config config;
private File configfile;
public Storage(Nprotect plugin, Config config)
{
this.plugin = plugin;
this.config = config;
configfile = new File(plugin.getDataFolder(),"playerdata.yml");
}
private ConcurrentHashMap<String,Long> playerprotecttime = new ConcurrentHashMap<String,Long>();
protected void protectPlayer(String playername, long starttimestamp)
{
playerprotecttime.put(playername, starttimestamp);
}
protected void unprotectPlayer(String playername)
{
playerprotecttime.remove(playername);
}
protected boolean isPlayerProtected(String playername)
{
- if (System.currentTimeMillis() - playerprotecttime.get(playername) > config.protecttime)
+ if (playerprotecttime.containsKey(playername) && System.currentTimeMillis() - playerprotecttime.get(playername) > config.protecttime)
{
unprotectPlayer(playername);
}
Player player = Bukkit.getPlayerExact(playername);
try {
List<String> aregions = WGBukkit.getRegionManager(player.getWorld()).getApplicableRegionsIDs(BukkitUtil.toVector(player.getLocation()));
for (String region : aregions)
{
if (config.disabledegions.contains(region))
{
return false;
}
}
} catch (Exception e) {}
return playerprotecttime.containsKey(playername);
}
protected void loadTimeConfig()
{
FileConfiguration config = YamlConfiguration.loadConfiguration(configfile);
ConfigurationSection cs = config.getConfigurationSection("");
if (cs != null)
{
for (String playername : cs.getKeys(false))
{
playerprotecttime.put(playername, config.getLong(playername));
}
}
}
protected void saveTimeConfig()
{
FileConfiguration config = new YamlConfiguration();
for (String playername : playerprotecttime.keySet())
{
config.set(playername, playerprotecttime.get(playername));
}
try {
config.save(configfile);
} catch (IOException e) {}
}
private int taskid;
protected void startCheck()
{
Bukkit.getScheduler().scheduleAsyncRepeatingTask(plugin, new Runnable(){
public void run()
{
for (String playername : playerprotecttime.keySet())
{
if (System.currentTimeMillis() - playerprotecttime.get(playername) > config.protecttime)
{
unprotectPlayer(playername);
}
}
}
}, 0, 20*60);
}
protected void stopCheck()
{
Bukkit.getScheduler().cancelTask(taskid);
}
}
| true | true | protected boolean isPlayerProtected(String playername)
{
if (System.currentTimeMillis() - playerprotecttime.get(playername) > config.protecttime)
{
unprotectPlayer(playername);
}
Player player = Bukkit.getPlayerExact(playername);
try {
List<String> aregions = WGBukkit.getRegionManager(player.getWorld()).getApplicableRegionsIDs(BukkitUtil.toVector(player.getLocation()));
for (String region : aregions)
{
if (config.disabledegions.contains(region))
{
return false;
}
}
} catch (Exception e) {}
return playerprotecttime.containsKey(playername);
}
| protected boolean isPlayerProtected(String playername)
{
if (playerprotecttime.containsKey(playername) && System.currentTimeMillis() - playerprotecttime.get(playername) > config.protecttime)
{
unprotectPlayer(playername);
}
Player player = Bukkit.getPlayerExact(playername);
try {
List<String> aregions = WGBukkit.getRegionManager(player.getWorld()).getApplicableRegionsIDs(BukkitUtil.toVector(player.getLocation()));
for (String region : aregions)
{
if (config.disabledegions.contains(region))
{
return false;
}
}
} catch (Exception e) {}
return playerprotecttime.containsKey(playername);
}
|
diff --git a/GoldBankListener.java b/GoldBankListener.java
index 9cb9797..f1594c4 100644
--- a/GoldBankListener.java
+++ b/GoldBankListener.java
@@ -1,147 +1,148 @@
public class GoldBankListener extends PluginListener
{
private GoldBankData data;
private Bank bank;
private Bool bool;
private static Sign sign;
private static Server server;
public GoldBankListener()
{
data = new GoldBankData();
bank = new Bank(data);
bool = new Bool();
}
public boolean onBlockRightClick(Player player,
Block block,
Item itemInHand)
{
if(bool.isGoldBankSign(block))
{
//command flag
if(!player.canUseCommand("/goldbank"))
{
player.notify("No permission to use GoldBank!");
return true;
}
sign = bool.getSign();
if(!bool.isChest(player, player.getWorld().getBlockAt(sign.getX(), sign.getY() - 1, sign.getZ())))
{
player.notify("GoldBank broken!");
return true;
}
Chest chest = (Chest)player.getWorld().getOnlyComplexBlock(sign.getX(), sign.getY() - 1, sign.getZ());
bank.handleBlockRightClick(player, chest);
}
return false;
}
public boolean onBlockBreak(Player player, Block block)
{
if(bool.isGoldBankSign(block) || bool.isGoldBankChest(player, block))
{
//command flag
if(player.canUseCommand("/goldbankdestroy"))
{
player.notify("Destroyed GoldBank!");
return false;
}else
{
player.notify("No permission to destroy GoldBank!");
return true;
}
}else
return false;
}
public boolean onSignChange(Player player, Sign sign)
{
if(bool.isGoldBankSign(player.getWorld().getBlockAt(sign.getX(), sign.getY(), sign.getZ())))
{
if(bool.isChest(player, player.getWorld().getBlockAt(sign.getX(), sign.getY() - 1, sign.getZ())))
{
if(player.canUseCommand("/goldbankcreate"))
{
player.notify("GoldBank created!");
return false;
}else
{
player.notify("No permission to create a GoldBank");
return true;
}
}else
{
player.notify("Chest must be placed first!");
return true;
}
}else
return false;
}
public boolean onCommand(Player player, java.lang.String[] split)
{
if(split[0].equalsIgnoreCase("/goldbank"))
{
if(split[1].equalsIgnoreCase("transfer") && !split[2].equalsIgnoreCase("") && !split[3].equalsIgnoreCase("") && !split[4].equalsIgnoreCase(""))
{
if(split[3].equalsIgnoreCase("diamond"))
{
if(data.getDiamond(player.getName()) < Integer.parseInt(split[4]))
{
player.notify("Not enough Diamond! Gold: " + data.getDiamond(player.getName()));
}else
{
int amount = data.getDiamond(player.getName()) - Integer.parseInt(split[4]);
player.notify("" + amount);
data.setDiamond(split[2], Integer.parseInt(split[4]));
data.setDiamond(player.getName(), amount);
player.notify(data.getInfo(player.getName()));
}
}else if(split[3].equalsIgnoreCase("gold"))
{
if(data.getGold(player.getName()) < Integer.parseInt(split[4]))
{
player.notify("Not enough Gold! Gold: " + data.getGold(player.getName()));
}else
{
int amount = data.getGold(player.getName()) - Integer.parseInt(split[4]);
player.notify("" + amount);
data.setGold(split[2], Integer.parseInt(split[4]));
data.setGold(player.getName(), amount);
player.notify(data.getInfo(player.getName()));
}
}else if(split[3].equalsIgnoreCase("iron"))
{
if(data.getIron(player.getName()) < Integer.parseInt(split[4]))
{
player.notify("Not enough Iron! Gold: " + data.getIron(player.getName()));
}else
{
int amount = data.getIron(player.getName()) - Integer.parseInt(split[4]);
player.notify("" + amount);
data.setIron(split[2], Integer.parseInt(split[4]));
data.setIron(player.getName(), amount);
player.notify(data.getInfo(player.getName()));
}
}
}else if(split[1].equalsIgnoreCase("info"))
{
player.notify(data.getInfo(player.getName()));
}else
{
- //player.notify("Usage: /goldbank transfer <player> <diamond/gold/iron> <amount>");
+ player.notify("Usage: /goldbank transfer <player> <diamond/gold/iron> <amount>");
+ return false;
}
return true;
}
return false;
}
}
| true | true | public boolean onCommand(Player player, java.lang.String[] split)
{
if(split[0].equalsIgnoreCase("/goldbank"))
{
if(split[1].equalsIgnoreCase("transfer") && !split[2].equalsIgnoreCase("") && !split[3].equalsIgnoreCase("") && !split[4].equalsIgnoreCase(""))
{
if(split[3].equalsIgnoreCase("diamond"))
{
if(data.getDiamond(player.getName()) < Integer.parseInt(split[4]))
{
player.notify("Not enough Diamond! Gold: " + data.getDiamond(player.getName()));
}else
{
int amount = data.getDiamond(player.getName()) - Integer.parseInt(split[4]);
player.notify("" + amount);
data.setDiamond(split[2], Integer.parseInt(split[4]));
data.setDiamond(player.getName(), amount);
player.notify(data.getInfo(player.getName()));
}
}else if(split[3].equalsIgnoreCase("gold"))
{
if(data.getGold(player.getName()) < Integer.parseInt(split[4]))
{
player.notify("Not enough Gold! Gold: " + data.getGold(player.getName()));
}else
{
int amount = data.getGold(player.getName()) - Integer.parseInt(split[4]);
player.notify("" + amount);
data.setGold(split[2], Integer.parseInt(split[4]));
data.setGold(player.getName(), amount);
player.notify(data.getInfo(player.getName()));
}
}else if(split[3].equalsIgnoreCase("iron"))
{
if(data.getIron(player.getName()) < Integer.parseInt(split[4]))
{
player.notify("Not enough Iron! Gold: " + data.getIron(player.getName()));
}else
{
int amount = data.getIron(player.getName()) - Integer.parseInt(split[4]);
player.notify("" + amount);
data.setIron(split[2], Integer.parseInt(split[4]));
data.setIron(player.getName(), amount);
player.notify(data.getInfo(player.getName()));
}
}
}else if(split[1].equalsIgnoreCase("info"))
{
player.notify(data.getInfo(player.getName()));
}else
{
//player.notify("Usage: /goldbank transfer <player> <diamond/gold/iron> <amount>");
}
return true;
}
return false;
}
| public boolean onCommand(Player player, java.lang.String[] split)
{
if(split[0].equalsIgnoreCase("/goldbank"))
{
if(split[1].equalsIgnoreCase("transfer") && !split[2].equalsIgnoreCase("") && !split[3].equalsIgnoreCase("") && !split[4].equalsIgnoreCase(""))
{
if(split[3].equalsIgnoreCase("diamond"))
{
if(data.getDiamond(player.getName()) < Integer.parseInt(split[4]))
{
player.notify("Not enough Diamond! Gold: " + data.getDiamond(player.getName()));
}else
{
int amount = data.getDiamond(player.getName()) - Integer.parseInt(split[4]);
player.notify("" + amount);
data.setDiamond(split[2], Integer.parseInt(split[4]));
data.setDiamond(player.getName(), amount);
player.notify(data.getInfo(player.getName()));
}
}else if(split[3].equalsIgnoreCase("gold"))
{
if(data.getGold(player.getName()) < Integer.parseInt(split[4]))
{
player.notify("Not enough Gold! Gold: " + data.getGold(player.getName()));
}else
{
int amount = data.getGold(player.getName()) - Integer.parseInt(split[4]);
player.notify("" + amount);
data.setGold(split[2], Integer.parseInt(split[4]));
data.setGold(player.getName(), amount);
player.notify(data.getInfo(player.getName()));
}
}else if(split[3].equalsIgnoreCase("iron"))
{
if(data.getIron(player.getName()) < Integer.parseInt(split[4]))
{
player.notify("Not enough Iron! Gold: " + data.getIron(player.getName()));
}else
{
int amount = data.getIron(player.getName()) - Integer.parseInt(split[4]);
player.notify("" + amount);
data.setIron(split[2], Integer.parseInt(split[4]));
data.setIron(player.getName(), amount);
player.notify(data.getInfo(player.getName()));
}
}
}else if(split[1].equalsIgnoreCase("info"))
{
player.notify(data.getInfo(player.getName()));
}else
{
player.notify("Usage: /goldbank transfer <player> <diamond/gold/iron> <amount>");
return false;
}
return true;
}
return false;
}
|
diff --git a/api/src/main/java/org/sonar/runner/Bootstrapper.java b/api/src/main/java/org/sonar/runner/Bootstrapper.java
index 9f482bb..8e8a32c 100644
--- a/api/src/main/java/org/sonar/runner/Bootstrapper.java
+++ b/api/src/main/java/org/sonar/runner/Bootstrapper.java
@@ -1,267 +1,270 @@
/*
* Sonar Runner - API
* Copyright (C) 2011 SonarSource
* [email protected]
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
package org.sonar.runner;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Bootstrapper used to download everything from the server and create the correct classloader required to execute a Sonar analysis in isolation.
*/
class Bootstrapper {
static final String VERSION_PATH = "/api/server/version";
static final String BATCH_PATH = "/batch/";
static final String BOOTSTRAP_INDEX_PATH = "/batch_bootstrap/index";
static final int CONNECT_TIMEOUT_MILLISECONDS = 30000;
static final int READ_TIMEOUT_MILLISECONDS = 60000;
private static final Pattern CHARSET_PATTERN = Pattern.compile("(?i)\\bcharset=\\s*\"?([^\\s;\"]*)");
private static final String[] UNSUPPORTED_VERSIONS_FOR_CACHE = {"1", "2", "3.0", "3.1", "3.2", "3.3", "3.4"};
private File bootDir;
private String serverUrl;
private String productToken;
private String serverVersion;
private SonarCache cache;
/**
* @param productToken part of User-Agent request-header field - see http://tools.ietf.org/html/rfc1945#section-10.15
*/
Bootstrapper(String productToken, String serverUrl, File workDir, File cacheLocation) {
this.productToken = productToken;
this.cache = SonarCache.create().setCacheLocation(cacheLocation).build();
bootDir = new File(workDir, "batch");
bootDir.mkdirs();
if (serverUrl.endsWith("/")) {
this.serverUrl = serverUrl.substring(0, serverUrl.length() - 1);
} else {
this.serverUrl = serverUrl;
}
}
/**
* @return server url
*/
String getServerUrl() {
return serverUrl;
}
/**
* @return server version
*/
String getServerVersion() {
if (serverVersion == null) {
try {
serverVersion = remoteContent(VERSION_PATH);
} catch (ConnectException e) {
Logs.error("Sonar server '" + serverUrl + "' can not be reached");
throw new RunnerException("Fail to request server version", e);
} catch (UnknownHostException e) {
Logs.error("Sonar server '" + serverUrl + "' can not be reached");
throw new RunnerException("Fail to request server version", e);
} catch (IOException e) {
throw new RunnerException("Fail to request server version", e);
}
}
return serverVersion;
}
/**
* Download batch files from server and creates {@link BootstrapClassLoader}.
* To use this method version of Sonar should be at least 2.6.
*
* @param urls additional URLs for loading classes and resources
* @param parent parent ClassLoader
* @param unmaskedPackages only classes and resources from those packages would be available for loading from parent
*/
BootstrapClassLoader createClassLoader(URL[] urls, ClassLoader parent, String... unmaskedPackages) {
BootstrapClassLoader classLoader = new BootstrapClassLoader(parent, unmaskedPackages);
List<File> files = downloadBatchFiles();
for (URL url : urls) {
classLoader.addURL(url);
}
for (File file : files) {
try {
classLoader.addURL(file.toURI().toURL());
} catch (MalformedURLException e) {
throw new IllegalStateException("Fail to create classloader", e);
}
}
return classLoader;
}
private void remoteContentToFile(String path, File toFile) {
InputStream input = null;
FileOutputStream output = null;
String fullUrl = serverUrl + path;
if (Logs.isDebugEnabled()) {
Logs.debug("Downloading " + fullUrl + " to " + toFile.getAbsolutePath());
}
// Don't log for old versions without cache to not pollute logs
else if (!isUnsupportedVersionForCache(getServerVersion())) {
Logs.info("Downloading " + path.substring(path.lastIndexOf("/") + 1));
}
try {
HttpURLConnection connection = newHttpConnection(new URL(fullUrl));
output = new FileOutputStream(toFile, false);
input = connection.getInputStream();
IOUtils.copyLarge(input, output);
} catch (IOException e) {
IOUtils.closeQuietly(output);
FileUtils.deleteQuietly(toFile);
throw new IllegalStateException("Fail to download the file: " + fullUrl, e);
} finally {
IOUtils.closeQuietly(input);
IOUtils.closeQuietly(output);
}
}
String remoteContent(String path) throws IOException {
String fullUrl = serverUrl + path;
HttpURLConnection conn = newHttpConnection(new URL(fullUrl));
String charset = getCharsetFromContentType(conn.getContentType());
if (charset == null || "".equals(charset)) {
charset = "UTF-8";
}
Reader reader = new InputStreamReader(conn.getInputStream(), charset);
try {
int statusCode = conn.getResponseCode();
if (statusCode != HttpURLConnection.HTTP_OK) {
throw new IOException("Status returned by url : '" + fullUrl + "' is invalid : " + statusCode);
}
return IOUtils.toString(reader);
} finally {
IOUtils.closeQuietly(reader);
conn.disconnect();
}
}
/**
* By convention, the product tokens are listed in order of their significance for identifying the application.
*/
String getUserAgent() {
return "sonar-bootstrapper/" + Version.getVersion() + " " + productToken;
}
HttpURLConnection newHttpConnection(URL url) throws IOException {
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(CONNECT_TIMEOUT_MILLISECONDS);
connection.setReadTimeout(READ_TIMEOUT_MILLISECONDS);
connection.setInstanceFollowRedirects(true);
connection.setRequestMethod("GET");
connection.setRequestProperty("User-Agent", getUserAgent());
return connection;
}
private List<File> downloadBatchFiles() {
try {
List<File> files = new ArrayList<File>();
if (isUnsupportedVersionForCache(getServerVersion())) {
getBootstrapFilesFromOldURL(files);
}
else {
getBootstrapFiles(files);
}
return files;
} catch (Exception e) {
throw new IllegalStateException("Fail to download libraries from server", e);
}
}
private void getBootstrapFilesFromOldURL(List<File> files) throws IOException {
String libs = remoteContent(BATCH_PATH);
for (String lib : libs.split(",")) {
File file = new File(bootDir, lib);
remoteContentToFile(BATCH_PATH + lib, file);
files.add(file);
}
}
private void getBootstrapFiles(List<File> files) throws IOException {
String libs = remoteContent(BOOTSTRAP_INDEX_PATH);
String[] lines = libs.split("[\r\n]+");
for (String line : lines) {
line = line.trim();
if ("".equals(line)) {
continue;
}
String[] libAndMd5 = line.split("\\|");
String libName = libAndMd5[0];
String remoteMd5 = libAndMd5.length > 0 ? libAndMd5[1] : null;
- Logs.debug("Looking if library " + libName + " with md5 " + remoteMd5 + " is already in cache");
- File libInCache = cache.getFileFromCache(libName, remoteMd5);
+ File libInCache = null;
+ if (remoteMd5 != null && !"".equals(remoteMd5)) {
+ Logs.debug("Looking if library " + libName + " with md5 " + remoteMd5 + " is already in cache");
+ libInCache = cache.getFileFromCache(libName, remoteMd5);
+ }
if (libInCache != null) {
Logs.debug("File is already cached at location " + libInCache.getAbsolutePath());
}
else {
Logs.debug("File is not cached");
File tmpLocation = cache.getTemporaryFile();
remoteContentToFile(BATCH_PATH + libName, tmpLocation);
Logs.debug("Trying to cache file");
String md5 = cache.cacheFile(tmpLocation, libName);
libInCache = cache.getFileFromCache(libName, md5);
if (!md5.equals(remoteMd5)) {
Logs.warn("INVALID CHECKSUM: File " + libInCache.getAbsolutePath() + " was expected to have checksum " + remoteMd5 + " but was cached with checksum " + md5);
}
Logs.debug("File cached at location " + libInCache.getAbsolutePath());
}
files.add(libInCache);
}
}
static boolean isUnsupportedVersionForCache(String version) {
return VersionUtils.isUnsupportedVersion(version, UNSUPPORTED_VERSIONS_FOR_CACHE);
}
/**
* Parse out a charset from a content type header.
*
* @param contentType e.g. "text/html; charset=EUC-JP"
* @return "EUC-JP", or null if not found. Charset is trimmed and uppercased.
*/
static String getCharsetFromContentType(String contentType) {
if (contentType == null) {
return null;
}
Matcher m = CHARSET_PATTERN.matcher(contentType);
if (m.find()) {
return m.group(1).trim().toUpperCase();
}
return null;
}
}
| true | true | private void getBootstrapFiles(List<File> files) throws IOException {
String libs = remoteContent(BOOTSTRAP_INDEX_PATH);
String[] lines = libs.split("[\r\n]+");
for (String line : lines) {
line = line.trim();
if ("".equals(line)) {
continue;
}
String[] libAndMd5 = line.split("\\|");
String libName = libAndMd5[0];
String remoteMd5 = libAndMd5.length > 0 ? libAndMd5[1] : null;
Logs.debug("Looking if library " + libName + " with md5 " + remoteMd5 + " is already in cache");
File libInCache = cache.getFileFromCache(libName, remoteMd5);
if (libInCache != null) {
Logs.debug("File is already cached at location " + libInCache.getAbsolutePath());
}
else {
Logs.debug("File is not cached");
File tmpLocation = cache.getTemporaryFile();
remoteContentToFile(BATCH_PATH + libName, tmpLocation);
Logs.debug("Trying to cache file");
String md5 = cache.cacheFile(tmpLocation, libName);
libInCache = cache.getFileFromCache(libName, md5);
if (!md5.equals(remoteMd5)) {
Logs.warn("INVALID CHECKSUM: File " + libInCache.getAbsolutePath() + " was expected to have checksum " + remoteMd5 + " but was cached with checksum " + md5);
}
Logs.debug("File cached at location " + libInCache.getAbsolutePath());
}
files.add(libInCache);
}
}
| private void getBootstrapFiles(List<File> files) throws IOException {
String libs = remoteContent(BOOTSTRAP_INDEX_PATH);
String[] lines = libs.split("[\r\n]+");
for (String line : lines) {
line = line.trim();
if ("".equals(line)) {
continue;
}
String[] libAndMd5 = line.split("\\|");
String libName = libAndMd5[0];
String remoteMd5 = libAndMd5.length > 0 ? libAndMd5[1] : null;
File libInCache = null;
if (remoteMd5 != null && !"".equals(remoteMd5)) {
Logs.debug("Looking if library " + libName + " with md5 " + remoteMd5 + " is already in cache");
libInCache = cache.getFileFromCache(libName, remoteMd5);
}
if (libInCache != null) {
Logs.debug("File is already cached at location " + libInCache.getAbsolutePath());
}
else {
Logs.debug("File is not cached");
File tmpLocation = cache.getTemporaryFile();
remoteContentToFile(BATCH_PATH + libName, tmpLocation);
Logs.debug("Trying to cache file");
String md5 = cache.cacheFile(tmpLocation, libName);
libInCache = cache.getFileFromCache(libName, md5);
if (!md5.equals(remoteMd5)) {
Logs.warn("INVALID CHECKSUM: File " + libInCache.getAbsolutePath() + " was expected to have checksum " + remoteMd5 + " but was cached with checksum " + md5);
}
Logs.debug("File cached at location " + libInCache.getAbsolutePath());
}
files.add(libInCache);
}
}
|
diff --git a/src/leola/vm/asm/Scope.java b/src/leola/vm/asm/Scope.java
index 2b38a0f..62c3ac4 100644
--- a/src/leola/vm/asm/Scope.java
+++ b/src/leola/vm/asm/Scope.java
@@ -1,468 +1,468 @@
/*
Leola Programming Language
Author: Tony Sparks
See license.txt
*/
package leola.vm.asm;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import leola.vm.ClassDefinition;
import leola.vm.ClassDefinitions;
import leola.vm.NamespaceDefinitions;
import leola.vm.lib.LeolaMethod;
import leola.vm.types.LeoMap;
import leola.vm.types.LeoNamespace;
import leola.vm.types.LeoNativeFunction;
import leola.vm.types.LeoObject;
import leola.vm.types.LeoString;
import leola.vm.util.ArrayUtil;
import leola.vm.util.ClassUtil;
/**
* A {@link Scope} represents a lexical scope of variables
*
* @author Tony
*
*/
public class Scope {
/**
* Scope type
* @author Tony
*
*/
public static enum ScopeType {
LOCAL_SCOPE,
OBJECT_SCOPE,
GLOBAL_SCOPE
;
}
private static final AtomicLong id = new AtomicLong();
private String sid;
private Symbols symbols;
private Constants constants;
private Locals locals;
private Outers outers;
private Scope parent;
private ClassDefinitions classDefinitions;
private NamespaceDefinitions namespaceDefinitions;
private ScopeType scopeType;
private int maxstacksize;
private LeoMap values;
private Scope(Scope scope) {
this.symbols = scope.symbols;
this.constants = scope.constants;
this.parent = scope.parent;
this.scopeType = scope.scopeType;
this.classDefinitions = scope.classDefinitions;
this.namespaceDefinitions = scope.namespaceDefinitions;
this.outers = scope.outers;
this.locals = scope.locals.clone();
this.values = (LeoMap)scope.values.clone();
this.sid = "C" + scope.sid;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return this.sid + " parent: " + ((this.getParent()!=null)?this.getParent():"-");
}
public Scope() {
this(null, null);
}
/**
* @param symbols
* @param parent
*/
public Scope(Symbols symbols, Scope parent) {
this(symbols, parent, ScopeType.LOCAL_SCOPE);
}
/**
* @param symbols
* @param parent
* @param scopeType
*/
public Scope(Symbols symbols, Scope parent, ScopeType scopeType) {
this.symbols = symbols;
this.parent = parent;
this.scopeType = scopeType;
this.maxstacksize = 2; /* always leave room for binary operations */
this.sid = id.incrementAndGet() + "";
}
/**
* @return the symbols
*/
public Symbols getSymbols() {
return symbols;
}
/**
* @return the maxstacksize
*/
public int getMaxstacksize() {
return maxstacksize;
}
/**
* Increments the allocated stack size by delta.
* @param delta
*/
public void incrementMaxstacksize(int delta) {
this.maxstacksize += delta;
}
/**
* Clears the compiler data
* TODO: Attempt to remove this compiler data into either
* the {@link Asm} class or another {@link Symbols} stack element
*/
public void compiled() {
this.constants = null;
this.outers = null;
this.locals = null;
}
/**
* @param parent the parent to set
*/
public void setParent(Scope parent) {
this.parent = parent;
}
public void onClone(Scope newParent) {
setParent(newParent);
}
/**
* @return the scopeType
*/
public ScopeType getScopeType() {
return scopeType;
}
/**
* @param scopeType the scopeType to set
*/
public void setScopeType(ScopeType scopeType) {
this.scopeType = scopeType;
}
/**
* @return true if there are {@link ClassDefinition}s in this {@link Scope}
*/
public boolean hasClassDefinitions() {
return this.classDefinitions != null && this.classDefinitions.hasDefinitions();
}
/**
* @return the classDefinitions
*/
public ClassDefinitions getClassDefinitions() {
if ( this.classDefinitions == null ) {
this.classDefinitions = new ClassDefinitions();
}
return classDefinitions;
}
public boolean hasNamespaceDefinitions() {
return this.namespaceDefinitions != null && this.namespaceDefinitions.hasDefinitions();
}
/**
* @return the namespaceDefinitions
*/
public NamespaceDefinitions getNamespaceDefinitions() {
if(this.namespaceDefinitions == null) {
this.namespaceDefinitions = new NamespaceDefinitions();
}
return namespaceDefinitions;
}
/**
* @return the constants
*/
public Constants getConstants() {
if ( constants == null ) {
constants = new Constants();
}
return constants;
}
/**
* @return true if there are constants in this scope
*/
public boolean hasConstants() {
return constants != null && constants.getNumberOfConstants() > 0;
}
/**
* @return the globals
*/
public Outers getOuters() {
if ( outers == null ) {
outers = new Outers();
}
return outers;
}
/**
* @return true if there are outers in this scope
*/
public boolean hasOuters() {
return outers != null && outers.getNumberOfOuters() > 0;
}
/**
* @return the locals
*/
public Locals getLocals() {
if ( locals == null ) {
locals = new Locals();
}
return locals;
}
/**
* @return true if there are locals for this scope
*/
public boolean hasLocals() {
return locals != null && locals.getNumberOfLocals() > 0;
}
/**
* @return the underlying raw values of the {@link Scope}
*/
public LeoObject[] getScopedValues() {
return (this.values != null) ? this.values.vals().toArray() : ArrayUtil.EMPTY_LEOOBJECTS;
}
/**
* Recursively attempts to retrieve the value associated with the reference. If it
* isn't found in this scope, it will ask its parent scope.
* @param reference
* @return
*/
public LeoObject getObject(LeoString reference) {
LeoObject value = (this.values != null) ? this.values.getWithJNull(reference) : null;
if ( value == null && parent != null) {
value = parent.getObject(reference);
}
return value;
}
public LeoObject getObjectNoGlobal(LeoString reference) {
LeoObject value = (this.values != null) ? this.values.getWithJNull(reference) : null;
if ( value == null && parent != null && !parent.isGlobalScope()) {
value = parent.getObjectNoGlobal(reference);
}
return value;
}
/**
* Retrieves a {@link LeoNamespace}
* @param reference
* @return
*/
public LeoNamespace getNamespace(LeoString reference) {
// LeoObject value = (this.values != null) ? this.values.getWithJNull(reference) : null;
// if ( value == null && parent != null ) {
// value = parent.getNamespace(reference);
// }
// else if ( (value != null && !value.isNamespace()) && parent != null) {
// value = parent.getNamespace(reference);
// }
//
// return value!=null ? (LeoNamespace)value : null;
LeoNamespace value = (hasNamespaceDefinitions()) ? this.namespaceDefinitions.getNamespace(reference.getString()) : null;
if(value == null) {
value = parent.getNamespace(reference);
}
return value;
}
/**
* Recursively attempts to retrieve the value associated with the reference. If it
* isn't found in this scope, it will ask its parent scope.
* @see Scope#getObject(LeoString)
* @param reference
* @return
*/
public LeoObject getObject(String reference){
return getObject(LeoString.valueOf(reference));
}
public LeoObject getObjectNoGlobal(String reference) {
return getObjectNoGlobal(LeoString.valueOf(reference));
}
/**
* Stores an object in this scope and only this scope. This does
* not traverse the parent scopes to see if a value is already
* held.
*
* @param reference
* @param value
* @return the previously held value, if any
*/
public LeoObject putObject(LeoString reference, LeoObject value) {
if(this.values==null) {
this.values = new LeoMap();
}
return this.values.put(reference, value);
}
/**
* Stores an object in this scope, it first checks to see if any parent
* values contain the supplied reference, if it does it will override the existing
* value. This is to account for class data members.
*
* @param reference
* @param value
* @return the previously held value, if any
*/
public LeoObject storeObject(LeoString reference, LeoObject newValue) {
- Scope current = this;
- while (current != null) {
+ Scope current = this;
+ while (current != null && current.scopeType.equals(ScopeType.LOCAL_SCOPE)) {
// if the value is the the current scope, break out
if (current.values != null && current.values.getWithJNull(reference) != null ) {
break;
}
// else check the parent
if(current.parent != null && !current.parent.isGlobalScope()) {
current = current.parent;
}
else {
current = this;
break;
}
}
return current.putObject(reference, newValue);
}
public LeoObject storeObject(String reference, LeoObject value) {
return storeObject(LeoString.valueOf(reference), value);
}
/**
* Removes an object from this {@link Scope}
*
* @param reference
* @return
*/
public LeoObject removeObject(LeoString reference) {
return (this.values!=null) ? this.values.remove(reference) : null;
}
public LeoObject removeObject(String reference) {
return removeObject(LeoString.valueOf(reference));
}
/**
* @return the number of {@link LeoObject}s in this {@link Scope}
*/
public int getNumberOfObjects() {
return (this.values != null) ? this.values.size() : 0;
}
public LeoMap getRawObjects() {
return this.values;
}
/**
* @return true if this scope is the global scope
*/
public boolean isGlobalScope() {
return this == this.symbols.getGlobalScope();
}
/**
* @return the parent
*/
public Scope getParent() {
return parent;
}
/*
* (non-Javadoc)
* @see java.lang.Object#clone()
*/
public Scope clone() {
Scope clone = new Scope(this);
return clone;
}
/**
* Loads the objects methods into the supplied {@link Scope}
* @param scope
* @param jObject
*/
public void loadNatives(Object jObject) {
Class<?> nClass = jObject.getClass();
List<Method> methods = ClassUtil.getAllDeclaredMethods(nClass);
for(Method m: methods) {
LeoNativeFunction func = new LeoNativeFunction(nClass, jObject, m.getName(), m.getParameterTypes().length);
if(m.isAnnotationPresent(LeolaMethod.class)) {
storeObject(m.getAnnotation(LeolaMethod.class).alias(), func);
}
else {
storeObject(m.getName(), func);
}
}
}
/**
* Loads the static methods of the native class into the supplied {@link Scope}
*
* @param scope
* @param aClass
*/
public void loadStatics(Class<?> aClass) {
List<Method> methods = ClassUtil.getAllDeclaredMethods(aClass);
for(Method m: methods) {
LeoNativeFunction func = new LeoNativeFunction(aClass, null, m.getName(), m.getParameterTypes().length);
boolean isStatic = (m.getModifiers() & Modifier.STATIC) != 0;
if ( isStatic ) {
if(m.isAnnotationPresent(LeolaMethod.class)) {
storeObject(m.getAnnotation(LeolaMethod.class).alias(), func);
}
else {
storeObject(m.getName(), func);
}
}
}
}
}
| true | true | public LeoObject storeObject(LeoString reference, LeoObject newValue) {
Scope current = this;
while (current != null) {
// if the value is the the current scope, break out
if (current.values != null && current.values.getWithJNull(reference) != null ) {
break;
}
// else check the parent
if(current.parent != null && !current.parent.isGlobalScope()) {
current = current.parent;
}
else {
current = this;
break;
}
}
return current.putObject(reference, newValue);
}
| public LeoObject storeObject(LeoString reference, LeoObject newValue) {
Scope current = this;
while (current != null && current.scopeType.equals(ScopeType.LOCAL_SCOPE)) {
// if the value is the the current scope, break out
if (current.values != null && current.values.getWithJNull(reference) != null ) {
break;
}
// else check the parent
if(current.parent != null && !current.parent.isGlobalScope()) {
current = current.parent;
}
else {
current = this;
break;
}
}
return current.putObject(reference, newValue);
}
|
diff --git a/Project/src/be/uclouvain/sinf1225/gourmet/DishListView.java b/Project/src/be/uclouvain/sinf1225/gourmet/DishListView.java
index 464fe6b..b1aee03 100644
--- a/Project/src/be/uclouvain/sinf1225/gourmet/DishListView.java
+++ b/Project/src/be/uclouvain/sinf1225/gourmet/DishListView.java
@@ -1,97 +1,97 @@
package be.uclouvain.sinf1225.gourmet;
import java.util.List;
import be.uclouvain.sinf1225.gourmet.models.City;
import be.uclouvain.sinf1225.gourmet.models.Dish;
import be.uclouvain.sinf1225.gourmet.models.Restaurant;
import be.uclouvain.sinf1225.gourmet.utils.GourmetUtils;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
public class DishListView extends Activity // implements GourmetLocationReceiver
{
private Restaurant restaurant = null;
public boolean onCreateOptionsMenu(Menu menu)
{
GourmetUtils.createMenu(menu, this, R.id.search);
return true;
}
public boolean onOptionsItemSelected(MenuItem item)
{
return GourmetUtils.onMenuItemSelected(item, this);
}
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dish_list);
// Initialisation des services de localisation
// locationListener = new GourmetLocationListener(this,this).init();
// Récupération du restaurant sur lequel on a cliqué et les plats qui lui appartiennent
restaurant = Restaurant.getRestaurant(getIntent().getExtras().getInt("restoId"));
List<Dish> dishes = Dish.getDishInRestaurant(restaurant);
// On recupere la vue "liste"
ListView DishList = (ListView) this.findViewById(R.id.DishListView);
// On cree un adapter qui va mettre dans la liste les donnes adequates des villes
DishAdapter adapter = new DishAdapter(this, R.layout.dish_list_row, dishes);
DishList.setAdapter(adapter);
DishList.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
final ListView DishList = (ListView) findViewById(R.id.DishListView);
final DishAdapter adapter = (DishAdapter) DishList.getAdapter();
Dish dish = adapter.getItem(position);
Intent intent = new Intent(DishListView.this, DishView.class);
- intent.putExtra("dishId", dish.getId());
+ intent.putExtra("dishId", dish.getDishId());
startActivity(intent);
}
});
final Button button = (Button) findViewById(R.id.DishListRetour);
button.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View arg0)
{
finish();
}
});
}
@Override
public void onPause()
{
super.onPause();
}
@Override
public void onStop()
{
super.onStop();
}
@Override
public void onResume()
{
super.onResume();
}
}
| true | true | public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dish_list);
// Initialisation des services de localisation
// locationListener = new GourmetLocationListener(this,this).init();
// Récupération du restaurant sur lequel on a cliqué et les plats qui lui appartiennent
restaurant = Restaurant.getRestaurant(getIntent().getExtras().getInt("restoId"));
List<Dish> dishes = Dish.getDishInRestaurant(restaurant);
// On recupere la vue "liste"
ListView DishList = (ListView) this.findViewById(R.id.DishListView);
// On cree un adapter qui va mettre dans la liste les donnes adequates des villes
DishAdapter adapter = new DishAdapter(this, R.layout.dish_list_row, dishes);
DishList.setAdapter(adapter);
DishList.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
final ListView DishList = (ListView) findViewById(R.id.DishListView);
final DishAdapter adapter = (DishAdapter) DishList.getAdapter();
Dish dish = adapter.getItem(position);
Intent intent = new Intent(DishListView.this, DishView.class);
intent.putExtra("dishId", dish.getId());
startActivity(intent);
}
});
final Button button = (Button) findViewById(R.id.DishListRetour);
button.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View arg0)
{
finish();
}
});
}
| public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dish_list);
// Initialisation des services de localisation
// locationListener = new GourmetLocationListener(this,this).init();
// Récupération du restaurant sur lequel on a cliqué et les plats qui lui appartiennent
restaurant = Restaurant.getRestaurant(getIntent().getExtras().getInt("restoId"));
List<Dish> dishes = Dish.getDishInRestaurant(restaurant);
// On recupere la vue "liste"
ListView DishList = (ListView) this.findViewById(R.id.DishListView);
// On cree un adapter qui va mettre dans la liste les donnes adequates des villes
DishAdapter adapter = new DishAdapter(this, R.layout.dish_list_row, dishes);
DishList.setAdapter(adapter);
DishList.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
final ListView DishList = (ListView) findViewById(R.id.DishListView);
final DishAdapter adapter = (DishAdapter) DishList.getAdapter();
Dish dish = adapter.getItem(position);
Intent intent = new Intent(DishListView.this, DishView.class);
intent.putExtra("dishId", dish.getDishId());
startActivity(intent);
}
});
final Button button = (Button) findViewById(R.id.DishListRetour);
button.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View arg0)
{
finish();
}
});
}
|
diff --git a/core-api/src/main/java/no/schibstedsok/searchportal/mode/command/NewsSearchCommand.java b/core-api/src/main/java/no/schibstedsok/searchportal/mode/command/NewsSearchCommand.java
index ed07d76cb..85dcefdaf 100644
--- a/core-api/src/main/java/no/schibstedsok/searchportal/mode/command/NewsSearchCommand.java
+++ b/core-api/src/main/java/no/schibstedsok/searchportal/mode/command/NewsSearchCommand.java
@@ -1,145 +1,147 @@
// Copyright (2006) Schibsted Søk AS
/*
* NewsSearchCommand.java
*
* Created on March 7, 2006, 5:31 PM
*
*/
package no.schibstedsok.searchportal.mode.command;
import java.util.Map;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
import no.schibstedsok.searchportal.query.LeafClause;
import no.schibstedsok.searchportal.query.Visitor;
import no.schibstedsok.searchportal.query.XorClause;
import no.schibstedsok.searchportal.query.token.TokenPredicate;
/**
*
* @author magnuse
* @version $Id$
*/
public class NewsSearchCommand extends FastSearchCommand {
// Filter used to get all articles.
private static final String FAST_SIZE_HACK = " +size:>0";
/** Creates a new instance of NewsSearchCommand
*
* @param cxt Search command context.
* @param parameters Search command parameters.
*/
public NewsSearchCommand(final Context cxt, final Map parameters) {
super(cxt, parameters);
}
private StringBuilder filterBuilder = null;
/**
*
* @param clause The clause to examine.
*/
protected void visitXorClause(final Visitor visitor, final XorClause clause) {
switch(clause.getHint()){
case PHRASE_ON_LEFT:
// Web searches should use phrases over separate words.
clause.getFirstClause().accept(visitor);
break;
default:
// All other high level clauses are ignored.
clause.getSecondClause().accept(visitor);
break;
}
}
/**
* LeafClause
*
* A leaf clause with a site field does not add anything to the query. Also
* if the query just contains the prefix do not output anything.
*
*/
protected void visitImpl(final LeafClause clause) {
if (! containsJustThePrefix() ) {
super.visitImpl(clause);
}
}
protected String getAdditionalFilter() {
synchronized (this) {
if (filterBuilder == null) {
filterBuilder = new StringBuilder(super.getAdditionalFilter());
// Add filter to retrieve all documents.
if (containsJustThePrefix() || getTransformedQuery().equals("")) {
filterBuilder.append(FAST_SIZE_HACK);
}
GregorianCalendar calendar = new java.util.GregorianCalendar();
calendar.add( java.util.Calendar.MONTH, -24 );
final SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String newsdate = formatter.format(calendar.getTime());
if (!getSearchConfiguration().isIgnoreNavigation()) {
final String contentSource = getParameter("contentsource");
final String newsCountry = getParameter("newscountry");
final String newsSource = getParameter("newssource");
// general rule is to display news fresher than 2 years, but with exceptions for:
// "norske papiraviser" -> display for all years
// certain newssources (as listed below) -> display for all years
if (!contentSource.equals("Mediearkivet")) {
// AAhhrghh. Need to provide backwards compatibility.
// People are linking us using contentsource="Norske nyheter"
if (contentSource != null && !contentSource.equals("")) {
if (contentSource.equals("Norske nyheter")) {
filterBuilder.append(" AND newscountry:Norge");
} else {
filterBuilder.append(" AND contentsource:\""+ contentSource + "\"");
}
} else {
if (newsCountry != null && !newsCountry.equals(""))
filterBuilder.append(" AND newscountry:\""+ newsCountry + "\"");
+ else // for newscount navigator
+ filterBuilder.append(" AND newscountry:Norge");
}
filterBuilder.append(" ANDNOT meta.collection:mano");
filterBuilder.append(" AND (docdatetime:>" + newsdate);
filterBuilder.append(" OR newssource:Digi.no");
filterBuilder.append(" OR newssource:DinSide");
filterBuilder.append(" OR newssource:ITavisen");
filterBuilder.append(" OR newssource:iMarkedet");
filterBuilder.append(" OR newssource:Propaganda )");
// PAPERNEWS:
} else {
filterBuilder.append(" AND contentsource:" + contentSource);
}
} else {
filterBuilder.append(" AND (docdatetime:>" + newsdate);
filterBuilder.append(" OR newssource:Digi.no");
filterBuilder.append(" OR newssource:DinSide");
filterBuilder.append(" OR newssource:ITavisen");
filterBuilder.append(" OR newssource:iMarkedet");
filterBuilder.append(" OR newssource:Propaganda ");
filterBuilder.append(" OR meta.collection:mano )");
}
}
}
return filterBuilder.toString();
}
private boolean containsJustThePrefix() {
final LeafClause firstLeaf = context.getQuery().getFirstLeafClause();
return context.getQuery().getRootClause() == firstLeaf
&& (firstLeaf.getKnownPredicates().contains(TokenPredicate.NEWS_MAGIC)
|| firstLeaf.getPossiblePredicates().contains(TokenPredicate.NEWS_MAGIC));
}
}
| true | true | protected String getAdditionalFilter() {
synchronized (this) {
if (filterBuilder == null) {
filterBuilder = new StringBuilder(super.getAdditionalFilter());
// Add filter to retrieve all documents.
if (containsJustThePrefix() || getTransformedQuery().equals("")) {
filterBuilder.append(FAST_SIZE_HACK);
}
GregorianCalendar calendar = new java.util.GregorianCalendar();
calendar.add( java.util.Calendar.MONTH, -24 );
final SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String newsdate = formatter.format(calendar.getTime());
if (!getSearchConfiguration().isIgnoreNavigation()) {
final String contentSource = getParameter("contentsource");
final String newsCountry = getParameter("newscountry");
final String newsSource = getParameter("newssource");
// general rule is to display news fresher than 2 years, but with exceptions for:
// "norske papiraviser" -> display for all years
// certain newssources (as listed below) -> display for all years
if (!contentSource.equals("Mediearkivet")) {
// AAhhrghh. Need to provide backwards compatibility.
// People are linking us using contentsource="Norske nyheter"
if (contentSource != null && !contentSource.equals("")) {
if (contentSource.equals("Norske nyheter")) {
filterBuilder.append(" AND newscountry:Norge");
} else {
filterBuilder.append(" AND contentsource:\""+ contentSource + "\"");
}
} else {
if (newsCountry != null && !newsCountry.equals(""))
filterBuilder.append(" AND newscountry:\""+ newsCountry + "\"");
}
filterBuilder.append(" ANDNOT meta.collection:mano");
filterBuilder.append(" AND (docdatetime:>" + newsdate);
filterBuilder.append(" OR newssource:Digi.no");
filterBuilder.append(" OR newssource:DinSide");
filterBuilder.append(" OR newssource:ITavisen");
filterBuilder.append(" OR newssource:iMarkedet");
filterBuilder.append(" OR newssource:Propaganda )");
// PAPERNEWS:
} else {
filterBuilder.append(" AND contentsource:" + contentSource);
}
} else {
filterBuilder.append(" AND (docdatetime:>" + newsdate);
filterBuilder.append(" OR newssource:Digi.no");
filterBuilder.append(" OR newssource:DinSide");
filterBuilder.append(" OR newssource:ITavisen");
filterBuilder.append(" OR newssource:iMarkedet");
filterBuilder.append(" OR newssource:Propaganda ");
filterBuilder.append(" OR meta.collection:mano )");
}
}
}
return filterBuilder.toString();
}
| protected String getAdditionalFilter() {
synchronized (this) {
if (filterBuilder == null) {
filterBuilder = new StringBuilder(super.getAdditionalFilter());
// Add filter to retrieve all documents.
if (containsJustThePrefix() || getTransformedQuery().equals("")) {
filterBuilder.append(FAST_SIZE_HACK);
}
GregorianCalendar calendar = new java.util.GregorianCalendar();
calendar.add( java.util.Calendar.MONTH, -24 );
final SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String newsdate = formatter.format(calendar.getTime());
if (!getSearchConfiguration().isIgnoreNavigation()) {
final String contentSource = getParameter("contentsource");
final String newsCountry = getParameter("newscountry");
final String newsSource = getParameter("newssource");
// general rule is to display news fresher than 2 years, but with exceptions for:
// "norske papiraviser" -> display for all years
// certain newssources (as listed below) -> display for all years
if (!contentSource.equals("Mediearkivet")) {
// AAhhrghh. Need to provide backwards compatibility.
// People are linking us using contentsource="Norske nyheter"
if (contentSource != null && !contentSource.equals("")) {
if (contentSource.equals("Norske nyheter")) {
filterBuilder.append(" AND newscountry:Norge");
} else {
filterBuilder.append(" AND contentsource:\""+ contentSource + "\"");
}
} else {
if (newsCountry != null && !newsCountry.equals(""))
filterBuilder.append(" AND newscountry:\""+ newsCountry + "\"");
else // for newscount navigator
filterBuilder.append(" AND newscountry:Norge");
}
filterBuilder.append(" ANDNOT meta.collection:mano");
filterBuilder.append(" AND (docdatetime:>" + newsdate);
filterBuilder.append(" OR newssource:Digi.no");
filterBuilder.append(" OR newssource:DinSide");
filterBuilder.append(" OR newssource:ITavisen");
filterBuilder.append(" OR newssource:iMarkedet");
filterBuilder.append(" OR newssource:Propaganda )");
// PAPERNEWS:
} else {
filterBuilder.append(" AND contentsource:" + contentSource);
}
} else {
filterBuilder.append(" AND (docdatetime:>" + newsdate);
filterBuilder.append(" OR newssource:Digi.no");
filterBuilder.append(" OR newssource:DinSide");
filterBuilder.append(" OR newssource:ITavisen");
filterBuilder.append(" OR newssource:iMarkedet");
filterBuilder.append(" OR newssource:Propaganda ");
filterBuilder.append(" OR meta.collection:mano )");
}
}
}
return filterBuilder.toString();
}
|
diff --git a/src/org/bouncycastle/mail/smime/SMIMEUtil.java b/src/org/bouncycastle/mail/smime/SMIMEUtil.java
index 2029aa3a..31c9f7f5 100644
--- a/src/org/bouncycastle/mail/smime/SMIMEUtil.java
+++ b/src/org/bouncycastle/mail/smime/SMIMEUtil.java
@@ -1,310 +1,310 @@
package org.bouncycastle.mail.smime;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.cert.X509Certificate;
import java.security.cert.CertificateParsingException;
import java.util.Enumeration;
import javax.mail.MessagingException;
import javax.mail.Part;
import javax.mail.internet.MimeBodyPart;
import org.bouncycastle.asn1.cms.IssuerAndSerialNumber;
import org.bouncycastle.cms.CMSTypedStream;
import org.bouncycastle.jce.PrincipalUtil;
import org.bouncycastle.mail.smime.util.CRLFOutputStream;
import org.bouncycastle.mail.smime.util.FileBackedMimeBodyPart;
public class SMIMEUtil
{
private static final int BUF_SIZE = 4096;
static boolean isCanonicalisationRequired(
Part bodyPart,
String defaultContentTransferEncoding)
throws MessagingException
{
if (bodyPart instanceof MimeBodyPart)
{
MimeBodyPart mimePart = (MimeBodyPart)bodyPart;
String[] cte = mimePart.getHeader("Content-Transfer-Encoding");
String contentTransferEncoding;
if (cte == null)
{
contentTransferEncoding = defaultContentTransferEncoding;
}
else
{
contentTransferEncoding = cte[0];
}
return !contentTransferEncoding.equalsIgnoreCase("binary");
}
else
{
return !defaultContentTransferEncoding.equalsIgnoreCase("binary");
}
}
private static class LineOutputStream extends FilterOutputStream
{
private static byte newline[];
public LineOutputStream(OutputStream outputstream)
{
super(outputstream);
}
public void writeln(String s)
throws MessagingException
{
try
{
byte abyte0[] = getBytes(s);
super.out.write(abyte0);
super.out.write(newline);
return;
}
catch(Exception exception)
{
throw new MessagingException("IOException", exception);
}
}
public void writeln()
throws MessagingException
{
try
{
super.out.write(newline);
return;
}
catch(Exception exception)
{
throw new MessagingException("IOException", exception);
}
}
static
{
newline = new byte[2];
newline[0] = 13;
newline[1] = 10;
}
private static byte[] getBytes(String s)
{
char ac[] = s.toCharArray();
int i = ac.length;
byte abyte0[] = new byte[i];
int j = 0;
while (j < i)
{
abyte0[j] = (byte)ac[j++];
}
return abyte0;
}
}
- static void outputBodyPart(
+ static void outputBodyPart(
OutputStream out,
Part bodyPart,
String defaultContentTransferEncoding)
throws MessagingException, IOException
{
if (bodyPart instanceof MimeBodyPart)
{
MimeBodyPart mimePart = (MimeBodyPart)bodyPart;
String[] cte = mimePart.getHeader("Content-Transfer-Encoding");
String contentTransferEncoding;
if (cte == null)
{
contentTransferEncoding = defaultContentTransferEncoding;
}
else
{
contentTransferEncoding = cte[0];
}
if (!contentTransferEncoding.equalsIgnoreCase("base64")
&& !contentTransferEncoding.equalsIgnoreCase("quoted-printable"))
{
if (!contentTransferEncoding.equalsIgnoreCase("binary"))
{
out = new CRLFOutputStream(out);
}
bodyPart.writeTo(out);
out.flush();
return;
}
//
// Special handling for Base64 or quoted-printable encoded
// body part - this is to get around JavaMail's habit of
// decoding and then re-encoding base64 data...
//
//
// Write headers
//
LineOutputStream outLine = new LineOutputStream(out);
for (Enumeration e = mimePart.getAllHeaderLines(); e.hasMoreElements();)
{
outLine.writeln((String)e.nextElement());
}
outLine.writeln();
outLine.flush();
//
// Write raw content, performing canonicalization
//
InputStream in = mimePart.getRawInputStream();
CRLFOutputStream outCRLF = new CRLFOutputStream(out);
byte[] buf = new byte[BUF_SIZE];
int len = 0;
while ((len = in.read(buf, 0, buf.length)) > 0)
{
outCRLF.write(buf, 0, len);
}
outCRLF.flush();
}
else
{
if (!defaultContentTransferEncoding.equalsIgnoreCase("binary"))
{
out = new CRLFOutputStream(out);
}
bodyPart.writeTo(new CRLFOutputStream(out));
}
}
/**
* return the MimeBodyPart described in the raw bytes provided in content
*/
public static MimeBodyPart toMimeBodyPart(
byte[] content)
throws SMIMEException
{
return toMimeBodyPart(new ByteArrayInputStream(content));
}
/**
* return the MimeBodyPart described in the input stream content
*/
public static MimeBodyPart toMimeBodyPart(
InputStream content)
throws SMIMEException
{
try
{
return new MimeBodyPart(content);
}
catch (MessagingException e)
{
throw new SMIMEException("exception creating body part.", e);
}
}
/**
* return a file backed MimeBodyPart described in {@link CMSTypedStream} content.
* </p>
*/
public static FileBackedMimeBodyPart toMimeBodyPart(
CMSTypedStream content)
throws SMIMEException
{
try
{
return toMimeBodyPart(content, File.createTempFile("bcMail", ".mime"));
}
catch (IOException e)
{
throw new SMIMEException("IOException creating tmp file:" + e.getMessage());
}
}
/**
* Return a file based MimeBodyPart represented by content and backed
* by the file represented by file.
*
* @param content content stream containing body part.
* @param file file to store the decoded body part in.
* @return the decoded body part.
* @throws SMIMEException
*/
public static FileBackedMimeBodyPart toMimeBodyPart(
CMSTypedStream content,
File file)
throws SMIMEException
{
try
{
saveContentToFile(content, file);
return new FileBackedMimeBodyPart(file);
}
catch (IOException e)
{
throw new SMIMEException("can't save content to file: " + e, e);
}
catch (MessagingException e)
{
throw new SMIMEException("can't create part: " + e, e);
}
}
private static void saveContentToFile(
CMSTypedStream content,
File tmp)
throws FileNotFoundException, IOException
{
OutputStream out = new FileOutputStream(tmp);
InputStream in = content.getContentStream();
byte[] buf = new byte[10000];
int len;
while ((len = in.read(buf, 0, buf.length)) > 0)
{
out.write(buf, 0, len);
}
out.close();
in.close();
}
/**
* Return a CMS IssuerAndSerialNumber structure for the passed in X.509 certificate.
*
* @param cert the X.509 certificate to get the issuer and serial number for.
* @return an IssuerAndSerialNumber structure representing the certificate.
*/
public static IssuerAndSerialNumber createIssuerAndSerialNumberFor(
X509Certificate cert)
throws CertificateParsingException
{
try
{
return new IssuerAndSerialNumber(PrincipalUtil.getIssuerX509Principal(cert), cert.getSerialNumber());
}
catch (Exception e)
{
throw new CertificateParsingException("exception extracting issuer and serial number: " + e);
}
}
}
| true | true | static void outputBodyPart(
OutputStream out,
Part bodyPart,
String defaultContentTransferEncoding)
throws MessagingException, IOException
{
if (bodyPart instanceof MimeBodyPart)
{
MimeBodyPart mimePart = (MimeBodyPart)bodyPart;
String[] cte = mimePart.getHeader("Content-Transfer-Encoding");
String contentTransferEncoding;
if (cte == null)
{
contentTransferEncoding = defaultContentTransferEncoding;
}
else
{
contentTransferEncoding = cte[0];
}
if (!contentTransferEncoding.equalsIgnoreCase("base64")
&& !contentTransferEncoding.equalsIgnoreCase("quoted-printable"))
{
if (!contentTransferEncoding.equalsIgnoreCase("binary"))
{
out = new CRLFOutputStream(out);
}
bodyPart.writeTo(out);
out.flush();
return;
}
//
// Special handling for Base64 or quoted-printable encoded
// body part - this is to get around JavaMail's habit of
// decoding and then re-encoding base64 data...
//
//
// Write headers
//
LineOutputStream outLine = new LineOutputStream(out);
for (Enumeration e = mimePart.getAllHeaderLines(); e.hasMoreElements();)
{
outLine.writeln((String)e.nextElement());
}
outLine.writeln();
outLine.flush();
//
// Write raw content, performing canonicalization
//
InputStream in = mimePart.getRawInputStream();
CRLFOutputStream outCRLF = new CRLFOutputStream(out);
byte[] buf = new byte[BUF_SIZE];
int len = 0;
while ((len = in.read(buf, 0, buf.length)) > 0)
{
outCRLF.write(buf, 0, len);
}
outCRLF.flush();
}
else
{
if (!defaultContentTransferEncoding.equalsIgnoreCase("binary"))
{
out = new CRLFOutputStream(out);
}
bodyPart.writeTo(new CRLFOutputStream(out));
}
}
| static void outputBodyPart(
OutputStream out,
Part bodyPart,
String defaultContentTransferEncoding)
throws MessagingException, IOException
{
if (bodyPart instanceof MimeBodyPart)
{
MimeBodyPart mimePart = (MimeBodyPart)bodyPart;
String[] cte = mimePart.getHeader("Content-Transfer-Encoding");
String contentTransferEncoding;
if (cte == null)
{
contentTransferEncoding = defaultContentTransferEncoding;
}
else
{
contentTransferEncoding = cte[0];
}
if (!contentTransferEncoding.equalsIgnoreCase("base64")
&& !contentTransferEncoding.equalsIgnoreCase("quoted-printable"))
{
if (!contentTransferEncoding.equalsIgnoreCase("binary"))
{
out = new CRLFOutputStream(out);
}
bodyPart.writeTo(out);
out.flush();
return;
}
//
// Special handling for Base64 or quoted-printable encoded
// body part - this is to get around JavaMail's habit of
// decoding and then re-encoding base64 data...
//
//
// Write headers
//
LineOutputStream outLine = new LineOutputStream(out);
for (Enumeration e = mimePart.getAllHeaderLines(); e.hasMoreElements();)
{
outLine.writeln((String)e.nextElement());
}
outLine.writeln();
outLine.flush();
//
// Write raw content, performing canonicalization
//
InputStream in = mimePart.getRawInputStream();
CRLFOutputStream outCRLF = new CRLFOutputStream(out);
byte[] buf = new byte[BUF_SIZE];
int len = 0;
while ((len = in.read(buf, 0, buf.length)) > 0)
{
outCRLF.write(buf, 0, len);
}
outCRLF.flush();
}
else
{
if (!defaultContentTransferEncoding.equalsIgnoreCase("binary"))
{
out = new CRLFOutputStream(out);
}
bodyPart.writeTo(new CRLFOutputStream(out));
}
}
|
diff --git a/src/test/java/org/apache/wicket/examples/StartExamples.java b/src/test/java/org/apache/wicket/examples/StartExamples.java
index 9d1101b..03bcd0b 100644
--- a/src/test/java/org/apache/wicket/examples/StartExamples.java
+++ b/src/test/java/org/apache/wicket/examples/StartExamples.java
@@ -1,84 +1,84 @@
/*
* 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.wicket.examples;
import java.lang.management.ManagementFactory;
import javax.management.MBeanServer;
import org.eclipse.jetty.jmx.MBeanContainer;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.bio.SocketConnector;
import org.eclipse.jetty.webapp.WebAppContext;
/**
* Separate startup class for people that want to run the examples directly. Use parameter
* -Dcom.sun.management.jmxremote to startup JMX (and e.g. connect with jconsole).
*/
public class StartExamples
{
//FIXME: less can not handle width *: which is some trick!!
/**
* Main function, starts the jetty server.
*
* @param args
*/
public static void main(String[] args)
{
Server server = new Server();
SocketConnector connector = new SocketConnector();
// Set some timeout options to make debugging easier.
connector.setMaxIdleTime(1000 * 60 * 60);
connector.setSoLingerTime(-1);
connector.setPort(8080);
server.setConnectors(new Connector[] { connector });
WebAppContext bb = new WebAppContext();
bb.setServer(server);
- bb.setContextPath("/");
+ bb.setContextPath("/wicket-wro");
bb.setWar("src/main/webapp");
server.setHandler(bb);
MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
MBeanContainer mBeanContainer = new MBeanContainer(mBeanServer);
server.getContainer().addEventListener(mBeanContainer);
try
{
mBeanContainer.start();
server.start();
server.join();
}
catch (Exception e)
{
e.printStackTrace();
System.exit(100);
}
}
/**
* Construct.
*/
StartExamples()
{
super();
}
}
| true | true | public static void main(String[] args)
{
Server server = new Server();
SocketConnector connector = new SocketConnector();
// Set some timeout options to make debugging easier.
connector.setMaxIdleTime(1000 * 60 * 60);
connector.setSoLingerTime(-1);
connector.setPort(8080);
server.setConnectors(new Connector[] { connector });
WebAppContext bb = new WebAppContext();
bb.setServer(server);
bb.setContextPath("/");
bb.setWar("src/main/webapp");
server.setHandler(bb);
MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
MBeanContainer mBeanContainer = new MBeanContainer(mBeanServer);
server.getContainer().addEventListener(mBeanContainer);
try
{
mBeanContainer.start();
server.start();
server.join();
}
catch (Exception e)
{
e.printStackTrace();
System.exit(100);
}
}
| public static void main(String[] args)
{
Server server = new Server();
SocketConnector connector = new SocketConnector();
// Set some timeout options to make debugging easier.
connector.setMaxIdleTime(1000 * 60 * 60);
connector.setSoLingerTime(-1);
connector.setPort(8080);
server.setConnectors(new Connector[] { connector });
WebAppContext bb = new WebAppContext();
bb.setServer(server);
bb.setContextPath("/wicket-wro");
bb.setWar("src/main/webapp");
server.setHandler(bb);
MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
MBeanContainer mBeanContainer = new MBeanContainer(mBeanServer);
server.getContainer().addEventListener(mBeanContainer);
try
{
mBeanContainer.start();
server.start();
server.join();
}
catch (Exception e)
{
e.printStackTrace();
System.exit(100);
}
}
|
diff --git a/ShopifyAPITests/src/com/shopify/api/resources/AssetTest.java b/ShopifyAPITests/src/com/shopify/api/resources/AssetTest.java
index 1287730..ecd1fd7 100644
--- a/ShopifyAPITests/src/com/shopify/api/resources/AssetTest.java
+++ b/ShopifyAPITests/src/com/shopify/api/resources/AssetTest.java
@@ -1,20 +1,20 @@
package com.shopify.api.resources;
import com.shopify.assets.AssetLoader;
public class AssetTest extends FixturesTestCase {
public void testReadingInSingleAsset() {
String singleAsset = AssetLoader.loadAsset(fixturesDir, "Asset/singleAsset.json");
Asset result = reader.read(singleAsset, Asset.class).get(0);
{
- assertEquals("2010-07-12T15:31:50-04:00", result.getCreated_at());
- assertEquals("2010-07-12T15:31:50-04:00", result.getUpdated_at());
+ assertEquals("2010-07-12T15:31:50-04:00", result.getCreatedAt());
+ assertEquals("2010-07-12T15:31:50-04:00", result.getUpdatedAt());
assertEquals(null, result.getPublicUrl());
assertTrue(result.getValue().startsWith("<!-- LIST 3 PER ROW -->"));
assertEquals("templates/index.liquid", result.getKey());
}
}
}
| true | true | public void testReadingInSingleAsset() {
String singleAsset = AssetLoader.loadAsset(fixturesDir, "Asset/singleAsset.json");
Asset result = reader.read(singleAsset, Asset.class).get(0);
{
assertEquals("2010-07-12T15:31:50-04:00", result.getCreated_at());
assertEquals("2010-07-12T15:31:50-04:00", result.getUpdated_at());
assertEquals(null, result.getPublicUrl());
assertTrue(result.getValue().startsWith("<!-- LIST 3 PER ROW -->"));
assertEquals("templates/index.liquid", result.getKey());
}
}
| public void testReadingInSingleAsset() {
String singleAsset = AssetLoader.loadAsset(fixturesDir, "Asset/singleAsset.json");
Asset result = reader.read(singleAsset, Asset.class).get(0);
{
assertEquals("2010-07-12T15:31:50-04:00", result.getCreatedAt());
assertEquals("2010-07-12T15:31:50-04:00", result.getUpdatedAt());
assertEquals(null, result.getPublicUrl());
assertTrue(result.getValue().startsWith("<!-- LIST 3 PER ROW -->"));
assertEquals("templates/index.liquid", result.getKey());
}
}
|
diff --git a/DbstarLauncher/src/com/dbstar/app/settings/RestoreFactoryUtil.java b/DbstarLauncher/src/com/dbstar/app/settings/RestoreFactoryUtil.java
index 1e2ac66e..e2b96bb2 100644
--- a/DbstarLauncher/src/com/dbstar/app/settings/RestoreFactoryUtil.java
+++ b/DbstarLauncher/src/com/dbstar/app/settings/RestoreFactoryUtil.java
@@ -1,81 +1,81 @@
package com.dbstar.app.settings;
import java.util.List;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import com.dbstar.app.GDApplication;
import com.dbstar.model.GDCommon;
import android.net.ethernet.EthernetManager;
import android.net.ethernet.EthernetDevInfo;
public class RestoreFactoryUtil {
private static final String ActionClearSettings = "com.dbstar.Settings.Action.CLEAR_SETTINGS";
public static void clearNetworkInfo() {
Context context = GDApplication.getAppContext();
WifiManager wifiMgr = (WifiManager) context
.getSystemService(Context.WIFI_SERVICE);
List<WifiConfiguration> allConfigs = wifiMgr.getConfiguredNetworks();
for(WifiConfiguration config: allConfigs) {
wifiMgr.removeNetwork(config.networkId);
}
wifiMgr.saveConfiguration();
EthernetManager ethernetMgr = (EthernetManager) context
.getSystemService(Context.ETH_SERVICE);
EthernetDevInfo ethInfo = null;
if (ethernetMgr.isEthConfigured()) {
ethInfo = ethernetMgr.getSavedEthConfig();
- if (mEthInfo.getConnectMode().equals(
+ if (ethInfo.getConnectMode().equals(
EthernetDevInfo.ETH_CONN_MODE_MANUAL)) {
ethInfo.setConnectMode(EthernetDevInfo.ETH_CONN_MODE_DHCP);
ethInfo.setIpAddress(null);
ethInfo.setRouteAddr(null);
ethInfo.setDnsAddr(null);
ethInfo.setNetMask(null);
ethernetMgr.updateEthDevInfo(ethInfo);
}
}
}
public static void clearSystemSettings() {
// send broadcast to settings package
Context context = GDApplication.getAppContext();
Intent intent = new Intent(ActionClearSettings);
context.sendBroadcast(intent);
}
public static void clearPushSettings() {
// send broadcast to system
Context context = GDApplication.getAppContext();
Intent intent = new Intent(GDCommon.ActionSystemRecovery);
intent.putExtra(GDCommon.KeyRecoveryType, GDCommon.RecoveryTypeClearPush);
context.sendBroadcast(intent);
}
public static void clearDrmInfo() {
// send broadcast to system
Context context = GDApplication.getAppContext();
Intent intent = new Intent(GDCommon.ActionSystemRecovery);
intent.putExtra(GDCommon.KeyRecoveryType, GDCommon.RecoveryTypeClearDrmInfo);
context.sendBroadcast(intent);
}
public static void formatDisk () {
Context context = GDApplication.getAppContext();
Intent intent = new Intent(GDCommon.ActionSystemRecovery);
intent.putExtra(GDCommon.KeyRecoveryType, GDCommon.RecoveryTypeFormatDisk);
context.sendBroadcast(intent);
}
}
| true | true | public static void clearNetworkInfo() {
Context context = GDApplication.getAppContext();
WifiManager wifiMgr = (WifiManager) context
.getSystemService(Context.WIFI_SERVICE);
List<WifiConfiguration> allConfigs = wifiMgr.getConfiguredNetworks();
for(WifiConfiguration config: allConfigs) {
wifiMgr.removeNetwork(config.networkId);
}
wifiMgr.saveConfiguration();
EthernetManager ethernetMgr = (EthernetManager) context
.getSystemService(Context.ETH_SERVICE);
EthernetDevInfo ethInfo = null;
if (ethernetMgr.isEthConfigured()) {
ethInfo = ethernetMgr.getSavedEthConfig();
if (mEthInfo.getConnectMode().equals(
EthernetDevInfo.ETH_CONN_MODE_MANUAL)) {
ethInfo.setConnectMode(EthernetDevInfo.ETH_CONN_MODE_DHCP);
ethInfo.setIpAddress(null);
ethInfo.setRouteAddr(null);
ethInfo.setDnsAddr(null);
ethInfo.setNetMask(null);
ethernetMgr.updateEthDevInfo(ethInfo);
}
}
}
| public static void clearNetworkInfo() {
Context context = GDApplication.getAppContext();
WifiManager wifiMgr = (WifiManager) context
.getSystemService(Context.WIFI_SERVICE);
List<WifiConfiguration> allConfigs = wifiMgr.getConfiguredNetworks();
for(WifiConfiguration config: allConfigs) {
wifiMgr.removeNetwork(config.networkId);
}
wifiMgr.saveConfiguration();
EthernetManager ethernetMgr = (EthernetManager) context
.getSystemService(Context.ETH_SERVICE);
EthernetDevInfo ethInfo = null;
if (ethernetMgr.isEthConfigured()) {
ethInfo = ethernetMgr.getSavedEthConfig();
if (ethInfo.getConnectMode().equals(
EthernetDevInfo.ETH_CONN_MODE_MANUAL)) {
ethInfo.setConnectMode(EthernetDevInfo.ETH_CONN_MODE_DHCP);
ethInfo.setIpAddress(null);
ethInfo.setRouteAddr(null);
ethInfo.setDnsAddr(null);
ethInfo.setNetMask(null);
ethernetMgr.updateEthDevInfo(ethInfo);
}
}
}
|
diff --git a/fog.routing.hrm/src/de/tuilmenau/ics/fog/routing/hierarchical/management/Cluster.java b/fog.routing.hrm/src/de/tuilmenau/ics/fog/routing/hierarchical/management/Cluster.java
index 5008b8a7..2322de58 100644
--- a/fog.routing.hrm/src/de/tuilmenau/ics/fog/routing/hierarchical/management/Cluster.java
+++ b/fog.routing.hrm/src/de/tuilmenau/ics/fog/routing/hierarchical/management/Cluster.java
@@ -1,1406 +1,1406 @@
/*******************************************************************************
* Forwarding on Gates Simulator/Emulator - Hierarchical Routing Management
* Copyright (c) 2012, Integrated Communication Systems Group, TU Ilmenau.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
******************************************************************************/
package de.tuilmenau.ics.fog.routing.hierarchical.management;
import java.math.BigInteger;
import java.util.LinkedList;
import de.tuilmenau.ics.fog.bus.Bus;
import de.tuilmenau.ics.fog.packets.hierarchical.clustering.RequestClusterMembership;
import de.tuilmenau.ics.fog.packets.hierarchical.routing.RouteReport;
import de.tuilmenau.ics.fog.routing.hierarchical.election.Elector;
import de.tuilmenau.ics.fog.routing.hierarchical.HRMConfig;
import de.tuilmenau.ics.fog.routing.hierarchical.HRMController;
import de.tuilmenau.ics.fog.routing.hierarchical.RoutingEntry;
import de.tuilmenau.ics.fog.routing.hierarchical.RoutingTable;
import de.tuilmenau.ics.fog.routing.naming.hierarchical.HRMID;
import de.tuilmenau.ics.fog.ui.Logging;
/**
* This class represents a cluster head at a defined hierarchy level.
* At base hierarchy level, multiple Cluster instances may exist. However, at higher hierarchy levels, exactly one Cluster instance may exist.
* Each Cluster instance may manage an unlimited amount of cluster members (-> ClusterMember).
*/
public class Cluster extends ClusterMember
{
/**
* For using this class within (de-)serialization.
*/
private static final long serialVersionUID = -7486131336574637721L;
/**
* This is the cluster counter, which allows for globally (related to a physical simulation machine) unique cluster IDs.
*/
public static long sNextFreeClusterID = 1;
/**
* Stores a reference to the local coordinator instance if the local router is also the coordinator for this cluster
*/
private Coordinator mCoordinator = null;
/**
* Stores the connect inferior local coordinators.
*/
private LinkedList<Coordinator> mInferiorLocalCoordinators = new LinkedList<Coordinator>(); //TODO: register and auto-remove if coordinator is invalidated
/**
* Stores the connect inferior local coordinators.
*/
private LinkedList<CoordinatorProxy> mInferiorRemoteCoordinators = new LinkedList<CoordinatorProxy>(); //TODO: register and auto-remove if coordinatorProxy is invalidated
/**
* Stores a description of former GUICoordinatorIDs
*/
private String mDescriptionFormerGUICoordinatorIDs = "";
/**
* Stores a list of the already used addresses
*/
private LinkedList<Integer> mUsedAddresses = new LinkedList<Integer>();
/**
* Stores how many address broadcasts were already sent
*/
private int mSentAddressBroadcast = 0;
/**
* Stores the local HRMID of the last address distribution event
*/
private HRMID mHRMIDLastDistribution = null;
/**
* Stores a description about the HRMID allocations
*/
private String mDescriptionHRMIDAllocation = new String();
/**
* Stores how many clusters were created per hierarchy level
*/
public static int mCreatedClusters[] = new int[HRMConfig.Hierarchy.HEIGHT];
/**
* This is the constructor of a cluster object. At first such a cluster is identified by its cluster
* ID and the hierarchical level. Later on - once a coordinator is found, it is additionally identified
* by a token the coordinator sends to all participants. In contrast to the cluster token the identity is used
* to filter potential participants that may be used for the election of a coordinator.
*
* Constructor
*
* @param pHRMController the local HRMController instance
* @param pHierarchyLevel the hierarchy level
* @param pClusterID the unique ID of this cluster, a value of "-1" triggers the creation of a new ID
*/
private Cluster(HRMController pHRMController, HierarchyLevel pHierarchyLevel, Long pClusterID)
{
super(pHRMController, pHierarchyLevel, null, -1, null);
Logging.log(this, "CONSTRUCTOR got ClusterID: " + pClusterID);
// set the ClusterID
if ((pClusterID == null) || (pClusterID < 0)){
// create an ID for the cluster
setClusterID(createClusterID());
Logging.log(this, "ClusterID - created unique clusterID " + getClusterID() + "(" + getGUIClusterID() + ")");
}else{
// use the ClusterID from outside
setClusterID(pClusterID);
Logging.log(this, "ClusterID - using pre-defined clusterID " + getClusterID() + "(" + getGUIClusterID() + ")");
}
synchronized (mCreatedClusters) {
mCreatedClusters[getHierarchyLevel().getValue()]++;
}
}
/**
* Factory function: create a cluster
*
* @param pHRMController the local HRMController instance
* @param pHierarchyLevel the hierarchy level
* @param pClusterID the unique ID of this cluster, a value of "-1" triggers the creation of a new ID
*
* @return the new Cluster object
*/
static public Cluster create(HRMController pHRMController, HierarchyLevel pHierarchyLevel, Long pClusterID)
{
Cluster tResult = new Cluster(pHRMController, pHierarchyLevel, pClusterID);
Logging.log(tResult, "\n\n\n################ CREATED CLUSTER at hierarchy level: " + (tResult.getHierarchyLevel().getValue()));
// register at HRMController's internal database
pHRMController.registerCluster(tResult);
// creates new elector object, which is responsible for election processes
tResult.mElector = new Elector(pHRMController, tResult);
return tResult;
}
/**
* Factory function: create a base hierarchy level cluster
*
* @param pHrmController the local HRMController instance
*
* @return the new Cluster object
*/
static public Cluster createBaseCluster(HRMController pHrmController)
{
return create(pHrmController, HierarchyLevel.createBaseLevel(), null);
}
/**
* Generates a new ClusterID
*
* @return the ClusterID
*/
static public synchronized long createClusterID()
{
// get the current unique ID counter
long tResult = sNextFreeClusterID * idMachineMultiplier();
// make sure the next ID isn't equal
sNextFreeClusterID++;
return tResult;
}
/**
* Counts all registered clusters
*
* @return the number of already created clusters
*/
public static long countCreatedClusters()
{
return (sNextFreeClusterID - 1);
}
/**
* Creates a ClusterName object which describes this cluster
*
* @return the new ClusterName object
*/
public ClusterName createClusterName()
{
ClusterName tResult = null;
tResult = new ClusterName(mHRMController, getHierarchyLevel(), getClusterID(), getCoordinatorID());
return tResult;
}
/**
* Determines the coordinator of this cluster. It is "null" if the election was lost or hasn't finished yet.
*
* @return the cluster's coordinator
*/
@Override
public Coordinator getCoordinator()
{
return mCoordinator;
}
/**
* Determines if a coordinator is known.
*
* @return true if the coordinator is elected and known, otherwise false
*/
public boolean hasLocalCoordinator()
{
return (mCoordinator != null);
}
/**
* Returns how many address broadcasts were already sent
*
* @return the number of broadcasts
*/
public int countAddressBroadcasts()
{
return mSentAddressBroadcast;
}
/**
* DISTRIBUTE: distribute addresses among cluster members if:
* + an HRMID was received from a superior coordinator, used to distribute HRMIDs downwards the hierarchy,
* + we were announced as coordinator
* This function is called for distributing HRMIDs among the cluster members.
*/
public void distributeAddresses()
{
HRMID tOwnHRMID = getHRMID();
boolean tClusterIsTopOfHierarchy = getHierarchyLevel().isHighest();
boolean tNewL0HRMID = false;
if((tOwnHRMID != null) || (tClusterIsTopOfHierarchy)){
// do we have a new HRMID since the last call?
// if ((mHRMIDLastDistribution == null) || (!mHRMIDLastDistribution.equals(tOwnHRMID))){
// update the stored HRMID
mHRMIDLastDistribution = tOwnHRMID;
/**
* Distribute addresses
*/
if ((tClusterIsTopOfHierarchy) || ((tOwnHRMID != null) && ((HRMConfig.Addressing.DISTRIBUTE_RELATIVE_ADDRESSES) || (!tOwnHRMID.isRelativeAddress()) /* we already have been assigned a valid HRMID? */))){
mSentAddressBroadcast++;
Logging.log(this, "DISTRIBUTING ADDRESSES [" + mSentAddressBroadcast + "] to entities at level " + getHierarchyLevel().getValue() + "/" + (HRMConfig.Hierarchy.HEIGHT - 1));
/**
* Assign ourself an HRMID address
*/
// are we at the base level?
if(getHierarchyLevel().isBaseLevel()) {
// get the old L0 HRMID
HRMID tOldL0HRMID = getL0HRMID();
/**
* Check we should actually assign a new L0 HRMID
*/
if((tOldL0HRMID == null) || (tOldL0HRMID.isZero()) || (tOldL0HRMID.isRelativeAddress()) || (!tOldL0HRMID.isCluster(getHRMID()))){
// create new HRMID for ourself
HRMID tThisNodesAddress = allocateClusterMemberAddress();
if((tThisNodesAddress != null) && (!tThisNodesAddress.equals(getL0HRMID()))){
// inform HRM controller about the address change
if(getL0HRMID() != null){
// free only if the assigned new address has a different used cluster address
if(tThisNodesAddress.getLevelAddress(getHierarchyLevel()) != getL0HRMID().getLevelAddress(getHierarchyLevel())){
mDescriptionHRMIDAllocation += "\n ..revoked " + getL0HRMID().toString() + " for " + this + ", cause=distributeAddresses() [" + mSentAddressBroadcast + "]";
freeClusterMemberAddress(getL0HRMID().getLevelAddress(getHierarchyLevel()));
}
}
mDescriptionHRMIDAllocation += "\n .." + tThisNodesAddress.toString() + " for " + this + ", cause=distributeAddresses() [" + mSentAddressBroadcast + "]";
Logging.log(this, " ..setting local HRMID " + tThisNodesAddress.toString());
// store the new HRMID for this node
Logging.log(this, "distributeAddresses() [" + mSentAddressBroadcast + "] sets new L0HRMID: " + tThisNodesAddress);
setL0HRMID(tThisNodesAddress);
tNewL0HRMID = true;
}else{
if(tThisNodesAddress == null){
throw new RuntimeException(this + "::distributeAddresses() got a zero HRMID from allocateClusterMemberAddress()");
}
// free the allocated address again
freeClusterMemberAddress(tThisNodesAddress.getLevelAddress(getHierarchyLevel()));
}
}
}
if(tClusterIsTopOfHierarchy){
setHRMID(this, new HRMID(0));
}
/**
* Distribute AssignHRMID packets among the cluster members
*/
LinkedList<ComChannel> tComChannels = getComChannels();
Logging.log(this, " ..distributing HRMIDs among cluster members: " + tComChannels);
int i = 0;
for(ComChannel tComChannel : tComChannels) {
/**
* Trigger: cluster member needs HRMID
*/
Logging.log(this, " ..[" + i + "]: assigning HRMID to: " + tComChannel);
eventClusterMemberNeedsHRMID(tComChannel, "distributeAddresses() [" + mSentAddressBroadcast + "]");
i++;
}
/**
* Announce the local node HRMIDs if we are at base hierarchy level
*/
if(tNewL0HRMID){
LinkedList<ClusterMember> tL0ClusterMembers = mHRMController.getAllL0ClusterMembers();
for(ClusterMember tL0ClusterMember : tL0ClusterMembers){
Logging.log(this, "distributeAddresses() [" + mSentAddressBroadcast + "] triggers an AnnounceHRMID for: " + tL0ClusterMember + " with HRMIDs: " + mHRMController.getHRMIDs());
tL0ClusterMember.distributeAnnounceHRMIDs();
}
}
}
// }else{
// Logging.log(this, "distributeAddresses() skipped because the own HRMID is still the same: " + getHRMID());
// }
}else{
mDescriptionHRMIDAllocation += "\n ..aborted distributeAddresses() because of own HRMID: " + tOwnHRMID;
Logging.warn(this, "distributeAddresses() skipped because the own HRMID is still invalid: " + getHRMID());
}
}
/**
* EVENT: new HRMID assigned
* The function is called when an address update was received.
*
* @param pSourceComChannel the source comm. channel
* @param pHRMID the new HRMID
*/
@Override
public void eventAssignedHRMID(ComChannel pSourceComChannel, HRMID pHRMID)
{
if (HRMConfig.DebugOutput.SHOW_DEBUG_ADDRESS_DISTRIBUTION){
Logging.log(this, "Handling AssignHRMID with assigned HRMID " + pHRMID.toString());
}
if((pHRMID != null) && (!pHRMID.isZero())){
// setHRMID()
super.eventAssignedHRMID(pSourceComChannel, pHRMID);
/**
* Automatic address distribution via this cluster
*/
if (hasLocalCoordinator()){
// we should automatically continue the address distribution?
if (HRMController.GUI_USER_CTRL_ADDRESS_DISTRUTION){
if (HRMConfig.DebugOutput.SHOW_DEBUG_ADDRESS_DISTRIBUTION){
Logging.log(this, " ..continuing the address distribution process via this cluster");
}
distributeAddresses();
}
}else{
if (HRMConfig.DebugOutput.SHOW_DEBUG_ADDRESS_DISTRIBUTION){
Logging.log(this, " ..stopping address propagation here");
}
}
}
}
/**
* Assign new HRMID for being addressable.
*
* @param pCaller the caller who assigns the new HRMID
* @param pHRMID the new HRMID
*/
@Override
public void setHRMID(Object pCaller, HRMID pHRMID)
{
Logging.log(this, "Got new HRMID: " + pHRMID + ", caller=" + pCaller);
/**
* Do we have a new HRMID?
*/
if((pHRMID == null) || (!pHRMID.equals(getHRMID()))){
freeAllClusterMemberAddresses("setHRMID() for " + pHRMID);
/**
* Set the new HRMID
*/
super.setHRMID(pCaller, pHRMID);
// /**
// * Update the local HRG: find other active Cluster instances and store a local loopback link to them
// */
// LinkedList<Cluster> tSiblings = mHRMController.getAllClusters(getHierarchyLevel());
// // iterate over all siblings
// for(Cluster tSibling : tSiblings){
// if(tSibling.isActiveCluster()){
// Logging.log(this, " ..found active sibling: " + tSibling);
// HRMID tSiblingAddress = tSibling.getHRMID();
// HRMID tSiblingL0Address = tSibling.getL0HRMID();
// // has the sibling a valid address?
// if((tSiblingAddress != null) && (!tSiblingAddress.isZero())){
// // avoid recursion
// if(!tSibling.equals(this)){
// // create the new reported routing table entry
// RoutingEntry tRoutingEntryToSibling = RoutingEntry.create(getL0HRMID() /* this cluster */, tSiblingAddress /* the sibling */, tSiblingL0Address, 0 /* loopback route */, RoutingEntry.NO_UTILIZATION, RoutingEntry.NO_DELAY, RoutingEntry.INFINITE_DATARATE);
// // register the new HRG entry
// mHRMController.registerCluster2ClusterLinkHRG(getHRMID(), tSiblingAddress, tRoutingEntryToSibling);
// }
// }
// }
// }
}
}
/**
* Resets the list of used cluster addresses
*
* @param pCause the cause for this reset
*/
private void freeAllClusterMemberAddresses(String pCause)
{
/**
* Reset the list of used addresses because we got a new HRMID
*/
synchronized (mUsedAddresses) {
Logging.log(this, "Resetting list of used addresses: " + mUsedAddresses);
mUsedAddresses.clear();
mDescriptionHRMIDAllocation += "\n ..reset list of used cluster addresses" + ", cause=" + pCause;
}
}
/**
* Allocates a new HRMID for a cluster member.
*
* @return the allocated HRMID for the cluster member
*/
private HRMID allocateClusterMemberAddress()
{
HRMID tResult = (getHRMID() != null ? getHRMID().clone() : null);
if(getHierarchyLevel().isHighest()){
tResult = new HRMID(0);
}
if(tResult != null){
/**
* Search for the lowest free address
*/
int tUsedAddress = 0;
synchronized (mUsedAddresses) {
// iterate over all possible addresses
for(tUsedAddress = 1; tUsedAddress < 1024 /* TODO: 2 ^ digits from HRMConfig */; tUsedAddress++){
// have we found a free address?
if(!mUsedAddresses.contains(tUsedAddress)){
mUsedAddresses.add(tUsedAddress);
Logging.log(this, "Allocated ClusterMember address: " + tUsedAddress);
break;
}
}
}
// transform the member number to a BigInteger
BigInteger tAddress = BigInteger.valueOf(tUsedAddress);
// set the member number for the given hierarchy level
tResult.setLevelAddress(getHierarchyLevel(), tAddress);
// some debug outputs
if (HRMConfig.DebugOutput.GUI_HRMID_UPDATES){
Logging.log(this, "Set " + tAddress + " on hierarchy level " + getHierarchyLevel().getValue() + " for HRMID " + tResult.toString());
Logging.log(this, "Created for a cluster member the NEW HRMID=" + tResult.toString());
}
}
return tResult;
}
/**
* Frees an allocated cluster member address.
*
* @param pAddress the address which should be freed
*/
private void freeClusterMemberAddress(int pAddress)
{
synchronized (mUsedAddresses) {
if(mUsedAddresses.contains(pAddress)){
mUsedAddresses.remove(new Integer(pAddress));
Logging.log(this, "Freed ClusterMember address: " + pAddress);
}
}
}
/**
* Returns the list of used addresses
*
* @return the list
*/
@SuppressWarnings("unchecked")
public LinkedList<Integer> getUsedAddresses()
{
LinkedList<Integer> tResult = null;
Logging.log(this, "Having allocated these HRMIDs: " + mDescriptionHRMIDAllocation);
synchronized (mUsedAddresses) {
tResult = (LinkedList<Integer>) mUsedAddresses.clone();
}
return tResult;
}
/**
* EVENT: cluster member needs HRMID
*
* @param pComChannel the comm. channel towards the cluster member, which needs a new HRMID
* @param pCause the cause for this event
*/
private void eventClusterMemberNeedsHRMID(ComChannel pComChannel, String pCause)
{
Logging.log(this, "EVENT: Cluster_Member_Needs_HRMID for: " + pComChannel + ", cause=" + pCause);
/**
* AUTO ADDRESS DISTRIBUTION
*/
if (HRMController.GUI_USER_CTRL_ADDRESS_DISTRUTION){
HRMID tOldHRMIDForPeer = pComChannel.getPeerHRMID();
HRMID tHRMIDForPeer = null;
/**
* Check old assignment
*/
Logging.log(this, " ..old peer HRMID: " + tOldHRMIDForPeer);
if(!HRMConfig.Addressing.REUSE_ADDRESSES){
Logging.log(this, " ..reseting the old HRMID to null because address reusage is disabled");
tOldHRMIDForPeer = null;
}
if((tOldHRMIDForPeer != null) && (!tOldHRMIDForPeer.isZero()) && ((tOldHRMIDForPeer.isCluster(getHRMID())) || (getHierarchyLevel().isHighest()))){
int tUsedAddress = tOldHRMIDForPeer.getLevelAddress(getHierarchyLevel());
synchronized (mUsedAddresses) {
if(!mUsedAddresses.contains(tUsedAddress)){
Logging.log(this, " ..mark the address as used in this cluster");
// add the peer address to the used addresses
mUsedAddresses.add(tUsedAddress);
}
// else{
// if(!getHierarchyLevel().isHighest()){
// Logging.log(this, " ..this address is already used, allocating a new one");
// // the formerly used address isn't available anymore
// tOldHRMIDForPeer = null;
// }else{
// Logging.log(this, " ..this address is already used, allocating a new one");
// }
// }
}
}
/**
* Check we should actually assign a new HRMID
*/
if((tOldHRMIDForPeer == null) || (tOldHRMIDForPeer.isZero()) || (tOldHRMIDForPeer.isRelativeAddress()) || ((!tOldHRMIDForPeer.isCluster(getHRMID()) && (!getHierarchyLevel().isHighest())))){
HRMID tNewHRMIDForPeer = allocateClusterMemberAddress();
if(tNewHRMIDForPeer != null){
mDescriptionHRMIDAllocation += "\n .." + tNewHRMIDForPeer.toString() + " for " + pComChannel + ", cause=" + pCause;
/**
* Abort if we shouldn't distribute relative addresses
*/
if((!HRMConfig.Addressing.DISTRIBUTE_RELATIVE_ADDRESSES) && (tNewHRMIDForPeer.isRelativeAddress())){
//Logging.warn(this, "eventClusterMemberNeedsHRMID() aborted because the relative address shouldn't be distributed: " + tNewHRMIDForPeer);
mDescriptionHRMIDAllocation += "\n ..revoked " + tNewHRMIDForPeer.toString() + " for " + pComChannel + ", cause=" + pCause;
freeClusterMemberAddress(tNewHRMIDForPeer.getLevelAddress(getHierarchyLevel()));
return;
}
// store the HRMID under which the peer will be addressable from now
pComChannel.setPeerHRMID(tNewHRMIDForPeer);
// register this new HRMID in the local HRS and create a mapping to the right L2Address
if(!tNewHRMIDForPeer.isClusterAddress()){
Logging.log(this, " ..creating MAPPING " + tNewHRMIDForPeer.toString() + " to " + pComChannel.getPeerL2Address());
mHRMController.getHRS().mapHRMID(tNewHRMIDForPeer, pComChannel.getPeerL2Address());
}
tHRMIDForPeer = tNewHRMIDForPeer;
}else{
Logging.err(this, "::eventClusterMemberNeedsHRMID() [" + getHRMID() + "] got an invalid new cluster member address for: " + pComChannel);
}
}else{
mDescriptionHRMIDAllocation += "\n ..reassigned " + tOldHRMIDForPeer.toString() + " for " + pComChannel + ", cause=" + pCause;
Logging.log(this, " ..reassigning " + tOldHRMIDForPeer.toString() + " for " + pComChannel);
tHRMIDForPeer = tOldHRMIDForPeer;
}
// send the packet in every case
if(tHRMIDForPeer != null){
if ((pComChannel.getPeerHRMID() != null) && (!pComChannel.getPeerHRMID().equals(tHRMIDForPeer))){
Logging.log(this, " ..replacing HRMID " + pComChannel.getPeerHRMID().toString() + " and assign new HRMID " + tHRMIDForPeer.toString() + " to " + pComChannel.getPeerL2Address());
}else
Logging.log(this, " ..assigning new HRMID " + tHRMIDForPeer.toString() + " to " + pComChannel.getPeerL2Address());
pComChannel.distributeAssignHRMID(tHRMIDForPeer);
}else{
mDescriptionHRMIDAllocation += "\n ..invalid HRMID for " + pComChannel + ", cause=" + pCause;
Logging.warn(this, "eventClusterMemberNeedsHRMID() detected invalid cluster HRMID and cannot signal new HRMID to: " + pComChannel);
}
}else{
Logging.log(this, "Address distribution is deactivated, no new assigned HRMID for: " + pComChannel);
}
}
/**
* EVENT: all cluster addresses are invalid
*/
public void eventAllClusterAddressesInvalid()
{
Logging.log(this, "EVENT: all cluster addresses got declared invalid");
setHRMID(this, null);
/**
* Revoke all HRMIDs from the cluster members
*/
LinkedList<ComChannel> tComChannels = getComChannels();
int i = 0;
for (ComChannel tComChannel : tComChannels){
/**
* Unregister all HRMID-2-L2Address mappings
*/
for(HRMID tHRMIDForPeer:tComChannel.getAssignedPeerHRMIDs()){
// register this new HRMID in the local HRS and create a mapping to the right L2Address
Logging.log(this, " ..removing MAPPING " + tHRMIDForPeer.toString() + " to " + tComChannel.getPeerL2Address());
mHRMController.getHRS().unmapHRMID(tHRMIDForPeer);
}
/**
* Revoke all assigned HRMIDs from peers
*/
Logging.log(this, " ..[" + i + "]: revoking HRMIDs via: " + tComChannel);
tComChannel.signalRevokeAssignedHRMIDs();
i++;
}
/**
* Reset the list of used addresses
*/
freeAllClusterMemberAddresses("eventAllClusterAddressesInvalid()");
}
/**
* EVENT: new local coordinator, triggered by the Coordinator
*
* @param pCoordinator the new coordinator, which is located on this node
*/
public void eventNewLocalCoordinator(Coordinator pCoordinator)
{
Logging.log(this, "EVENT: new local coordinator: " + pCoordinator + ", old one is: " + mCoordinator);
// set the coordinator
mCoordinator = pCoordinator;
/**
* Update cluster activation
*/
if(pCoordinator != null){
// mark this cluster as active
setClusterWithValidCoordinator(true);
}else{
// mark this cluster as inactive
setClusterWithValidCoordinator(false);
}
// update the stored unique ID for the coordinator
if (pCoordinator != null){
setSuperiorCoordinatorID(pCoordinator.getCoordinatorID());
setCoordinatorID(pCoordinator.getCoordinatorID());
// update the descriptive string about the coordinator
setSuperiorCoordinatorDescription(mCoordinator.toLocation());
}else{
setSuperiorCoordinatorID(0);
setCoordinatorID(0);
setSuperiorCoordinatorDescription("");
}
}
/**
* Detects the local neighborhood.
* IMPORTANT: This is the main function for determining capacities and link usage
*/
@Override
public void detectNeighborhood()
{
if(hasClusterValidCoordinator()){
if(getHierarchyLevel().isBaseLevel()){
super.detectNeighborhood();
if(countConnectedRemoteClusterMembers() > 1){
if(getBaseHierarchyLevelNetworkInterface() != null){
// get the physical BUS
Bus tPhysicalBus = (Bus)getBaseHierarchyLevelNetworkInterface().getBus();
// iterate over all comm. channels
for(ComChannel tOuterChannel : getComChannels()){
HRMID tOuterHRMID = tOuterChannel.getPeerHRMID();
for(ComChannel tInnerChannel : getComChannels()){
HRMID tInnerHRMID = tInnerChannel.getPeerHRMID();
if((tOuterHRMID != null) && (tInnerHRMID != null)){
if(!tOuterHRMID.equals(tInnerHRMID)){
//Logging.log(this, " .." + tOuterHRMID + " is BUS neighbor of: " + tInnerHRMID);
RoutingEntry tEntryForward = RoutingEntry.createRouteToDirectNeighbor(tOuterHRMID, tInnerHRMID, tInnerHRMID, tPhysicalBus.getUtilization(), tPhysicalBus.getDelayMSec(), tPhysicalBus.getAvailableDataRate(), this + "::detectNeighborhood()");
tEntryForward.setNextHopL2Address(tInnerChannel.getPeerL2Address());
mHRMController.registerAutoHRG(tEntryForward);
RoutingEntry tEntryBackward = RoutingEntry.createRouteToDirectNeighbor(tInnerHRMID, tOuterHRMID, tOuterHRMID, tPhysicalBus.getUtilization(), tPhysicalBus.getDelayMSec(), tPhysicalBus.getAvailableDataRate(), this + "::detectNeighborhood()");
tEntryBackward.setNextHopL2Address(tOuterChannel.getPeerL2Address());
mHRMController.registerAutoHRG(tEntryBackward);
}
}
}
}
}
}
}else{
Logging.err(this, "detectNeighborhood() expects base hierarchy level");
}
}
}
/**
* Returns the machine-local ClusterID (excluding the machine specific multiplier)
*
* @return the machine-local ClusterID
*/
public long getGUIClusterID()
{
if (getClusterID() != null)
return getClusterID() / idMachineMultiplier();
else
return -1;
}
/**
* EVENT: coordinator lost
*/
public void eventCoordinatorLost()
{
Logging.log(this, "EVENT: coordinator was lost");
/**
* Revoke HRMID of physical node if we are on base hierarchy level
*/
if(getHierarchyLevel().isBaseLevel()){
if(getL0HRMID() != null){
Logging.log(this, "Unregistering physical node HRMID: " + getL0HRMID());
mDescriptionHRMIDAllocation += "\n ..revoked " + getL0HRMID().toString() + " for " + this + ", cause=eventCoordinatorLost()";
freeClusterMemberAddress(getL0HRMID().getLevelAddress(getHierarchyLevel()));
mHRMController.unregisterHRMID(this, getL0HRMID(), this + "::eventCoordinatorLost()");
}
}
// store the former coordinator ID
mDescriptionFormerGUICoordinatorIDs += " " + Long.toString(getGUICoordinatorID());
// unregister coordinator
eventNewLocalCoordinator(null);
}
/**
* Returns a description of the former GUICoordinatorIDs
*
* @return the description
*/
public String getDescriptionFormerGUICoordinatorIDs()
{
return mDescriptionFormerGUICoordinatorIDs;
}
/**
* EVENT: RouteReport from an inferior entity received, triggered by the comm. channel
*
* @param pComChannel the source comm. channel
* @param pRouteReportPacket the packet
*/
public void eventReceivedRouteReport(ComChannel pSourceComChannel, RouteReport pRouteReportPacket)
{
if(HRMConfig.DebugOutput.SHOW_REPORT_PHASE){
Logging.log(this, "EVENT: ReceivedRouteReport: " + pRouteReportPacket);
}
/**
* Iterate over all reported routes and derive new data for the HRG
*/
RoutingTable tNewReportedRoutingTable = pRouteReportPacket.getRoutes();
for(RoutingEntry tEntry : tNewReportedRoutingTable){
if(HRMConfig.DebugOutput.SHOW_REPORT_PHASE){
Logging.err(this, " ..received route: " + tEntry);
}
double tBefore = HRMController.getRealTime();
/**
* Set the timeout for reported routes
*/
tEntry.setTimeout(mHRMController.getSimulationTime() + HRMConfig.Routing.ROUTE_TIMEOUT);
/**
* Mark as reported entry
*/
tEntry.setReportedLink(pSourceComChannel.getPeerHRMID());
/**
* Update the HRG
*/
int tHopCount = tEntry.getHopCount();
switch(tHopCount)
{
case 0:
// it's an inter-cluster link because local loopbacks aren't sent as report
tEntry.extendCause(this + "::eventReceivedRouteReport()(0 hops) from " + pSourceComChannel.getPeerHRMID());
/**
* Check if the reported link is already reported by a local inferior coordinator.
*
* For example, the local coordinator 1.0.0 exists and the foreign coordinator 2.0.0 reports a link from (1.0.0 <==> 2.0.0).
* In this case, the local coordinator 1.0.0 has already registered the corresponding HRG links.
*/
HRMID tFromCluster = tEntry.getNextHop().getForeignCluster(tEntry.getSource());
HRMID tToCluster = tEntry.getSource().getForeignCluster(tEntry.getNextHop());
boolean tLinkAlreadyKnown = false;
LinkedList<Coordinator> tLocalInferiorCoordinators = mHRMController.getAllCoordinators(getHierarchyLevel().getValue() - 1);
for(Coordinator tCoordinator : tLocalInferiorCoordinators){
if((tFromCluster.equals(tCoordinator.getHRMID())) || (tToCluster.equals(tCoordinator.getHRMID()))){
tLinkAlreadyKnown = true;
}
}
if(!tLinkAlreadyKnown){
mHRMController.registerAutoHRG(tEntry);
}else{
if(HRMConfig.DebugOutput.SHOW_REPORT_PHASE){
Logging.log(this, "Dropping uninteresting reported route: " + tEntry);
}
}
break;
case 1:
default: // 2+
// do we have an intra-cluster link?
if((!tEntry.getDest().isClusterAddress()) && (tEntry.getDest().equals(tEntry.getLastNextHop()))){
tEntry.extendCause(this + "::eventReceivedRouteReport()(1 hop) from " + pSourceComChannel.getPeerHRMID());
mHRMController.registerLinkHRG(tEntry.getSource(), tEntry.getLastNextHop(), tEntry);
}else{
// strange, an inter-cluster link with ONE hop?!
}
break;
}
double tSpentTime = HRMController.getRealTime() - tBefore;
if(tSpentTime > 30){
Logging.log(this, " ..eventReceivedRouteReport() for entry with " + tHopCount + " hops took " + tSpentTime + " ms for processing " + tEntry + " of route report: " + pRouteReportPacket);
}
// /**
// * Does the next hop lead to a foreign cluster?
// */
// if(tDestHRMID.isClusterAddress()){
// // is it a route from a physical node to the next one, which belongs to the destination cluster?
// if(pRoutingEntry.isRouteToDirectNeighbor()){
// // register automatically new links in the HRG based on pRoutingEntry
// registerAutoHRG(pRoutingEntry);
// }
// }else{
// pRoutingEntry.extendCause(this + "::addHRMRoute()_2");
// if(HRMConfig.DebugOutput.GUI_SHOW_HRG_UPDATES){
// Logging.log(this, " ..registering (" + mCallsAddHRMRoute + ") nodeHRMID-2-nodeHRMID HRG link for: " + pRoutingEntry);
// }
// registerLinkHRG(pRoutingEntry.getSource(), pRoutingEntry.getNextHop(), pRoutingEntry);
// }
// HRMID tDestHRMID = tEntry.getDest();
// HRMID tOwnClusterAddress = getHRMID();
// if(tDestHRMID != null){
// // search for cluster destinations
// if(tDestHRMID.isClusterAddress()){
// // avoid recursion
// if(!tDestHRMID.equals(tOwnClusterAddress)){
// if(HRMConfig.DebugOutput.SHOW_SHARE_PHASE){
// Logging.log(this, " ..route between clusters found");
// }
//
// /**
// * Store/update link in the HRG
// */
//// mHRMController.registerCluster2ClusterLinkHRG(tEntry.getSource(), tDestHRMID, tEntry);
// }
// }
// }else{
// Logging.err(this, "Invalid route received: " + tEntry);
// }
}
}
/**
* EVENT: "lost cluster member", triggered by Elector in case a member left the election
* @param pComChannel the comm. channel of the lost cluster member
* @param pCause the cause for the call
*/
public void eventClusterMemberLost(ComChannel pComChannel, String pCause)
{
Logging.log(this, "EVENT: lost cluster member behind: " + pComChannel + "\n cause=" + pCause);
/**
* Unregister all HRMID-2-L2Address mappings
*/
for(HRMID tHRMIDForPeer : pComChannel.getAssignedPeerHRMIDs()){
// unregister the old HRMID fom the local HRS and remove the mapping to the corresponding L2Address
Logging.log(this, " ..removing MAPPING " + tHRMIDForPeer.toString() + " to " + pComChannel.getPeerL2Address());
mHRMController.getHRS().unmapHRMID(tHRMIDForPeer);
}
/**
* Free the previously allocated cluster address
*/
HRMID tPeerHRMID = pComChannel.getPeerHRMID();
if((tPeerHRMID != null) && (!tPeerHRMID.isZero())){
mDescriptionHRMIDAllocation += "\n ..revoked " + tPeerHRMID.toString() + " for " + pComChannel + ", cause=eventClusterMemberLost()";
freeClusterMemberAddress(tPeerHRMID.getLevelAddress(getHierarchyLevel()));
}
/**
* Unregister the comm. channel
*/
unregisterComChannel(pComChannel);
ControlEntity tChannelPeer = pComChannel.getPeer();
if (tChannelPeer != null){
/**
* Update ARG
*/
mHRMController.unregisterLinkARG(this, tChannelPeer);
/**
* Update locally stored database about inferior entities
*/
// does this comm. channel end at a local coordinator?
if(tChannelPeer instanceof Coordinator){
synchronized (mInferiorLocalCoordinators) {
if(HRMConfig.DebugOutput.SHOW_CLUSTERING_STEPS){
Logging.log(this, " ..removing local cluster member: " + tChannelPeer);
}
if(mInferiorLocalCoordinators.contains(tChannelPeer)){
mInferiorLocalCoordinators.remove(tChannelPeer);
}else{
Logging.err(this, "Cannot remove unknown local inferior coordinator: " + tChannelPeer);
}
}
}else
// does this comm. channel end at a remote coordinator (a coordinator proxy)?
if(tChannelPeer instanceof CoordinatorProxy){
synchronized (mInferiorRemoteCoordinators) {
if(HRMConfig.DebugOutput.SHOW_CLUSTERING_STEPS){
Logging.log(this, " ..removing remote cluster member: " + tChannelPeer);
}
if(mInferiorRemoteCoordinators.contains(tChannelPeer)){
mInferiorRemoteCoordinators.remove(tChannelPeer);
}else{
Logging.err(this, "Cannot remove unknown remote inferior coordinator: " + tChannelPeer);
}
}
}else{
Logging.err(this, "Comm. channel peer has unsupported type: " + tChannelPeer);
}
}
if(HRMConfig.DebugOutput.SHOW_CLUSTERING_STEPS){
Logging.log(this, " ..remaining comm. channels: " + getComChannels());
Logging.log(this, " ..remaining connected local coordinators: " + mInferiorLocalCoordinators);
Logging.log(this, " ..remaining connected remote coordinators: " + mInferiorRemoteCoordinators);
}
// check necessity
checkClusterNecessity();
/**
* Trigger: "lost candidate" for election
*/
if(isThisEntityValid()){
mElector.eventLostCandidate(pComChannel);
}
}
/**
* Checks the necessity of the cluster
*/
private void checkClusterNecessity()
{
Logging.log(this, "Checking necessity of this cluster");
// no further external candidates available/known (all candidates are gone) or has the last local inferior coordinator left the area?
if ((countConnectedClusterMembers() < 1 /* do we still have cluster members? */) || (mInferiorLocalCoordinators.size() == 0 /* has the last local coordinator left this cluster? */)){
Logging.log(this, "checkClusterNecessity() detected an unneeded cluster");
/**
* TRIGGER: cluster invalid
*/
eventClusterRoleInvalid();
}
}
/**
* EVENT: cluster role invalid
*/
public synchronized void eventClusterRoleInvalid()
{
Logging.log(this, "============ EVENT: cluster role invalid");
if(isThisEntityValid()){
/**
* Trigger: role invalid
*/
eventInvalidation();
/**
* TRIGGER: event coordinator role invalid
*/
if (getCoordinator() != null){
Logging.log(this, " ..eventClusterRoleInvalid() invalidates now the local coordinator: " + getCoordinator());
getCoordinator().eventCoordinatorRoleInvalid();
}else{
Logging.log(this, "eventClusterInvalid() can't deactivate the coordinator because there is none");
}
Logging.log(this, "============ EVENT: canceling all memberships");
Logging.log(this, " ..knowing these comm. channels: " + getComChannels());
LinkedList<ComChannel> tcomChannels = getComChannels();
for(ComChannel tComChannel: tcomChannels){
Logging.log(this, " ..cancelling: " + tComChannel);
/**
* Check if we have already received an ACK for the ClusterMembershipRequest packet
*/
if(!tComChannel.isOpen()){
// enforce "open" state for this comm. channel
Logging.log(this, " ..enforcing OPEN state for this comm. channel: " + tComChannel);
tComChannel.eventEstablished();
}
/**
* Destroy the channel
*/
unregisterComChannel(tComChannel);
}
/**
* Unregister from local databases
*/
Logging.log(this, "============ Destroying this cluster now...");
// unregister the HRMID for this node from the HRM controller
if(getL0HRMID() != null){
mDescriptionHRMIDAllocation += "\n ..revoked " + getL0HRMID().toString() + " for " + this + ", cause=eventClusterRoleInvalid()";
freeClusterMemberAddress(getL0HRMID().getLevelAddress(getHierarchyLevel()));
mHRMController.unregisterHRMID(this, getL0HRMID(), this + "::eventClusterRoleInvalid()");
}
// unregister from HRMController's internal database
mHRMController.unregisterCluster(this);
}else{
Logging.warn(this, "This Cluster is already invalid");
}
}
/**
* EVENT: detected additional cluster member, the event is triggered by the comm. channel
*
* @param pComChannel the comm. channel of the new cluster member
*/
public synchronized void eventClusterMemberJoined(ComChannel pComChannel)
{
Logging.log(this, "EVENT: joined cluster member, comm. channel: " + pComChannel);
/**
* Update ARG
*/
ControlEntity tChannelPeer = pComChannel.getPeer();
if (tChannelPeer != null){
if (tChannelPeer instanceof Coordinator){
mHRMController.registerLinkARG(this, tChannelPeer, new AbstractRoutingGraphLink(AbstractRoutingGraphLink.LinkType.LOCAL_CONNECTION));
}else if(tChannelPeer instanceof CoordinatorProxy){
mHRMController.registerLinkARG(this, tChannelPeer, new AbstractRoutingGraphLink(AbstractRoutingGraphLink.LinkType.REMOTE_CONNECTION));
}else{
Logging.err(this, "Peer (" + pComChannel.getPeer() + " is unsuported for channel: " + pComChannel);
}
}else{
if(!getHierarchyLevel().isBaseLevel()){
Logging.err(this, "Cannot link to invalid peer for channel: " + pComChannel);
}else{
// we are at base hierarchy level: the peer object is a ClusterMember object at a foreign node, there doesn't exist a representation for this entity on this node
}
}
/**
* Trigger: comm. channel established
*/
eventComChannelEstablished(pComChannel);
/**
* Trigger: assign new HRMID
*/
if (hasLocalCoordinator()){
if(pComChannel.getPeerHRMID() == null){
eventClusterMemberNeedsHRMID(pComChannel, "eventClusterMemberJoined()");
}else{
Logging.log(this, "eventClusterMemberJoined() found an already existing peer HRMID for joined cluster member behind: " + pComChannel);
}
}else{
Logging.log(this, "Coordinator missing, we cannot assign a new HRMID to the joined cluster member behind comm. channel: " + pComChannel);
}
}
/**
* Establishes a communication channel
*
* @param pComSession the parent comm. session for the new channel
* @param pRemoteEndPointName the remote EP describing ClusterName
* @param pLocalEndpointName the local EP describing ClusterName
* @param pPeer the control entity which represents the peer
*/
private void establishComChannel(ComSession pComSession, ClusterName pRemoteEndPointName, ClusterName pLocalEndpointName, ControlEntity pPeer)
{
Logging.log(this, "Establishing comm. channel to peer=" + pPeer + "(remoteEP=" + pRemoteEndPointName + ", localEP=" + pLocalEndpointName +")");
/**
* Create communication channel
*/
Logging.log(this, " ..creating new communication channel");
ComChannel tComChannel = new ComChannel(mHRMController, ComChannel.Direction.OUT, this, pComSession, pPeer);
tComChannel.setRemoteClusterName(pLocalEndpointName);
tComChannel.setPeerPriority(pPeer.getPriority());
/**
* Send "RequestClusterMembership" along the comm. session
* HINT: we cannot use the created channel because the remote side doesn't know anything about the new comm. channel yet)
*/
RequestClusterMembership tRequestClusterMembership = new RequestClusterMembership(mHRMController.getNodeL2Address(), pComSession.getPeerL2Address(), createClusterName(), pRemoteEndPointName);
Logging.log(this, " ..sending membership request: " + tRequestClusterMembership);
if (pComSession.write(tRequestClusterMembership)){
Logging.log(this, " ..requested successfully for membership of: " + pPeer);
}else{
Logging.err(this, " ..failed to request for membership of: " + pPeer);
}
}
/**
* Distributes cluster membership requests
* HINT: This function has to be called in a separate thread because it starts new connections and calls blocking functions
*
*/
private int mCountDistributeMembershipRequests = 0;
public void distributeMembershipRequests()
{
mCountDistributeMembershipRequests ++;
/*************************************
* Request for local coordinators
************************************/
if(HRMConfig.DebugOutput.SHOW_CLUSTERING_STEPS){
Logging.log(this, "\n\n\n################ REQUESTING MEMBERSHIP FOR LOCAL COORDINATORS STARTED (call nr: " + mCountDistributeMembershipRequests + ")");
}
if(isThisEntityValid()){
LinkedList<Coordinator> tCoordinators = mHRMController.getAllCoordinators(getHierarchyLevel().getValue() - 1);
if(HRMConfig.DebugOutput.SHOW_CLUSTERING_STEPS){
Logging.log(this, " ..inferior local coordinators: " + tCoordinators.size());
}
/**
* Copy list of inferior local coordinators
*/
- LinkedList<Coordinator> tInferiorLocalCoordinators = null;
+ LinkedList<Coordinator> tOldInferiorLocalCoordinators = null;
synchronized (mInferiorLocalCoordinators) {
- tInferiorLocalCoordinators = (LinkedList<Coordinator>) mInferiorLocalCoordinators.clone();
+ tOldInferiorLocalCoordinators = (LinkedList<Coordinator>) mInferiorLocalCoordinators.clone();
}
/**
* Iterate over all found inferior local coordinators
*/
- synchronized (tInferiorLocalCoordinators) {
+ synchronized (tOldInferiorLocalCoordinators) {
if(mCountDistributeMembershipRequests > 1){
if(HRMConfig.DebugOutput.SHOW_CLUSTERING_STEPS){
- Logging.log(this, " ..having connections to these inferior local coordinators: " + tInferiorLocalCoordinators.toString());
+ Logging.log(this, " ..having connections to these inferior local coordinators: " + tOldInferiorLocalCoordinators.toString());
}
}
for (Coordinator tCoordinator : tCoordinators){
- if (!tInferiorLocalCoordinators.contains(tCoordinator)){
+ if (!tOldInferiorLocalCoordinators.contains(tCoordinator)){
if(HRMConfig.DebugOutput.SHOW_CLUSTERING_STEPS){
Logging.log(this, " ..found inferior local coordinator [NEW]: " + tCoordinator);
}
// add this local coordinator to the list of connected coordinators
synchronized (mInferiorLocalCoordinators) {
if(!mInferiorLocalCoordinators.contains(tCoordinator)){
mInferiorLocalCoordinators.add(tCoordinator);
}else{
Logging.err(this, "Cannot add a duplicate of the local inferior coordinator: " + tCoordinator);
}
}
if(HRMConfig.DebugOutput.SHOW_CLUSTERING_STEPS){
Logging.log(this, " ..get/create communication session");
}
ComSession tComSession = mHRMController.getCreateComSession(mHRMController.getNodeL2Address());
if (tComSession != null){
/**
* Create coordinator name for this coordinator
*/
ClusterName tRemoteEndPointName = tCoordinator.createCoordinatorName();
ClusterName tLocalEndPointName = new ClusterName(mHRMController, tRemoteEndPointName.getHierarchyLevel().inc() /* at the remote side, a CoordinatorAsClusterMember is always located at one hierarchy level above the original coordinator object */, tRemoteEndPointName.getClusterID(), tRemoteEndPointName.getCoordinatorID());
/**
* Establish the comm. channel
*/
establishComChannel(tComSession, tRemoteEndPointName, tLocalEndPointName, tCoordinator);
}else{
Logging.err(this, "distributeMembershipRequests() couldn't determine the comm. session to: " + mHRMController.getNodeName() + " for local coordinator: " + tCoordinator);
}
}else{
if(HRMConfig.DebugOutput.SHOW_CLUSTERING_STEPS){
Logging.log(this, " ..found inferior local coordinator [already connected]: " + tCoordinator);
}
}
}
if(HRMConfig.DebugOutput.SHOW_CLUSTERING_STEPS){
Logging.log(this, " ..finished clustering of local inferior coordinators");
}
/************************************
* Requests for remote coordinators
************************************/
- if(tInferiorLocalCoordinators.size() > 0){
+ if(mInferiorLocalCoordinators.size() > 0){
if(HRMConfig.DebugOutput.SHOW_CLUSTERING_STEPS){
Logging.log(this, "\n\n\n################ REQUESTING MEMBERSHIP FOR REMOTE COORDINATORS STARTED");
}
LinkedList<CoordinatorProxy> tCoordinatorProxies = mHRMController.getAllCoordinatorProxies(getHierarchyLevel().getValue() - 1);
if(HRMConfig.DebugOutput.SHOW_CLUSTERING_STEPS){
Logging.log(this, " ..inferior remote coordinators: " + tCoordinatorProxies.size());
}
if(tCoordinatorProxies.size() > 0){
/**
* Copy list of inferior local coordinators
*/
- LinkedList<Coordinator> tInferiorRemoteCoordinators = null;
+ LinkedList<Coordinator> tOldInferiorRemoteCoordinators = null;
synchronized (mInferiorRemoteCoordinators) {
- tInferiorRemoteCoordinators = (LinkedList<Coordinator>) mInferiorRemoteCoordinators.clone();
+ tOldInferiorRemoteCoordinators = (LinkedList<Coordinator>) mInferiorRemoteCoordinators.clone();
}
/**
* Iterate over all found remote coordinators
*/
- synchronized (tInferiorRemoteCoordinators) {
+ synchronized (tOldInferiorRemoteCoordinators) {
if(mCountDistributeMembershipRequests > 1){
if(HRMConfig.DebugOutput.SHOW_CLUSTERING_STEPS){
- Logging.log(this, " ..having connections to these inferior remote coordinators: " + tInferiorRemoteCoordinators.toString());
+ Logging.log(this, " ..having connections to these inferior remote coordinators: " + tOldInferiorRemoteCoordinators.toString());
}
}
for (CoordinatorProxy tCoordinatorProxy : tCoordinatorProxies){
- if (!tInferiorRemoteCoordinators.contains(tCoordinatorProxy)){
+ if (!tOldInferiorRemoteCoordinators.contains(tCoordinatorProxy)){
if(HRMConfig.DebugOutput.SHOW_CLUSTERING_STEPS){
Logging.log(this, " ..found remote inferior coordinator[NEW]: " + tCoordinatorProxy);
}
// add this remote coordinator to the list of connected coordinators
synchronized (mInferiorRemoteCoordinators) {
if(!mInferiorRemoteCoordinators.contains(tCoordinatorProxy)){
mInferiorRemoteCoordinators.add(tCoordinatorProxy);
}else{
Logging.err(this, "Cannot add a duplicate of the remote inferior coordinator: " + tCoordinatorProxy);
}
}
ComSession tComSession = mHRMController.getCreateComSession(tCoordinatorProxy.getCoordinatorNodeL2Address());
if (tComSession != null){
/**
* Create coordinator name for this coordinator proxy
*/
ClusterName tRemoteEndPointName = tCoordinatorProxy.createCoordinatorName();
ClusterName tLocalEndPointName = new ClusterName(mHRMController, tRemoteEndPointName.getHierarchyLevel().inc() /* at the remote side, a CoordinatorAsClusterMember is always located at one hierarchy level above the original coordinator object */, tRemoteEndPointName.getClusterID(), tRemoteEndPointName.getCoordinatorID());
/**
* Establish the comm. channel
*/
establishComChannel(tComSession, tRemoteEndPointName, tLocalEndPointName, tCoordinatorProxy);
}else{
Logging.err(this, "distributeMembershipRequests() couldn't determine the comm. session to: " + mHRMController.getNodeName() + " for remote coordinator: " + tCoordinatorProxy);
}
}else{
if(HRMConfig.DebugOutput.SHOW_CLUSTERING_STEPS){
Logging.log(this, " ..found inferior remote coordinator [already connected]: " + tCoordinatorProxy);
}
}
}
}
}else{
/**
* Trigger: detected local isolation
*/
eventDetectedIsolation();
}
}else{
if(HRMConfig.DebugOutput.SHOW_CLUSTERING_STEPS){
- Logging.log(this, " ..no local inferior coordinators found");
+ Logging.log(this, " ..no local inferior coordinators existing");
}
}
}
}else{
Logging.warn(this, "distributeMembershipRequests() skipped because cluster role is already invalidated");
}
// finally, check the necessity of this cluster again
checkClusterNecessity();
}
/**
* EVENT: detected isolation
*/
private void eventDetectedIsolation()
{
if(HRMConfig.DebugOutput.SHOW_CLUSTERING_STEPS){
Logging.log(this, "EVENT: detected local isolation");
}
}
/**
* Defines the decoration text for the ARG viewer
*
* @return text for the control entity or null if no text is available
*/
@Override
public String getText()
{
return null;
}
/**
* Returns a descriptive string about this object
*
* @return the descriptive string
*/
public String toString()
{
return toLocation() + "(" + idToString() + ")";
}
/**
* Returns a location description about this instance
*
* @return the location description
*/
@Override
public String toLocation()
{
String tResult = getClass().getSimpleName() + (getGUIClusterID() != -1 ? Long.toString(getGUIClusterID()) : "??") + "@" + mHRMController.getNodeGUIName() + "@" + getHierarchyLevel().getValue();
return tResult;
}
/**
* Returns a string including the ClusterID, the coordinator ID, and the node priority
*
* @return the complex string
*/
private String idToString()
{
if ((getHRMID() == null) || (getHRMID().isRelativeAddress())){
return "Coordinator" + getGUICoordinatorID();
}else{
return "Coordinator" + getGUICoordinatorID() + ", HRMID=" + getHRMID().toString();
}
}
}
| false | true | public void distributeMembershipRequests()
{
mCountDistributeMembershipRequests ++;
/*************************************
* Request for local coordinators
************************************/
if(HRMConfig.DebugOutput.SHOW_CLUSTERING_STEPS){
Logging.log(this, "\n\n\n################ REQUESTING MEMBERSHIP FOR LOCAL COORDINATORS STARTED (call nr: " + mCountDistributeMembershipRequests + ")");
}
if(isThisEntityValid()){
LinkedList<Coordinator> tCoordinators = mHRMController.getAllCoordinators(getHierarchyLevel().getValue() - 1);
if(HRMConfig.DebugOutput.SHOW_CLUSTERING_STEPS){
Logging.log(this, " ..inferior local coordinators: " + tCoordinators.size());
}
/**
* Copy list of inferior local coordinators
*/
LinkedList<Coordinator> tInferiorLocalCoordinators = null;
synchronized (mInferiorLocalCoordinators) {
tInferiorLocalCoordinators = (LinkedList<Coordinator>) mInferiorLocalCoordinators.clone();
}
/**
* Iterate over all found inferior local coordinators
*/
synchronized (tInferiorLocalCoordinators) {
if(mCountDistributeMembershipRequests > 1){
if(HRMConfig.DebugOutput.SHOW_CLUSTERING_STEPS){
Logging.log(this, " ..having connections to these inferior local coordinators: " + tInferiorLocalCoordinators.toString());
}
}
for (Coordinator tCoordinator : tCoordinators){
if (!tInferiorLocalCoordinators.contains(tCoordinator)){
if(HRMConfig.DebugOutput.SHOW_CLUSTERING_STEPS){
Logging.log(this, " ..found inferior local coordinator [NEW]: " + tCoordinator);
}
// add this local coordinator to the list of connected coordinators
synchronized (mInferiorLocalCoordinators) {
if(!mInferiorLocalCoordinators.contains(tCoordinator)){
mInferiorLocalCoordinators.add(tCoordinator);
}else{
Logging.err(this, "Cannot add a duplicate of the local inferior coordinator: " + tCoordinator);
}
}
if(HRMConfig.DebugOutput.SHOW_CLUSTERING_STEPS){
Logging.log(this, " ..get/create communication session");
}
ComSession tComSession = mHRMController.getCreateComSession(mHRMController.getNodeL2Address());
if (tComSession != null){
/**
* Create coordinator name for this coordinator
*/
ClusterName tRemoteEndPointName = tCoordinator.createCoordinatorName();
ClusterName tLocalEndPointName = new ClusterName(mHRMController, tRemoteEndPointName.getHierarchyLevel().inc() /* at the remote side, a CoordinatorAsClusterMember is always located at one hierarchy level above the original coordinator object */, tRemoteEndPointName.getClusterID(), tRemoteEndPointName.getCoordinatorID());
/**
* Establish the comm. channel
*/
establishComChannel(tComSession, tRemoteEndPointName, tLocalEndPointName, tCoordinator);
}else{
Logging.err(this, "distributeMembershipRequests() couldn't determine the comm. session to: " + mHRMController.getNodeName() + " for local coordinator: " + tCoordinator);
}
}else{
if(HRMConfig.DebugOutput.SHOW_CLUSTERING_STEPS){
Logging.log(this, " ..found inferior local coordinator [already connected]: " + tCoordinator);
}
}
}
if(HRMConfig.DebugOutput.SHOW_CLUSTERING_STEPS){
Logging.log(this, " ..finished clustering of local inferior coordinators");
}
/************************************
* Requests for remote coordinators
************************************/
if(tInferiorLocalCoordinators.size() > 0){
if(HRMConfig.DebugOutput.SHOW_CLUSTERING_STEPS){
Logging.log(this, "\n\n\n################ REQUESTING MEMBERSHIP FOR REMOTE COORDINATORS STARTED");
}
LinkedList<CoordinatorProxy> tCoordinatorProxies = mHRMController.getAllCoordinatorProxies(getHierarchyLevel().getValue() - 1);
if(HRMConfig.DebugOutput.SHOW_CLUSTERING_STEPS){
Logging.log(this, " ..inferior remote coordinators: " + tCoordinatorProxies.size());
}
if(tCoordinatorProxies.size() > 0){
/**
* Copy list of inferior local coordinators
*/
LinkedList<Coordinator> tInferiorRemoteCoordinators = null;
synchronized (mInferiorRemoteCoordinators) {
tInferiorRemoteCoordinators = (LinkedList<Coordinator>) mInferiorRemoteCoordinators.clone();
}
/**
* Iterate over all found remote coordinators
*/
synchronized (tInferiorRemoteCoordinators) {
if(mCountDistributeMembershipRequests > 1){
if(HRMConfig.DebugOutput.SHOW_CLUSTERING_STEPS){
Logging.log(this, " ..having connections to these inferior remote coordinators: " + tInferiorRemoteCoordinators.toString());
}
}
for (CoordinatorProxy tCoordinatorProxy : tCoordinatorProxies){
if (!tInferiorRemoteCoordinators.contains(tCoordinatorProxy)){
if(HRMConfig.DebugOutput.SHOW_CLUSTERING_STEPS){
Logging.log(this, " ..found remote inferior coordinator[NEW]: " + tCoordinatorProxy);
}
// add this remote coordinator to the list of connected coordinators
synchronized (mInferiorRemoteCoordinators) {
if(!mInferiorRemoteCoordinators.contains(tCoordinatorProxy)){
mInferiorRemoteCoordinators.add(tCoordinatorProxy);
}else{
Logging.err(this, "Cannot add a duplicate of the remote inferior coordinator: " + tCoordinatorProxy);
}
}
ComSession tComSession = mHRMController.getCreateComSession(tCoordinatorProxy.getCoordinatorNodeL2Address());
if (tComSession != null){
/**
* Create coordinator name for this coordinator proxy
*/
ClusterName tRemoteEndPointName = tCoordinatorProxy.createCoordinatorName();
ClusterName tLocalEndPointName = new ClusterName(mHRMController, tRemoteEndPointName.getHierarchyLevel().inc() /* at the remote side, a CoordinatorAsClusterMember is always located at one hierarchy level above the original coordinator object */, tRemoteEndPointName.getClusterID(), tRemoteEndPointName.getCoordinatorID());
/**
* Establish the comm. channel
*/
establishComChannel(tComSession, tRemoteEndPointName, tLocalEndPointName, tCoordinatorProxy);
}else{
Logging.err(this, "distributeMembershipRequests() couldn't determine the comm. session to: " + mHRMController.getNodeName() + " for remote coordinator: " + tCoordinatorProxy);
}
}else{
if(HRMConfig.DebugOutput.SHOW_CLUSTERING_STEPS){
Logging.log(this, " ..found inferior remote coordinator [already connected]: " + tCoordinatorProxy);
}
}
}
}
}else{
/**
* Trigger: detected local isolation
*/
eventDetectedIsolation();
}
}else{
if(HRMConfig.DebugOutput.SHOW_CLUSTERING_STEPS){
Logging.log(this, " ..no local inferior coordinators found");
}
}
}
}else{
Logging.warn(this, "distributeMembershipRequests() skipped because cluster role is already invalidated");
}
// finally, check the necessity of this cluster again
checkClusterNecessity();
}
| public void distributeMembershipRequests()
{
mCountDistributeMembershipRequests ++;
/*************************************
* Request for local coordinators
************************************/
if(HRMConfig.DebugOutput.SHOW_CLUSTERING_STEPS){
Logging.log(this, "\n\n\n################ REQUESTING MEMBERSHIP FOR LOCAL COORDINATORS STARTED (call nr: " + mCountDistributeMembershipRequests + ")");
}
if(isThisEntityValid()){
LinkedList<Coordinator> tCoordinators = mHRMController.getAllCoordinators(getHierarchyLevel().getValue() - 1);
if(HRMConfig.DebugOutput.SHOW_CLUSTERING_STEPS){
Logging.log(this, " ..inferior local coordinators: " + tCoordinators.size());
}
/**
* Copy list of inferior local coordinators
*/
LinkedList<Coordinator> tOldInferiorLocalCoordinators = null;
synchronized (mInferiorLocalCoordinators) {
tOldInferiorLocalCoordinators = (LinkedList<Coordinator>) mInferiorLocalCoordinators.clone();
}
/**
* Iterate over all found inferior local coordinators
*/
synchronized (tOldInferiorLocalCoordinators) {
if(mCountDistributeMembershipRequests > 1){
if(HRMConfig.DebugOutput.SHOW_CLUSTERING_STEPS){
Logging.log(this, " ..having connections to these inferior local coordinators: " + tOldInferiorLocalCoordinators.toString());
}
}
for (Coordinator tCoordinator : tCoordinators){
if (!tOldInferiorLocalCoordinators.contains(tCoordinator)){
if(HRMConfig.DebugOutput.SHOW_CLUSTERING_STEPS){
Logging.log(this, " ..found inferior local coordinator [NEW]: " + tCoordinator);
}
// add this local coordinator to the list of connected coordinators
synchronized (mInferiorLocalCoordinators) {
if(!mInferiorLocalCoordinators.contains(tCoordinator)){
mInferiorLocalCoordinators.add(tCoordinator);
}else{
Logging.err(this, "Cannot add a duplicate of the local inferior coordinator: " + tCoordinator);
}
}
if(HRMConfig.DebugOutput.SHOW_CLUSTERING_STEPS){
Logging.log(this, " ..get/create communication session");
}
ComSession tComSession = mHRMController.getCreateComSession(mHRMController.getNodeL2Address());
if (tComSession != null){
/**
* Create coordinator name for this coordinator
*/
ClusterName tRemoteEndPointName = tCoordinator.createCoordinatorName();
ClusterName tLocalEndPointName = new ClusterName(mHRMController, tRemoteEndPointName.getHierarchyLevel().inc() /* at the remote side, a CoordinatorAsClusterMember is always located at one hierarchy level above the original coordinator object */, tRemoteEndPointName.getClusterID(), tRemoteEndPointName.getCoordinatorID());
/**
* Establish the comm. channel
*/
establishComChannel(tComSession, tRemoteEndPointName, tLocalEndPointName, tCoordinator);
}else{
Logging.err(this, "distributeMembershipRequests() couldn't determine the comm. session to: " + mHRMController.getNodeName() + " for local coordinator: " + tCoordinator);
}
}else{
if(HRMConfig.DebugOutput.SHOW_CLUSTERING_STEPS){
Logging.log(this, " ..found inferior local coordinator [already connected]: " + tCoordinator);
}
}
}
if(HRMConfig.DebugOutput.SHOW_CLUSTERING_STEPS){
Logging.log(this, " ..finished clustering of local inferior coordinators");
}
/************************************
* Requests for remote coordinators
************************************/
if(mInferiorLocalCoordinators.size() > 0){
if(HRMConfig.DebugOutput.SHOW_CLUSTERING_STEPS){
Logging.log(this, "\n\n\n################ REQUESTING MEMBERSHIP FOR REMOTE COORDINATORS STARTED");
}
LinkedList<CoordinatorProxy> tCoordinatorProxies = mHRMController.getAllCoordinatorProxies(getHierarchyLevel().getValue() - 1);
if(HRMConfig.DebugOutput.SHOW_CLUSTERING_STEPS){
Logging.log(this, " ..inferior remote coordinators: " + tCoordinatorProxies.size());
}
if(tCoordinatorProxies.size() > 0){
/**
* Copy list of inferior local coordinators
*/
LinkedList<Coordinator> tOldInferiorRemoteCoordinators = null;
synchronized (mInferiorRemoteCoordinators) {
tOldInferiorRemoteCoordinators = (LinkedList<Coordinator>) mInferiorRemoteCoordinators.clone();
}
/**
* Iterate over all found remote coordinators
*/
synchronized (tOldInferiorRemoteCoordinators) {
if(mCountDistributeMembershipRequests > 1){
if(HRMConfig.DebugOutput.SHOW_CLUSTERING_STEPS){
Logging.log(this, " ..having connections to these inferior remote coordinators: " + tOldInferiorRemoteCoordinators.toString());
}
}
for (CoordinatorProxy tCoordinatorProxy : tCoordinatorProxies){
if (!tOldInferiorRemoteCoordinators.contains(tCoordinatorProxy)){
if(HRMConfig.DebugOutput.SHOW_CLUSTERING_STEPS){
Logging.log(this, " ..found remote inferior coordinator[NEW]: " + tCoordinatorProxy);
}
// add this remote coordinator to the list of connected coordinators
synchronized (mInferiorRemoteCoordinators) {
if(!mInferiorRemoteCoordinators.contains(tCoordinatorProxy)){
mInferiorRemoteCoordinators.add(tCoordinatorProxy);
}else{
Logging.err(this, "Cannot add a duplicate of the remote inferior coordinator: " + tCoordinatorProxy);
}
}
ComSession tComSession = mHRMController.getCreateComSession(tCoordinatorProxy.getCoordinatorNodeL2Address());
if (tComSession != null){
/**
* Create coordinator name for this coordinator proxy
*/
ClusterName tRemoteEndPointName = tCoordinatorProxy.createCoordinatorName();
ClusterName tLocalEndPointName = new ClusterName(mHRMController, tRemoteEndPointName.getHierarchyLevel().inc() /* at the remote side, a CoordinatorAsClusterMember is always located at one hierarchy level above the original coordinator object */, tRemoteEndPointName.getClusterID(), tRemoteEndPointName.getCoordinatorID());
/**
* Establish the comm. channel
*/
establishComChannel(tComSession, tRemoteEndPointName, tLocalEndPointName, tCoordinatorProxy);
}else{
Logging.err(this, "distributeMembershipRequests() couldn't determine the comm. session to: " + mHRMController.getNodeName() + " for remote coordinator: " + tCoordinatorProxy);
}
}else{
if(HRMConfig.DebugOutput.SHOW_CLUSTERING_STEPS){
Logging.log(this, " ..found inferior remote coordinator [already connected]: " + tCoordinatorProxy);
}
}
}
}
}else{
/**
* Trigger: detected local isolation
*/
eventDetectedIsolation();
}
}else{
if(HRMConfig.DebugOutput.SHOW_CLUSTERING_STEPS){
Logging.log(this, " ..no local inferior coordinators existing");
}
}
}
}else{
Logging.warn(this, "distributeMembershipRequests() skipped because cluster role is already invalidated");
}
// finally, check the necessity of this cluster again
checkClusterNecessity();
}
|
diff --git a/CS425MP2/src/Machine.java b/CS425MP2/src/Machine.java
index fe863f8..a2e8527 100644
--- a/CS425MP2/src/Machine.java
+++ b/CS425MP2/src/Machine.java
@@ -1,318 +1,319 @@
import java.io.*;
import java.net.*;
import java.util.HashMap;
import java.util.Vector;
import java.io.ByteArrayInputStream;
import querier.Server;
public class Machine {
public HashMap<String, Vector<String>> file_node_map;
public HashMap<String, Vector<String>> node_file_map;
public Vector<String> myFileList;
public static final int MEMBERSHIP_PORT = 8889;
public static final int FILE_OPERATIONS_PORT = 8891;
public static final int FILE_TRANSFER_PORT = 8892;
//public static final int DEFAULT_CONTACT_PORT = 8888;
public static final int HEARTBEAT_PORT = 8890;
public static final int QUERY_PORT = 10000;
public DatagramSocket membership_sock;
public DatagramSocket heartbeat_sock=null;
public DatagramSocket filerep_sock;
//public DatagramSocket outgoing;
public Vector<String> memberList;
//private String contactIP;
public String myName;
public String masterName;
public boolean master = false;
public FileReplication FileReplicator;
public Machine(boolean mflag) {
master = mflag;
membership_sock = null;
//outgoing = null;
memberList = null;
myFileList = null;
if (master)
file_node_map = new HashMap<String, Vector<String>>();
node_file_map = new HashMap<String, Vector<String>>();
try {
//myIP = InetAddress.getLocalHost().getHostAddress();
myName = InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
public Machine() {
membership_sock = null;
//outgoing = null;
memberList = null;
myFileList = null;
if (master)
file_node_map = new HashMap<String, Vector<String>>();
node_file_map = new HashMap<String, Vector<String>>();
try {
//myIP = InetAddress.getLocalHost().getHostAddress();
myName = InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
/**
* get memberlist from the connecting contact
*
* @param ip
* contact machine ip
* @param port
* port number
*/
@SuppressWarnings("unchecked")
public void getMemberlistFromIP(String ip) {
String joinMsg;
byte[] joinbaos=null;
joinMsg = 'J'+myName;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(joinMsg);
oos.flush();
joinbaos = baos.toByteArray();
} catch(IOException e) {
e.printStackTrace();
}
sendMsg(membership_sock, ip, joinbaos, Machine.MEMBERSHIP_PORT);
DatagramPacket recvPacket;
byte[] recvData = new byte[1024];
try {
recvPacket = new DatagramPacket(recvData,recvData.length);
membership_sock.receive(recvPacket);
//TODO - need to decide whether we need to define this length or not!!
ByteArrayInputStream bais = new ByteArrayInputStream(recvData);
ObjectInputStream ois = new ObjectInputStream(bais);
memberList = (Vector<String>)ois.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
WriteLog.writelog(myName, "received ML");
WriteLog.printList2Log(myName, memberList);
} catch (IOException e) {
e.printStackTrace();
}
//recvMsg = new String(recvPacket.getData());
//need to review - need to set memberlist using recvPkt
}
/**
* send an add message to the first machine in the system
*/
@SuppressWarnings("resource")
public void sendMsg(DatagramSocket sock, String ip, byte[] msg, int portN) {
try {
InetAddress ipAddr = InetAddress.getByName(ip);
//byte[] sendData = msg.getBytes();
DatagramPacket sendPacket = new DatagramPacket(msg,
msg.length, ipAddr, portN);
sock.send(sendPacket);
} catch (SocketException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* get msg string from UDP
*
* @return
*/
public String recvStrMsg() {
DatagramPacket recvPacket;
String recvMsg = null;
byte[] recvData = new byte[1024];
//recvPacket = new DatagramPacket(recvData,recvData.length);
try {
recvPacket = new DatagramPacket(recvData,recvData.length);
membership_sock.receive(recvPacket);
//TODO - need to decide whether we need to define this length or not!!
ByteArrayInputStream bais = new ByteArrayInputStream(recvData);
ObjectInputStream ois = new ObjectInputStream(bais);
recvMsg = (String)ois.readObject();
WriteLog.writelog(myName, "received from UDP "+recvMsg);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return recvMsg;
}
public void sendMsgToAllNodes(String nodeIP, String cmd)
{
String addOrRemMsg = null;
byte[] fmsg = null;
if (cmd == "ADD")
addOrRemMsg = 'A'+nodeIP;
else if (cmd == "REM")
addOrRemMsg = 'R'+nodeIP;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(addOrRemMsg);
oos.flush();
fmsg= baos.toByteArray();
//fmsg = baos.toString();
} catch(IOException e) {
e.printStackTrace();
}
for (String tempIP : memberList)
{
sendMsg(membership_sock, tempIP, fmsg, Machine.MEMBERSHIP_PORT);
}
}
/**
* start the server socket and listen to membership_sock connection request
*/
public void startAddRem() {
Runnable runnable = new ContactAddRemove(this);
Thread thread = new Thread(runnable);
thread.start();
}
public void startFileReplication() {
FileReplicator = new FileReplication(this);
FileReplicator.start();
}
public static void main(String[] args) {
boolean mflag = false;
Machine m;
if (args.length == 2) {
mflag = args[1].equals("mastermode");
m = new Machine(mflag);
} else {
m = new Machine();
}
m.memberList = new Vector<String>();
m.myFileList = new Vector<String>();
System.out.println("in machine main: program started!!");
try {
m.membership_sock = new DatagramSocket(Machine.MEMBERSHIP_PORT);
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//join
if (m.master)
{
//TODO - need to review the file_node_map.put call
m.masterName = m.myName;
m.memberList.add(m.myName);
//m.file_node_map.put(null, m.memberList);
- m.node_file_map.put(m.myName, null);
+ Vector<String> emptyList = new Vector<String>();
+ m.node_file_map.put(m.myName, emptyList);
m.startAddRem();
}
else
{
m.masterName = args[0];
m.getMemberlistFromIP(args[0]);
m.startAddRem();
}
// r (String s : m.getMemberList())
// System.out.println(s);
m.startFileReplication();
try {
WriteLog.printList2Log(m.myName, m.memberList);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Runnable runnableS = new HeartbeatSender(m);
Thread threadS = new Thread(runnableS);
threadS.start();
Runnable runnableR = new HeartbeatReceiver(m);
Thread threadR = new Thread(runnableR);
threadR.start();
Runnable commandC = new VoluntaryLeave(m);
Thread threadC = new Thread(commandC);
threadC.start();
}
public DatagramSocket getmembership_sock() {
return membership_sock;
}
public void setmembership_sock(DatagramSocket membership_sock) {
this.membership_sock = membership_sock;
}
//public DatagramSocket getOutgoing() {
// return outgoing;
//}
//public void setOutgoing(DatagramSocket outgoing) {
// this.outgoing = outgoing;
//}
public Vector<String> getMemberList() {
return memberList;
}
public void setMemberList(Vector<String> memberList) {
this.memberList = memberList;
}
public String getContactName() {
return masterName;
}
public void setContactName(String contactIP) {
this.masterName = contactIP;
}
public String getMyName() {
return myName;
}
public void setMyName(String myIP) {
this.myName = myIP;
}
}
| true | true | public static void main(String[] args) {
boolean mflag = false;
Machine m;
if (args.length == 2) {
mflag = args[1].equals("mastermode");
m = new Machine(mflag);
} else {
m = new Machine();
}
m.memberList = new Vector<String>();
m.myFileList = new Vector<String>();
System.out.println("in machine main: program started!!");
try {
m.membership_sock = new DatagramSocket(Machine.MEMBERSHIP_PORT);
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//join
if (m.master)
{
//TODO - need to review the file_node_map.put call
m.masterName = m.myName;
m.memberList.add(m.myName);
//m.file_node_map.put(null, m.memberList);
m.node_file_map.put(m.myName, null);
m.startAddRem();
}
else
{
m.masterName = args[0];
m.getMemberlistFromIP(args[0]);
m.startAddRem();
}
// r (String s : m.getMemberList())
// System.out.println(s);
m.startFileReplication();
try {
WriteLog.printList2Log(m.myName, m.memberList);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Runnable runnableS = new HeartbeatSender(m);
Thread threadS = new Thread(runnableS);
threadS.start();
Runnable runnableR = new HeartbeatReceiver(m);
Thread threadR = new Thread(runnableR);
threadR.start();
Runnable commandC = new VoluntaryLeave(m);
Thread threadC = new Thread(commandC);
threadC.start();
}
| public static void main(String[] args) {
boolean mflag = false;
Machine m;
if (args.length == 2) {
mflag = args[1].equals("mastermode");
m = new Machine(mflag);
} else {
m = new Machine();
}
m.memberList = new Vector<String>();
m.myFileList = new Vector<String>();
System.out.println("in machine main: program started!!");
try {
m.membership_sock = new DatagramSocket(Machine.MEMBERSHIP_PORT);
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//join
if (m.master)
{
//TODO - need to review the file_node_map.put call
m.masterName = m.myName;
m.memberList.add(m.myName);
//m.file_node_map.put(null, m.memberList);
Vector<String> emptyList = new Vector<String>();
m.node_file_map.put(m.myName, emptyList);
m.startAddRem();
}
else
{
m.masterName = args[0];
m.getMemberlistFromIP(args[0]);
m.startAddRem();
}
// r (String s : m.getMemberList())
// System.out.println(s);
m.startFileReplication();
try {
WriteLog.printList2Log(m.myName, m.memberList);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Runnable runnableS = new HeartbeatSender(m);
Thread threadS = new Thread(runnableS);
threadS.start();
Runnable runnableR = new HeartbeatReceiver(m);
Thread threadR = new Thread(runnableR);
threadR.start();
Runnable commandC = new VoluntaryLeave(m);
Thread threadC = new Thread(commandC);
threadC.start();
}
|
diff --git a/src/main/java/javax/time/calendar/LocalDate.java b/src/main/java/javax/time/calendar/LocalDate.java
index 1843aaff..17d46b89 100644
--- a/src/main/java/javax/time/calendar/LocalDate.java
+++ b/src/main/java/javax/time/calendar/LocalDate.java
@@ -1,1077 +1,1075 @@
/*
* Copyright (c) 2007,2008, Stephen Colebourne & Michael Nascimento Santos
*
* 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 JSR-310 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 javax.time.calendar;
import java.io.Serializable;
import javax.time.CalendricalException;
import javax.time.MathUtils;
import javax.time.calendar.field.DayOfMonth;
import javax.time.calendar.field.DayOfWeek;
import javax.time.calendar.field.DayOfYear;
import javax.time.calendar.field.MonthOfYear;
import javax.time.calendar.field.Year;
import javax.time.period.PeriodView;
import javax.time.period.Periods;
/**
* A date without a time zone in the ISO-8601 calendar system,
* such as '2007-12-03'.
* <p>
* LocalDate is an immutable calendrical that represents a date, often viewed
* as year-month-day. This object can also access other date fields such as
* day of year, day of week and week of year.
* <p>
* This class does not store or represent a time or time zone.
* Thus, for example, the value "2nd October 2007" can be stored in a LocalDate.
* <p>
* The ISO-8601 calendar system is the modern civil calendar system used today
* in most of the world. It is equivalent to the proleptic Gregorian calendar
* system, in which todays's rules for leap years are applied for all time.
* For most applications written today, the ISO-8601 rules are entirely suitable.
* <p>
* However, any application that makes use of historical dates and requires them
* to be accurate will find the ISO-8601 rules unsuitable. In this case, the
* application code should use <code>HistoricDate</code> and define an explicit
* cutover date between the Julian and Gregorian calendar systems.
* <p>
* LocalDate is thread-safe and immutable.
*
* @author Michael Nascimento Santos
* @author Stephen Colebourne
*/
public final class LocalDate
implements Calendrical, DateProvider, DateMatcher, DateAdjustor, Comparable<LocalDate>, Serializable {
/**
* A serialization identifier for this class.
*/
private static final long serialVersionUID = 798274969L;
/**
* The year, not null.
*/
private final Year year;
/**
* The month of year, not null.
*/
private final MonthOfYear month;
/**
* The day of month, not null.
*/
private final DayOfMonth day;
//-----------------------------------------------------------------------
/**
* Obtains an instance of <code>LocalDate</code> from a year, month and day.
*
* @param year the year to represent, not null
* @param monthOfYear the month of year to represent, not null
* @param dayOfMonth the day of month to represent, not null
* @return a LocalDate object, never null
* @throws InvalidCalendarFieldException if the day of month is invalid for the month-year
*/
public static LocalDate date(Year year, MonthOfYear monthOfYear, DayOfMonth dayOfMonth) {
if (year == null) {
throw new NullPointerException("Year must not be null");
}
if (monthOfYear == null) {
throw new NullPointerException("MonthOfYear must not be null");
}
if (dayOfMonth == null) {
throw new NullPointerException("DayOfMonth must not be null");
}
if (dayOfMonth.isValid(year, monthOfYear) == false) {
if (dayOfMonth.getValue() == 29) {
throw new InvalidCalendarFieldException("Illegal value for DayOfMonth field, value 29 is not valid as " +
year + " is not a leap year", DayOfMonth.rule());
} else {
throw new InvalidCalendarFieldException("Illegal value for DayOfMonth field, value " + dayOfMonth.getValue() +
" is not valid for month " + monthOfYear.name(), DayOfMonth.rule());
}
}
return new LocalDate(year, monthOfYear, dayOfMonth);
}
/**
* Obtains an instance of <code>LocalDate</code> from a year, month and day.
*
* @param year the year to represent, from MIN_YEAR to MAX_YEAR
* @param monthOfYear the month of year to represent, not null
* @param dayOfMonth the day of month to represent, from 1 to 31
* @return a LocalDate object, never null
* @throws IllegalCalendarFieldValueException if the value of any field is out of range
* @throws InvalidCalendarFieldException if the day of month is invalid for the month-year
*/
public static LocalDate date(int year, MonthOfYear monthOfYear, int dayOfMonth) {
return date(Year.isoYear(year), monthOfYear, DayOfMonth.dayOfMonth(dayOfMonth));
}
/**
* Obtains an instance of <code>LocalDate</code> from a year, month and day.
*
* @param year the year to represent, from MIN_YEAR to MAX_YEAR
* @param monthOfYear the month of year to represent, from 1 (January) to 12 (December)
* @param dayOfMonth the day of month to represent, from 1 to 31
* @return a LocalDate object, never null
* @throws IllegalCalendarFieldValueException if the value of any field is out of range
* @throws InvalidCalendarFieldException if the day of month is invalid for the month-year
*/
public static LocalDate date(int year, int monthOfYear, int dayOfMonth) {
return date(Year.isoYear(year), MonthOfYear.monthOfYear(monthOfYear), DayOfMonth.dayOfMonth(dayOfMonth));
}
/**
* Obtains an instance of <code>LocalDate</code> from a date provider.
*
* @param dateProvider the date provider to use, not null
* @return a LocalDate object, never null
*/
public static LocalDate date(DateProvider dateProvider) {
if (dateProvider == null) {
throw new NullPointerException("DateProvider must not be null");
}
LocalDate result = dateProvider.toLocalDate();
if (result == null) {
throw new NullPointerException("The DateProvider implementation must not return null");
}
return result;
}
/**
* Obtains an instance of <code>LocalDate</code> from a modified julian days.
*
* @param mjDays the modified julian day equivalent to the LocalDate
* @return a LocalDate object, never null
* @throws CalendarConversionException if the modified julian days value is outside the supported range
*/
public static LocalDate fromModifiedJulianDays(long mjDays) {
long total = mjDays + 678941;
long y = 0;
long leapYearCount = 0;
int yearLength = -1;
do {
y += total / 365;
total %= 365;
total += leapYearCount;
if (y >= 0) {
leapYearCount = (y + 3) / 4 - (y + 99) / 100 + (y + 399) / 400;
} else {
leapYearCount = y / 4 - y / 100 + y / 400;
}
total -= leapYearCount;
if (total < 0 && total / -365 == 0) {
y--;
yearLength = 365 + (((y & 3) == 0) && ((y % 100) != 0 || (y % 400) == 0) ? 1 : 0);
total = total % -365 + yearLength;
} else if (total >= 365) {
yearLength = 365 + (((y & 3) == 0) && ((y % 100) != 0 || (y % 400) == 0) ? 1 : 0);
}
} while (total < 0 || (yearLength != -1 && total >= yearLength));
int yAsInt = 0;
try {
yAsInt = MathUtils.safeToInt(y);
} catch (ArithmeticException ae) {
- if (mjDays < 0) {
- throw new CalendarConversionException("Cannot create LocalDate from modified julian days as value " +
- mjDays + " is outside the supported range of years");
- }
+ throw new CalendarConversionException("Cannot create LocalDate from modified julian days as value " +
+ mjDays + " is outside the supported range of years");
}
Year year = Year.isoYear(yAsInt);
MonthOfYear month = MonthOfYear.JANUARY;
int monthLength;
while (total > (monthLength = month.lengthInDays(year)) - 1) {
total -= monthLength;
month = month.next();
}
return new LocalDate(year, month, DayOfMonth.dayOfMonth(MathUtils.safeToInt(total) + 1));
}
//-----------------------------------------------------------------------
/**
* Constructor, previously validated.
*
* @param year the year to represent, not null
* @param monthOfYear the month of year to represent, not null
* @param dayOfMonth the day of month to represent, valid for year-month, not null
*/
private LocalDate(Year year, MonthOfYear monthOfYear, DayOfMonth dayOfMonth) {
this.year = year;
this.month = monthOfYear;
this.day = dayOfMonth;
}
//-----------------------------------------------------------------------
/**
* Gets the chronology that describes the calendar system rules for
* this date.
*
* @return the ISO chronology, never null
*/
public ISOChronology getChronology() {
return ISOChronology.INSTANCE;
}
//-----------------------------------------------------------------------
/**
* Checks if the specified calendar field is supported.
* <p>
* This method queries whether this <code>LocalDate</code> can
* be queried using the specified calendar field.
*
* @param field the field to query, not null
* @return true if the field is supported
*/
public boolean isSupported(DateTimeFieldRule field) {
return field.isSupported(Periods.DAYS, Periods.FOREVER);
}
/**
* Gets the value of the specified calendar field.
* <p>
* This method queries the value of the specified calendar field.
* If the calendar field is not supported then an exception is thrown.
*
* @param field the field to query, not null
* @return the value for the field
* @throws UnsupportedCalendarFieldException if no value for the field is found
* @throws InvalidCalendarFieldException if the value for the field is invalid
*/
public int get(DateTimeFieldRule field) {
return toFlexiDateTime().getValue(field);
}
//-----------------------------------------------------------------------
/**
* Gets an instance of <code>YearMonth</code> initialised to the
* year and month of this date.
*
* @return the year-month object, never null
*/
public YearMonth getYearMonth() {
return YearMonth.yearMonth(year, month);
}
/**
* Gets an instance of <code>MonthDay</code> initialised to the
* month and day of month of this date.
*
* @return the month-day object, never null
*/
public MonthDay getMonthDay() {
return MonthDay.monthDay(month, day);
}
//-----------------------------------------------------------------------
/**
* Gets the year field.
* <p>
* This method provides access to an object representing the year field.
* This can be used to access the {@link Year#getValue() int value}.
*
* @return the year, never null
*/
public Year getYear() {
return year;
}
/**
* Gets the month of year field.
* <p>
* This method provides access to an object representing the month field.
* This can be used to access the {@link MonthOfYear#getValue() int value}.
*
* @return the month of year, never null
*/
public MonthOfYear getMonthOfYear() {
return month;
}
/**
* Gets the day of month field.
* <p>
* This method provides access to an object representing the day of month field.
* This can be used to access the {@link DayOfMonth#getValue() int value}.
*
* @return the day of month, never null
*/
public DayOfMonth getDayOfMonth() {
return day;
}
/**
* Gets the day of year field.
* <p>
* This method provides access to an object representing the day of year field.
* This can be used to access the {@link DayOfYear#getValue() int value}.
*
* @return the day of year, never null
*/
public DayOfYear getDayOfYear() {
return DayOfYear.dayOfYear(this);
}
/**
* Gets the day of week field.
* <p>
* This method provides access to an object representing the day of week field.
* This can be used to access the {@link DayOfWeek#getValue() int value}.
*
* @return the day of week, never null
*/
public DayOfWeek getDayOfWeek() {
return DayOfWeek.dayOfWeek(this);
}
//-----------------------------------------------------------------------
/**
* Resolves the date, handling incorrcetly implemented resolvers.
*
* @param dateResolver the resolver, not null
* @param year the year, not null
* @param month the month, not null
* @param day the day of month, not null
* @return the resolved date, never null
* @throws NullPointerException if the resolver returned null
*/
private LocalDate resolveDate(DateResolver dateResolver, Year year, MonthOfYear month, DayOfMonth day) {
LocalDate date = dateResolver.resolveDate(year, month, day);
if (date == null) {
throw new NullPointerException("The implementation of DateResolver must not return null");
}
return date;
}
/**
* Returns a copy of this LocalDate with the date altered using the adjustor.
* <p>
* Adjustors can be used to alter the date in unusual ways. Examples might
* be an adjustor that set the date avoiding weekends, or one that sets the
* date to the last day of the month.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param adjustor the adjustor to use, not null
* @return a new updated LocalDate, never null
*/
public LocalDate with(DateAdjustor adjustor) {
LocalDate date = adjustor.adjustDate(this);
if (date == null) {
throw new NullPointerException("The implementation of DateAdjustor must not return null");
}
return date;
}
/**
* Returns a copy of this LocalDate with the year value altered.
* If the resulting <code>LocalDate</code> is invalid, it will be resolved using {@link DateResolvers#previousValid()}.
* <p>
* This method does the same as <code>withYear(year, DateResolvers.previousValid())</code>.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param year the year to represent, from MIN_YEAR to MAX_YEAR
* @return a new updated LocalDate, never null
* @throws IllegalCalendarFieldValueException if the year value is invalid
* @see #withYear(int,DateResolver)
*/
public LocalDate withYear(int year) {
return withYear(year, DateResolvers.previousValid());
}
/**
* Returns a copy of this LocalDate with the year value altered.
* If the resulting <code>LocalDate</code> is invalid, it will be resolved using <code>dateResolver</code>.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param year the year to represent, from MIN_YEAR to MAX_YEAR
* @param dateResolver the DateResolver to be used if the resulting date would be invalid
* @return a new updated LocalDate, never null
* @throws IllegalCalendarFieldValueException if the year value is invalid
*/
public LocalDate withYear(int year, DateResolver dateResolver) {
if (this.year.getValue() == year) {
return this;
}
return resolveDate(dateResolver, Year.isoYear(year), month, day);
}
/**
* Returns a copy of this LocalDate with the month of year value altered.
* If the resulting <code>LocalDate</code> is invalid, it will be resolved using {@link DateResolvers#previousValid()}.
* <p>
* This method does the same as <code>withMonthOfYear(monthOfYear, DateResolvers.previousValid())</code>.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param monthOfYear the month of year to represent, from 1 (January) to 12 (December)
* @return a new updated LocalDate, never null
* @throws IllegalCalendarFieldValueException if the month of year value is invalid
* @see #withMonthOfYear(int,DateResolver)
*/
public LocalDate withMonthOfYear(int monthOfYear) {
return withMonthOfYear(monthOfYear, DateResolvers.previousValid());
}
/**
* Returns a copy of this LocalDate with the month of year value altered.
* If the resulting <code>LocalDate</code> is invalid, it will be resolved using <code>dateResolver</code>.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param monthOfYear the month of year to represent, from 1 (January) to 12 (December)
* @param dateResolver the DateResolver to be used if the resulting date would be invalid
* @return a new updated LocalDate, never null
* @throws IllegalCalendarFieldValueException if the month of year value is invalid
*/
public LocalDate withMonthOfYear(int monthOfYear, DateResolver dateResolver) {
if (this.month.getValue() == monthOfYear) {
return this;
}
return resolveDate(dateResolver, year, MonthOfYear.monthOfYear(monthOfYear), day);
}
/**
* Returns a copy of this LocalDate with the day of month value altered.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param dayOfMonth the day of month to represent, from 1 to 28-31
* @return a new updated LocalDate, never null
* @throws IllegalCalendarFieldValueException if the day of month value is invalid
* @throws InvalidCalendarFieldException if the day of month is invalid for the month-year
*/
public LocalDate withDayOfMonth(int dayOfMonth) {
if (this.day.getValue() == dayOfMonth) {
return this;
}
return date(year, month, DayOfMonth.dayOfMonth(dayOfMonth));
}
//-----------------------------------------------------------------------
/**
* Returns a copy of this LocalDate with the specified period added.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param period the period to add, not null
* @return a new updated LocalDate, never null
* @throws CalendricalException if the result exceeds the supported date range
*/
public LocalDate plus(PeriodView period) {
// TODO
return null;
}
/**
* Returns a copy of this LocalDate with the specified periods added.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param periods the periods to add, no nulls
* @return a new updated LocalDate, never null
* @throws CalendricalException if the result exceeds the supported date range
*/
public LocalDate plus(PeriodView... periods) {
// TODO
return null;
}
//-----------------------------------------------------------------------
/**
* Returns a copy of this LocalDate with the specified period in years added.
* <p>
* This method add the specified amount to the years field in three steps:
* <ol>
* <li>Add the input years to the year field</li>
* <li>Check if the resulting date would be invalid</li>
* <li>Adjust the day of month to the last valid day if necessary</li>
* </ol>
* <p>
* For example, 2008-02-29 (leap year) plus one year would result in the
* invalid date 2009-02-29 (standard year). Instead of returning an invalid
* result, the last valid day of the month, 2009-02-28, is selected instead.
* <p>
* This method does the same as <code>plusYears(years, DateResolvers.previousValid())</code>.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param years the years to add, may be negative
* @return a new updated LocalDate, never null
* @throws CalendricalException if the result exceeds the supported date range
* @see #plusYears(int, javax.time.calendar.DateResolver)
*/
public LocalDate plusYears(int years) {
return plusYears(years, DateResolvers.previousValid());
}
/**
* Returns a copy of this LocalDate with the specified period in years added.
* <p>
* This method add the specified amount to the years field in three steps:
* <ol>
* <li>Add the input years to the year field</li>
* <li>Check if the resulting date would be invalid</li>
* <li>Adjust the date using <code>dateResolver</code> if necessary</li>
* </ol>
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param years the years to add, may be negative
* @param dateResolver the DateResolver to be used if the resulting date would be invalid
* @return a new updated LocalDate, never null
* @throws CalendricalException if the result exceeds the supported date range
*/
public LocalDate plusYears(int years, DateResolver dateResolver) {
if (years == 0) {
return this;
}
Year newYear = year.plusYears(years);
return resolveDate(dateResolver, newYear, month, day);
}
/**
* Returns a copy of this LocalDate with the specified period in months added.
* <p>
* This method add the specified amount to the months field in three steps:
* <ol>
* <li>Add the input months to the month of year field</li>
* <li>Check if the resulting date would be invalid</li>
* <li>Adjust the day of month to the last valid day if necessary</li>
* </ol>
* <p>
* For example, 2007-03-31 plus one month would result in the invalid date
* 2007-04-31. Instead of returning an invalid result, the last valid day
* of the month, 2007-04-30, is selected instead.
* <p>
* This method does the same as <code>plusMonts(months, DateResolvers.previousValid())</code>.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param months the months to add, may be negative
* @return a new updated LocalDate, never null
* @throws CalendricalException if the result exceeds the supported date range
* @see #plusMonths(int, javax.time.calendar.DateResolver)
*/
public LocalDate plusMonths(int months) {
return plusMonths(months, DateResolvers.previousValid());
}
/**
* Returns a copy of this LocalDate with the specified period in months added.
* <p>
* This method add the specified amount to the months field in three steps:
* <ol>
* <li>Add the input months to the month of year field</li>
* <li>Check if the resulting date would be invalid</li>
* <li>Adjust the date using <code>dateResolver</code> if necessary</li>
* </ol>
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param months the months to add, may be negative
* @param dateResolver the DateResolver to be used if the resulting date would be invalid
* @return a new updated LocalDate, never null
* @throws CalendricalException if the result exceeds the supported date range
*/
public LocalDate plusMonths(int months, DateResolver dateResolver) {
if (months == 0) {
return this;
}
long newMonth0 = month.getValue() - 1;
newMonth0 = newMonth0 + months;
int years = (int) (newMonth0 / 12);
newMonth0 = newMonth0 % 12;
if (newMonth0 < 0) {
newMonth0 += 12;
years = MathUtils.safeDecrement(years);
}
Year newYear = year.plusYears(years);
MonthOfYear newMonth = MonthOfYear.monthOfYear((int) ++newMonth0);
return resolveDate(dateResolver, newYear, newMonth, day);
}
/**
* Returns a copy of this LocalDate with the specified period in weeks added.
* <p>
* This method add the specified amount in weeks to the days field incrementing
* the month and year fields as necessary to ensure the result remains valid.
* The result is only invalid if the maximum/minimum year is exceeded.
* <p>
* For example, 2008-12-31 plus one week would result in the 2009-01-07.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param weeks the weeks to add, may be negative
* @return a new updated LocalDate, never null
* @throws CalendricalException if the result exceeds the supported date range
*/
public LocalDate plusWeeks(int weeks) {
return plusDays(7L * weeks);
}
/**
* Returns a copy of this LocalDate with the specified number of days added.
* <p>
* This method add the specified amount to the days field incrementing the
* month and year fields as necessary to ensure the result remains valid.
* The result is only invalid if the maximum/minimum year is exceeded.
* <p>
* For example, 2008-12-31 plus one day would result in the 2009-01-01.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param days the days to add, may be negative
* @return a new updated LocalDate, never null
* @throws CalendricalException if the result exceeds the supported date range
*/
public LocalDate plusDays(long days) {
if (days == 0) {
return this;
}
long mjDays = toModifiedJulianDays();
try {
mjDays = MathUtils.safeAdd(mjDays, days);
} catch (ArithmeticException ae) {
throw new CalendricalException(this + " + " + days + " days exceeds the current capacity");
}
return LocalDate.fromModifiedJulianDays(mjDays);
}
//-----------------------------------------------------------------------
/**
* Returns a copy of this LocalDate with the specified period subtracted.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param period the period to subtract, not null
* @return a new updated LocalDate, never null
* @throws CalendricalException if the result exceeds the supported date range
*/
public LocalDate minus(PeriodView period) {
// TODO
return null;
}
/**
* Returns a copy of this LocalDate with the specified periods subtracted.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param periods the periods to subtract, no nulls
* @return a new updated LocalDate, never null
* @throws CalendricalException if the result exceeds the supported date range
*/
public LocalDate minus(PeriodView... periods) {
// TODO
return null;
}
//-----------------------------------------------------------------------
/**
* Returns a copy of this LocalDate with the specified period in years subtracted.
* <p>
* This method subtract the specified amount to the years field in three steps:
* <ol>
* <li>Subtract the input years to the year field</li>
* <li>Check if the resulting date would be invalid</li>
* <li>Adjust the day of month to the last valid day if necessary</li>
* </ol>
* <p>
* For example, 2008-02-29 (leap year) minus one year would result in the
* invalid date 2007-02-29 (standard year). Instead of returning an invalid
* result, the last valid day of the month, 2007-02-28, is selected instead.
* <p>
* This method does the same as <code>minusYears(years, DateResolvers.previousValid())</code>.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param years the years to subtract, may be negative
* @return a new updated LocalDate, never null
* @throws CalendricalException if the result exceeds the supported date range
* @see #minusYears(int, javax.time.calendar.DateResolver)
*/
public LocalDate minusYears(int years) {
return minusYears(years, DateResolvers.previousValid());
}
/**
* Returns a copy of this LocalDate with the specified period in years subtracted.
* <p>
* This method subtract the specified amount to the years field in three steps:
* <ol>
* <li>Subtract the input years to the year field</li>
* <li>Check if the resulting date would be invalid</li>
* <li>Adjust the date using <code>dateResolver</code> if necessary</li>
* </ol>
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param years the years to subtract, may be negative
* @param dateResolver the DateResolver to be used if the resulting date would be invalid
* @return a new updated LocalDate, never null
* @throws CalendricalException if the result exceeds the supported date range
*/
public LocalDate minusYears(int years, DateResolver dateResolver) {
if (years == 0) {
return this;
}
Year newYear = year.minusYears(years);
return resolveDate(dateResolver, newYear, month, day);
}
/**
* Returns a copy of this LocalDate with the specified period in months subtracted.
* <p>
* This method subtract the specified amount to the months field in three steps:
* <ol>
* <li>Subtract the input months to the month of year field</li>
* <li>Check if the resulting date would be invalid</li>
* <li>Adjust the day of month to the last valid day if necessary</li>
* </ol>
* <p>
* For example, 2007-03-31 minus one month would result in the invalid date
* 2007-01-31. Instead of returning an invalid result, the last valid day
* of the month, 2007-02-28, is selected instead.
* <p>
* This method does the same as <code>minusMonts(months, DateResolvers.previousValid())</code>.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param months the months to subtract, may be negative
* @return a new updated LocalDate, never null
* @throws CalendricalException if the result exceeds the supported date range
* @see #minusMonths(int, javax.time.calendar.DateResolver)
*/
public LocalDate minusMonths(int months) {
return minusMonths(months, DateResolvers.previousValid());
}
/**
* Returns a copy of this LocalDate with the specified period in months subtracted.
* <p>
* This method subtract the specified amount to the months field in three steps:
* <ol>
* <li>Subtract the input months to the month of year field</li>
* <li>Check if the resulting date would be invalid</li>
* <li>Adjust the date using <code>dateResolver</code> if necessary</li>
* </ol>
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param months the months to subtract, may be negative
* @param dateResolver the DateResolver to be used if the resulting date would be invalid
* @return a new updated LocalDate, never null
* @throws CalendricalException if the result exceeds the supported date range
*/
public LocalDate minusMonths(int months, DateResolver dateResolver) {
if (months == 0) {
return this;
}
int years = months / 12;
long newMonth0 = month.getValue() - 1;
newMonth0 = newMonth0 - (months % 12);
if (newMonth0 >= 12) {
newMonth0 = newMonth0 % 12;
years = MathUtils.safeDecrement(years);
} else if (newMonth0 < 0) {
newMonth0 += 12;
years = MathUtils.safeIncrement(years);
}
Year newYear = year.minusYears(years);
MonthOfYear newMonth = MonthOfYear.monthOfYear((int) ++newMonth0);
return resolveDate(dateResolver, newYear, newMonth, day);
}
/**
* Returns a copy of this LocalDate with the specified period in weeks subtracted.
* <p>
* This method subtract the specified amount in weeks to the days field decrementing
* the month and year fields as necessary to ensure the result remains valid.
* The result is only invalid if the maximum/minimum year is exceeded.
* <p>
* For example, 2009-01-07 minus one week would result in the 2008-12-31.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param weeks the weeks to subtract, may be negative
* @return a new updated LocalDate, never null
* @throws CalendricalException if the result exceeds the supported date range
*/
public LocalDate minusWeeks(int weeks) {
return minusDays(7L * weeks);
}
/**
* Returns a copy of this LocalDate with the specified number of days subtracted.
* <p>
* This method subtract the specified amount to the days field decrementing the
* month and year fields as necessary to ensure the result remains valid.
* The result is only invalid if the maximum/minimum year is exceeded.
* <p>
* For example, 2009-01-01 minus one day would result in the 2008-12-31.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param days the days to subtract, may be negative
* @return a new updated LocalDate, never null
* @throws CalendricalException if the result exceeds the supported date range
*/
public LocalDate minusDays(long days) {
if (days == 0) {
return this;
}
long mjDays = toModifiedJulianDays();
try {
mjDays = MathUtils.safeSubtract(mjDays, days);
} catch (ArithmeticException ae) {
throw new CalendricalException(this + " - " + days + " days exceeds the current capacity");
}
return LocalDate.fromModifiedJulianDays(mjDays);
}
//-----------------------------------------------------------------------
/**
* Checks whether this date matches the specified matcher.
* <p>
* Matchers can be used to query the date in unusual ways. Examples might
* be a matcher that checks if the date is a weekend or holiday, or
* Friday the Thirteenth.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param matcher the matcher to use, not null
* @return true if this date matches the matcher, false otherwise
*/
public boolean matches(DateMatcher matcher) {
return matcher.matchesDate(this);
}
// //-----------------------------------------------------------------------
// /**
// * Appends the time to this date returning a LocalDateTime.
// * <p>
// * This instance is immutable and unaffected by this method call.
// *
// * @param time the time to append, not null
// * @return the LocalDateTime formed by appending the time to this date, never null
// */
// public LocalDateTime append(LocalTime time) {
// return LocalDateTime.dateTime(this, time);
// }
//-----------------------------------------------------------------------
/**
* Checks if this date is equal to the input date
*
* @param date the date to match, not null
* @return true if the two dates are equal, false otherwise
*/
public boolean matchesDate(LocalDate date) {
return (year.equals(date.year) && month == date.month && day.equals(date.day));
}
/**
* Adjusts a date to have the value of this date.
*
* @param date the date to be adjusted, not null
* @return the adjusted date, never null
*/
public LocalDate adjustDate(LocalDate date) {
return matchesDate(date) ? date : this;
}
//-----------------------------------------------------------------------
/**
* Converts this date to a <code>LocalDate</code>, trivially
* returning <code>this</code>.
*
* @return <code>this</code>, never null
*/
public LocalDate toLocalDate() {
return this;
}
/**
* Converts this date to a <code>FlexiDateTime</code>.
*
* @return the flexible date-time representation for this instance, never null
*/
public FlexiDateTime toFlexiDateTime() {
return new FlexiDateTime(this, null, null, null);
}
//-----------------------------------------------------------------------
/**
* Converts the date to modified julian days (MJD).
*
* @return the modified julian day equivalent to this date
*/
public long toModifiedJulianDays() {
long y = year.getValue();
long m = month.getValue();
long total = 0;
total += 365 * y;
if (y >= 0) {
total += (y + 3) / 4 - (y + 99) / 100 + (y + 399) / 400;
} else {
total -= y / -4 - y / -100 + y / -400;
}
total += ((367 * m - 362) / 12);
total += day.getValue() - 1;
if (m > 2) {
total--;
if (year.isLeap() == false) {
total--;
}
}
return total - 678941;
}
//-----------------------------------------------------------------------
/**
* Compares this date to another date.
*
* @param other the other date to compare to, not null
* @return the comparator value, negative if less, postive if greater
* @throws NullPointerException if <code>other</code> is null
*/
public int compareTo(LocalDate other) {
int cmp = year.compareTo(other.year);
if (cmp == 0) {
cmp = month.compareTo(other.month);
if (cmp == 0) {
cmp = day.compareTo(other.day);
}
}
return cmp;
}
/**
* Is this date after the specified date.
*
* @param other the other date to compare to, not null
* @return true if this is after the specified date
* @throws NullPointerException if <code>other</code> is null
*/
public boolean isAfter(LocalDate other) {
return compareTo(other) > 0;
}
/**
* Is this date before the specified date.
*
* @param other the other date to compare to, not null
* @return true if this point is before the specified date
* @throws NullPointerException if <code>other</code> is null
*/
public boolean isBefore(LocalDate other) {
return compareTo(other) < 0;
}
//-----------------------------------------------------------------------
/**
* Is this date equal to the specified date.
*
* @param other the other date to compare to, null returns false
* @return true if this point is equal to the specified date
*/
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (other instanceof LocalDate) {
LocalDate otherDate = (LocalDate) other;
return matchesDate(otherDate);
}
return false;
}
/**
* A hashcode for this date.
*
* @return a suitable hashcode
*/
@Override
public int hashCode() {
int yearValue = year.getValue();
int monthValue = month.getValue();
int dayValue = day.getValue();
return (yearValue & 0xFFFFF800) ^ ((yearValue << 11) + (monthValue << 6) + (dayValue));
}
//-----------------------------------------------------------------------
/**
* Outputs the date as a <code>String</code>, such as '2007-12-03'.
* <p>
* The output will be in the format 'yyyy-MM-dd'.
*
* @return the formatted date string, never null
*/
@Override
public String toString() {
int yearValue = year.getValue();
int monthValue = month.getValue();
int dayValue = day.getValue();
int absYear = Math.abs(yearValue);
StringBuilder buf = new StringBuilder(12);
if (absYear < 1000) {
if (yearValue < 0) {
buf.append(yearValue - 10000).deleteCharAt(1);
} else {
buf.append(yearValue + 10000).deleteCharAt(0);
}
} else {
buf.append(yearValue);
}
return buf.append(monthValue < 10 ? "-0" : "-")
.append(monthValue)
.append(dayValue < 10 ? "-0" : "-")
.append(dayValue)
.toString();
}
}
| true | true | public static LocalDate fromModifiedJulianDays(long mjDays) {
long total = mjDays + 678941;
long y = 0;
long leapYearCount = 0;
int yearLength = -1;
do {
y += total / 365;
total %= 365;
total += leapYearCount;
if (y >= 0) {
leapYearCount = (y + 3) / 4 - (y + 99) / 100 + (y + 399) / 400;
} else {
leapYearCount = y / 4 - y / 100 + y / 400;
}
total -= leapYearCount;
if (total < 0 && total / -365 == 0) {
y--;
yearLength = 365 + (((y & 3) == 0) && ((y % 100) != 0 || (y % 400) == 0) ? 1 : 0);
total = total % -365 + yearLength;
} else if (total >= 365) {
yearLength = 365 + (((y & 3) == 0) && ((y % 100) != 0 || (y % 400) == 0) ? 1 : 0);
}
} while (total < 0 || (yearLength != -1 && total >= yearLength));
int yAsInt = 0;
try {
yAsInt = MathUtils.safeToInt(y);
} catch (ArithmeticException ae) {
if (mjDays < 0) {
throw new CalendarConversionException("Cannot create LocalDate from modified julian days as value " +
mjDays + " is outside the supported range of years");
}
}
Year year = Year.isoYear(yAsInt);
MonthOfYear month = MonthOfYear.JANUARY;
int monthLength;
while (total > (monthLength = month.lengthInDays(year)) - 1) {
total -= monthLength;
month = month.next();
}
return new LocalDate(year, month, DayOfMonth.dayOfMonth(MathUtils.safeToInt(total) + 1));
}
| public static LocalDate fromModifiedJulianDays(long mjDays) {
long total = mjDays + 678941;
long y = 0;
long leapYearCount = 0;
int yearLength = -1;
do {
y += total / 365;
total %= 365;
total += leapYearCount;
if (y >= 0) {
leapYearCount = (y + 3) / 4 - (y + 99) / 100 + (y + 399) / 400;
} else {
leapYearCount = y / 4 - y / 100 + y / 400;
}
total -= leapYearCount;
if (total < 0 && total / -365 == 0) {
y--;
yearLength = 365 + (((y & 3) == 0) && ((y % 100) != 0 || (y % 400) == 0) ? 1 : 0);
total = total % -365 + yearLength;
} else if (total >= 365) {
yearLength = 365 + (((y & 3) == 0) && ((y % 100) != 0 || (y % 400) == 0) ? 1 : 0);
}
} while (total < 0 || (yearLength != -1 && total >= yearLength));
int yAsInt = 0;
try {
yAsInt = MathUtils.safeToInt(y);
} catch (ArithmeticException ae) {
throw new CalendarConversionException("Cannot create LocalDate from modified julian days as value " +
mjDays + " is outside the supported range of years");
}
Year year = Year.isoYear(yAsInt);
MonthOfYear month = MonthOfYear.JANUARY;
int monthLength;
while (total > (monthLength = month.lengthInDays(year)) - 1) {
total -= monthLength;
month = month.next();
}
return new LocalDate(year, month, DayOfMonth.dayOfMonth(MathUtils.safeToInt(total) + 1));
}
|
diff --git a/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb.persistence/src/org/wso2/developerstudio/eclipse/gmf/esb/internal/persistence/SequenceTransformer.java b/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb.persistence/src/org/wso2/developerstudio/eclipse/gmf/esb/internal/persistence/SequenceTransformer.java
index 4268f4962..a112377d9 100755
--- a/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb.persistence/src/org/wso2/developerstudio/eclipse/gmf/esb/internal/persistence/SequenceTransformer.java
+++ b/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb.persistence/src/org/wso2/developerstudio/eclipse/gmf/esb/internal/persistence/SequenceTransformer.java
@@ -1,160 +1,163 @@
package org.wso2.developerstudio.eclipse.gmf.esb.internal.persistence;
import java.io.File;
import java.util.List;
import org.apache.synapse.endpoints.Endpoint;
import org.apache.synapse.mediators.Value;
import org.apache.synapse.mediators.base.SequenceMediator;
import org.apache.synapse.mediators.builtin.SendMediator;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
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.ui.IEditorPart;
import org.eclipse.ui.IEditorReference;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.PlatformUI;
import org.wso2.developerstudio.eclipse.gmf.esb.AbstractEndPoint;
import org.wso2.developerstudio.eclipse.gmf.esb.AddressEndPoint;
import org.wso2.developerstudio.eclipse.gmf.esb.DefaultEndPoint;
import org.wso2.developerstudio.eclipse.gmf.esb.EsbDiagram;
import org.wso2.developerstudio.eclipse.gmf.esb.EsbElement;
import org.wso2.developerstudio.eclipse.gmf.esb.EsbLink;
import org.wso2.developerstudio.eclipse.gmf.esb.EsbNode;
import org.wso2.developerstudio.eclipse.gmf.esb.InputConnector;
import org.wso2.developerstudio.eclipse.gmf.esb.NamedEndpoint;
import org.wso2.developerstudio.eclipse.gmf.esb.OutputConnector;
import org.wso2.developerstudio.eclipse.gmf.esb.ProxyService;
import org.wso2.developerstudio.eclipse.gmf.esb.Sequence;
import org.wso2.developerstudio.eclipse.gmf.esb.Sequences;
import org.wso2.developerstudio.eclipse.gmf.esb.WSDLEndPoint;
import org.wso2.developerstudio.eclipse.gmf.esb.persistence.EsbNodeTransformer;
import org.wso2.developerstudio.eclipse.gmf.esb.persistence.EsbTransformerRegistry;
import org.wso2.developerstudio.eclipse.gmf.esb.persistence.SequenceInfo;
import org.wso2.developerstudio.eclipse.gmf.esb.persistence.TransformationInfo;
public class SequenceTransformer extends AbstractEsbNodeTransformer{
public void transform(TransformationInfo information, EsbNode subject)
throws Exception {
}
public void createSynapseObject(TransformationInfo info, EObject subject,
List<Endpoint> endPoints) {
}
public void transformWithinSequence(TransformationInfo information,
EsbNode subject, SequenceMediator sequence) throws Exception {
// Check subject.
Assert.isTrue(
subject instanceof org.wso2.developerstudio.eclipse.gmf.esb.Sequences,
"Invalid subject.");
org.wso2.developerstudio.eclipse.gmf.esb.Sequences visualSequence = (org.wso2.developerstudio.eclipse.gmf.esb.Sequences) subject;
EsbLink outgoingLink= visualSequence.getOutputConnector().getOutgoingLink();
doTransformWithinSequence(information, outgoingLink, sequence);
if(visualSequence.isRecieveSequence()){
handleServiceChaining(visualSequence,sequence,visualSequence.getAssociatedProxy());
}
}
private void handleServiceChaining(org.wso2.developerstudio.eclipse.gmf.esb.Sequences visualSequence,SequenceMediator sequence,List proxyNames) throws Exception{
IEditorPart editorPart = null;
IProject activeProject = null;
Sequence currentSequence = null;
IEditorReference editorReferences[] = PlatformUI.getWorkbench()
.getActiveWorkbenchWindow().getActivePage()
.getEditorReferences();
for (int i = 0; i < editorReferences.length; i++) {
IEditorPart editor = editorReferences[i].getEditor(false);
if (editor != null) {
editorPart = editor.getSite().getWorkbenchWindow()
.getActivePage().getActiveEditor();
}
if (editorPart != null) {
IFileEditorInput input = (IFileEditorInput) editorPart
.getEditorInput();
IFile file = input.getFile();
activeProject = file.getProject();
}
}
String name = (String) proxyNames.get(0);
IPath location = new Path("src/main/graphical-synapse-config/proxy-services" + "/" + "proxy_"
+ name + ".esb_diagram");
IFile file = activeProject.getFile(location);
ResourceSet resourceSet = new ResourceSetImpl();
Resource resource = null;
File f = new File(file.getLocationURI().getPath());
URI uri = URI.createFileURI(f.getAbsolutePath());
if (!f.exists()) {
} else {
resource = resourceSet.getResource(uri, true);
EsbDiagram s = (EsbDiagram) ((org.eclipse.gmf.runtime.notation.impl.DiagramImpl) resource
.getContents().get(0)).getElement();
EList<EsbElement> children = s.getServer().getChildren();
for (EsbElement esbElement : children) {
if (esbElement instanceof ProxyService){
ProxyService proxyService = (ProxyService) esbElement;
List<EsbElement> elements = (List<EsbElement>) proxyService.getContainer().getSequenceAndEndpointContainer().getMediatorFlow().getChildren();
for(EsbElement elem:elements){
if((elem instanceof Sequence)&&(((Sequence)elem).getName().equals(visualSequence.getName()))){
currentSequence=(Sequence) elem;
}
}
}
}
OutputConnector source=((EsbLink)currentSequence.getInputConnector().getIncomingLinks().get(0)).getSource();
- InputConnector target = currentSequence.getOutputConnector().getOutgoingLink().getTarget();
+ InputConnector target=null;
+ if(currentSequence.getOutputConnector().getOutgoingLink()!=null){
+ target = currentSequence.getOutputConnector().getOutgoingLink().getTarget();
+ }
- if((source.eContainer() instanceof AbstractEndPoint)&&(target.eContainer() instanceof AbstractEndPoint)){
+ if((source.eContainer() instanceof AbstractEndPoint)&&((target!=null)&&(target.eContainer() instanceof AbstractEndPoint))){
EsbNodeTransformer transformer=EsbTransformerRegistry.getInstance().getTransformer((EsbNode)target.eContainer());
TransformationInfo transformationInfo=new TransformationInfo();
transformationInfo.setParentSequence(sequence);
SendMediator sendMediator=new SendMediator();
sequence.addChild(sendMediator);
InputConnector nextTarget=(getEndpointOutputConnector((AbstractEndPoint) target.eContainer())).getOutgoingLink().getTarget();
if(nextTarget.eContainer() instanceof Sequence){
String sequenceName=((Sequence)nextTarget.eContainer()).getName();
if(((Sequence)nextTarget.eContainer()).getOutputConnector().getOutgoingLink().getTarget().eContainer() instanceof AbstractEndPoint){
sendMediator.setReceivingSequence(new Value(sequenceName));
}
}
transformer.transformWithinSequence(transformationInfo,(EsbNode)target.eContainer(),sequence);
}
}
}
public static OutputConnector getEndpointOutputConnector(AbstractEndPoint endpoint){
if(endpoint instanceof AddressEndPoint){
return ((AddressEndPoint)endpoint).getOutputConnector();
}else if(endpoint instanceof DefaultEndPoint){
return ((DefaultEndPoint)endpoint).getOutputConnector();
}else if(endpoint instanceof WSDLEndPoint){
return ((WSDLEndPoint)endpoint).getOutputConnector();
}else if(endpoint instanceof NamedEndpoint){
return ((NamedEndpoint)endpoint).getOutputConnector();
}
return null;
}
}
| false | true | private void handleServiceChaining(org.wso2.developerstudio.eclipse.gmf.esb.Sequences visualSequence,SequenceMediator sequence,List proxyNames) throws Exception{
IEditorPart editorPart = null;
IProject activeProject = null;
Sequence currentSequence = null;
IEditorReference editorReferences[] = PlatformUI.getWorkbench()
.getActiveWorkbenchWindow().getActivePage()
.getEditorReferences();
for (int i = 0; i < editorReferences.length; i++) {
IEditorPart editor = editorReferences[i].getEditor(false);
if (editor != null) {
editorPart = editor.getSite().getWorkbenchWindow()
.getActivePage().getActiveEditor();
}
if (editorPart != null) {
IFileEditorInput input = (IFileEditorInput) editorPart
.getEditorInput();
IFile file = input.getFile();
activeProject = file.getProject();
}
}
String name = (String) proxyNames.get(0);
IPath location = new Path("src/main/graphical-synapse-config/proxy-services" + "/" + "proxy_"
+ name + ".esb_diagram");
IFile file = activeProject.getFile(location);
ResourceSet resourceSet = new ResourceSetImpl();
Resource resource = null;
File f = new File(file.getLocationURI().getPath());
URI uri = URI.createFileURI(f.getAbsolutePath());
if (!f.exists()) {
} else {
resource = resourceSet.getResource(uri, true);
EsbDiagram s = (EsbDiagram) ((org.eclipse.gmf.runtime.notation.impl.DiagramImpl) resource
.getContents().get(0)).getElement();
EList<EsbElement> children = s.getServer().getChildren();
for (EsbElement esbElement : children) {
if (esbElement instanceof ProxyService){
ProxyService proxyService = (ProxyService) esbElement;
List<EsbElement> elements = (List<EsbElement>) proxyService.getContainer().getSequenceAndEndpointContainer().getMediatorFlow().getChildren();
for(EsbElement elem:elements){
if((elem instanceof Sequence)&&(((Sequence)elem).getName().equals(visualSequence.getName()))){
currentSequence=(Sequence) elem;
}
}
}
}
OutputConnector source=((EsbLink)currentSequence.getInputConnector().getIncomingLinks().get(0)).getSource();
InputConnector target = currentSequence.getOutputConnector().getOutgoingLink().getTarget();
if((source.eContainer() instanceof AbstractEndPoint)&&(target.eContainer() instanceof AbstractEndPoint)){
EsbNodeTransformer transformer=EsbTransformerRegistry.getInstance().getTransformer((EsbNode)target.eContainer());
TransformationInfo transformationInfo=new TransformationInfo();
transformationInfo.setParentSequence(sequence);
SendMediator sendMediator=new SendMediator();
sequence.addChild(sendMediator);
InputConnector nextTarget=(getEndpointOutputConnector((AbstractEndPoint) target.eContainer())).getOutgoingLink().getTarget();
if(nextTarget.eContainer() instanceof Sequence){
String sequenceName=((Sequence)nextTarget.eContainer()).getName();
if(((Sequence)nextTarget.eContainer()).getOutputConnector().getOutgoingLink().getTarget().eContainer() instanceof AbstractEndPoint){
sendMediator.setReceivingSequence(new Value(sequenceName));
}
}
transformer.transformWithinSequence(transformationInfo,(EsbNode)target.eContainer(),sequence);
}
}
}
| private void handleServiceChaining(org.wso2.developerstudio.eclipse.gmf.esb.Sequences visualSequence,SequenceMediator sequence,List proxyNames) throws Exception{
IEditorPart editorPart = null;
IProject activeProject = null;
Sequence currentSequence = null;
IEditorReference editorReferences[] = PlatformUI.getWorkbench()
.getActiveWorkbenchWindow().getActivePage()
.getEditorReferences();
for (int i = 0; i < editorReferences.length; i++) {
IEditorPart editor = editorReferences[i].getEditor(false);
if (editor != null) {
editorPart = editor.getSite().getWorkbenchWindow()
.getActivePage().getActiveEditor();
}
if (editorPart != null) {
IFileEditorInput input = (IFileEditorInput) editorPart
.getEditorInput();
IFile file = input.getFile();
activeProject = file.getProject();
}
}
String name = (String) proxyNames.get(0);
IPath location = new Path("src/main/graphical-synapse-config/proxy-services" + "/" + "proxy_"
+ name + ".esb_diagram");
IFile file = activeProject.getFile(location);
ResourceSet resourceSet = new ResourceSetImpl();
Resource resource = null;
File f = new File(file.getLocationURI().getPath());
URI uri = URI.createFileURI(f.getAbsolutePath());
if (!f.exists()) {
} else {
resource = resourceSet.getResource(uri, true);
EsbDiagram s = (EsbDiagram) ((org.eclipse.gmf.runtime.notation.impl.DiagramImpl) resource
.getContents().get(0)).getElement();
EList<EsbElement> children = s.getServer().getChildren();
for (EsbElement esbElement : children) {
if (esbElement instanceof ProxyService){
ProxyService proxyService = (ProxyService) esbElement;
List<EsbElement> elements = (List<EsbElement>) proxyService.getContainer().getSequenceAndEndpointContainer().getMediatorFlow().getChildren();
for(EsbElement elem:elements){
if((elem instanceof Sequence)&&(((Sequence)elem).getName().equals(visualSequence.getName()))){
currentSequence=(Sequence) elem;
}
}
}
}
OutputConnector source=((EsbLink)currentSequence.getInputConnector().getIncomingLinks().get(0)).getSource();
InputConnector target=null;
if(currentSequence.getOutputConnector().getOutgoingLink()!=null){
target = currentSequence.getOutputConnector().getOutgoingLink().getTarget();
}
if((source.eContainer() instanceof AbstractEndPoint)&&((target!=null)&&(target.eContainer() instanceof AbstractEndPoint))){
EsbNodeTransformer transformer=EsbTransformerRegistry.getInstance().getTransformer((EsbNode)target.eContainer());
TransformationInfo transformationInfo=new TransformationInfo();
transformationInfo.setParentSequence(sequence);
SendMediator sendMediator=new SendMediator();
sequence.addChild(sendMediator);
InputConnector nextTarget=(getEndpointOutputConnector((AbstractEndPoint) target.eContainer())).getOutgoingLink().getTarget();
if(nextTarget.eContainer() instanceof Sequence){
String sequenceName=((Sequence)nextTarget.eContainer()).getName();
if(((Sequence)nextTarget.eContainer()).getOutputConnector().getOutgoingLink().getTarget().eContainer() instanceof AbstractEndPoint){
sendMediator.setReceivingSequence(new Value(sequenceName));
}
}
transformer.transformWithinSequence(transformationInfo,(EsbNode)target.eContainer(),sequence);
}
}
}
|
diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/HorizontalGroup.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/HorizontalGroup.java
index 675ae581a..bda5a355b 100644
--- a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/HorizontalGroup.java
+++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/HorizontalGroup.java
@@ -1,121 +1,121 @@
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.scenes.scene2d.ui;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Touchable;
import com.badlogic.gdx.scenes.scene2d.utils.Align;
import com.badlogic.gdx.scenes.scene2d.utils.Layout;
import com.badlogic.gdx.utils.SnapshotArray;
/** A group that lays out its children side by side in a single column. This can be easier than using {@link Table} when actors
* need to be inserted in the middle of the group.
* <p>
* The preferred width is the sum of the children's preferred widths. The preferred height is the largest preferred height of any
* child. The min size is the preferred size and the max size is 0.
* @author Nathan Sweet */
public class HorizontalGroup extends WidgetGroup {
private float prefWidth, prefHeight;
private boolean sizeInvalid = true;
private int alignment;
private boolean reverse;
private float spacing;
public HorizontalGroup () {
setTouchable(Touchable.childrenOnly);
}
/** Sets the vertical alignment of the children. Default is center.
* @see Align */
public void setAlignment (int alignment) {
this.alignment = alignment;
}
/** If true, the children will be ordered from right to left rather than the default left to right. */
public void setReverse (boolean reverse) {
this.reverse = reverse;
}
public void invalidate () {
super.invalidate();
sizeInvalid = true;
}
private void computeSize () {
sizeInvalid = false;
SnapshotArray<Actor> children = getChildren();
int n = children.size;
prefWidth = spacing * (n - 1);
prefHeight = 0;
for (int i = 0; i < n; i++) {
Actor child = children.get(i);
if (child instanceof Layout) {
Layout layout = (Layout)child;
prefWidth += layout.getPrefWidth();
prefHeight = Math.max(prefHeight, layout.getPrefHeight());
} else {
prefWidth += child.getWidth();
prefHeight = Math.max(prefHeight, child.getHeight());
}
}
}
public void layout () {
float spacing = this.spacing;
float groupHeight = getHeight();
float x = reverse ? getWidth() : 0;
float dir = reverse ? -1 : 1;
SnapshotArray<Actor> children = getChildren();
for (int i = 0, n = children.size; i < n; i++) {
Actor child = children.get(i);
float width, height;
if (child instanceof Layout) {
Layout layout = (Layout)child;
width = layout.getPrefWidth();
height = layout.getPrefHeight();
} else {
width = child.getWidth();
height = child.getHeight();
}
float y;
- if ((alignment & Align.left) != 0)
+ if ((alignment & Align.bottom) != 0)
y = 0;
- else if ((alignment & Align.right) != 0)
+ else if ((alignment & Align.top) != 0)
y = groupHeight - height;
else
y = (groupHeight - height) / 2;
if (reverse) x += (width + spacing) * dir;
child.setBounds(x, y, width, height);
if (!reverse) x += (width + spacing) * dir;
}
}
public float getPrefWidth () {
if (sizeInvalid) computeSize();
return prefWidth;
}
public float getPrefHeight () {
if (sizeInvalid) computeSize();
return prefHeight;
}
/** Sets the space between children. */
public void setSpacing (float spacing) {
this.spacing = spacing;
}
}
| false | true | public void layout () {
float spacing = this.spacing;
float groupHeight = getHeight();
float x = reverse ? getWidth() : 0;
float dir = reverse ? -1 : 1;
SnapshotArray<Actor> children = getChildren();
for (int i = 0, n = children.size; i < n; i++) {
Actor child = children.get(i);
float width, height;
if (child instanceof Layout) {
Layout layout = (Layout)child;
width = layout.getPrefWidth();
height = layout.getPrefHeight();
} else {
width = child.getWidth();
height = child.getHeight();
}
float y;
if ((alignment & Align.left) != 0)
y = 0;
else if ((alignment & Align.right) != 0)
y = groupHeight - height;
else
y = (groupHeight - height) / 2;
if (reverse) x += (width + spacing) * dir;
child.setBounds(x, y, width, height);
if (!reverse) x += (width + spacing) * dir;
}
}
| public void layout () {
float spacing = this.spacing;
float groupHeight = getHeight();
float x = reverse ? getWidth() : 0;
float dir = reverse ? -1 : 1;
SnapshotArray<Actor> children = getChildren();
for (int i = 0, n = children.size; i < n; i++) {
Actor child = children.get(i);
float width, height;
if (child instanceof Layout) {
Layout layout = (Layout)child;
width = layout.getPrefWidth();
height = layout.getPrefHeight();
} else {
width = child.getWidth();
height = child.getHeight();
}
float y;
if ((alignment & Align.bottom) != 0)
y = 0;
else if ((alignment & Align.top) != 0)
y = groupHeight - height;
else
y = (groupHeight - height) / 2;
if (reverse) x += (width + spacing) * dir;
child.setBounds(x, y, width, height);
if (!reverse) x += (width + spacing) * dir;
}
}
|
diff --git a/src/org/biojava/bio/program/gff/GFFTools.java b/src/org/biojava/bio/program/gff/GFFTools.java
index f07c5f098..89ab50881 100644
--- a/src/org/biojava/bio/program/gff/GFFTools.java
+++ b/src/org/biojava/bio/program/gff/GFFTools.java
@@ -1,344 +1,347 @@
/*
* BioJava development code
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. If you do not have a copy,
* see:
*
* http://www.gnu.org/copyleft/lesser.html
*
* Copyright for this code is held jointly by the individual
* authors. These should be listed in @author doc comments.
*
* For more information on the BioJava project and its aims,
* or to join the biojava-l mailing list, visit the home page
* at:
*
* http://www.biojava.org/
*
*/
package org.biojava.bio.program.gff;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.biojava.bio.BioError;
import org.biojava.bio.BioException;
import org.biojava.bio.seq.Sequence;
import org.biojava.bio.seq.SequenceIterator;
import org.biojava.bio.seq.db.IllegalIDException;
import org.biojava.bio.seq.db.SequenceDB;
import org.biojava.utils.ChangeVetoException;
import org.biojava.utils.ParserException;
/**
* @author Mark Schreiber
* @author Matthew Pocock
* @since 1.2
*/
public class GFFTools {
/**
* Flag to indicate that there is no score info.
*/
public static double NO_SCORE = Double.NEGATIVE_INFINITY;
/**
* Flag to indicate that there is no frame info.
*/
public static int NO_FRAME = -1;
/**
* Reads a <code>GFFEntrySet</code> from a file with no filtering.
*
* @param fileName the file containing the GFF
* @throws FileNotFoundException if file is not found
* @throws ParserException if format is wrong
* @throws BioException if format is wrong
* @throws IOException if file reading error occurs
* @return a <code>GFFEntrySet</code> encapsulating the records read from the file
* @deprecated use: readGff(File)
*/
public static GFFEntrySet readGFF(String fileName)
throws FileNotFoundException, ParserException, BioException, IOException
{
return readGFF(fileName, GFFRecordFilter.ACCEPT_ALL);
}
/**
* Reads a GFFEntrySet from a file with the specified filter.
*
* @param fileName the file containing the GFF
* @param recFilt the filter to use
* @throws FileNotFoundException if file is not found
* @throws ParserException if format is wrong
* @throws BioException if format is wrong
* @throws IOException if file reading error occurs
* @return a <code>GFFEntrySet</code> encapsulating the records read from the file
* @deprecated use: readGff(File,GFFRecordFilter)
*/
public static GFFEntrySet readGFF(String fileName, GFFRecordFilter recFilt)
throws FileNotFoundException, ParserException, BioException, IOException
{
GFFEntrySet gffEntries = new GFFEntrySet();
GFFFilterer filterer = new GFFFilterer(gffEntries.getAddHandler(),recFilt);
GFFParser parser = new GFFParser();
parser.parse(new BufferedReader(new FileReader(fileName)),filterer);
return gffEntries;
}
/**
* Reads a <code>GFFEntrySet</code> from a file with no filtering.
*
* @param inFile the File containing the GFF
* @throws FileNotFoundException if file is not found
* @throws ParserException if format is wrong
* @throws BioException if format is wrong
* @throws IOException if file reading error occurs
* @return a <code>GFFEntrySet</code> encapsulating the records read from the file
*/
public static GFFEntrySet readGFF(File inFile)
throws FileNotFoundException, ParserException, BioException, IOException
{
return readGFF(inFile, GFFRecordFilter.ACCEPT_ALL);
}
/**
* Reads a GFFEntrySet from a file with the specified filter.
*
* @param inFile the File containing the GFF
* @param recFilt the filter to use
* @throws FileNotFoundException if file is not found
* @throws ParserException if format is wrong
* @throws BioException if format is wrong
* @throws IOException if file reading error occurs
* @return a <code>GFFEntrySet</code> encapsulating the records read from the file
*/
public static GFFEntrySet readGFF(File inFile, GFFRecordFilter recFilt)
throws FileNotFoundException, ParserException, BioException, IOException
{
GFFEntrySet gffEntries = new GFFEntrySet();
GFFFilterer filterer = new GFFFilterer(gffEntries.getAddHandler(),recFilt);
GFFParser parser = new GFFParser();
parser.parse(new BufferedReader(new FileReader(inFile)),filterer);
return gffEntries;
}
/**
* Read all GFF entries from a buffered reader.
*
* This will read up untill the end of the reader.
*
* @param gffIn the BufferedReader to read text from
* @return a GFFEntrySet containing all of the GFF that could be read
* @throws parserException if the text could not be parsed as GFF
* @throws BioException if there was some error reading the GFF
* @throws IOException if there was an error with the reader
*/
public static GFFEntrySet readGFF(BufferedReader gffIn)
throws ParserException, BioException, IOException
{
return readGFF(gffIn, GFFRecordFilter.ACCEPT_ALL);
}
/**
* Read all GFF entries matching a filter from a buffered reader.
*
* This will read up untill the end of the reader.
*
* @param gffIn the BufferedReader to read text from
* @return a GFFEntrySet containing all of the GFF that could be read
* @throws parserException if the text could not be parsed as GFF
* @throws BioException if there was some error reading the GFF
* @throws IOException if there was an error with the reader
*/
public static GFFEntrySet readGFF(BufferedReader gffIn, GFFRecordFilter recFilt)
throws ParserException, BioException, IOException
{
GFFEntrySet gffEntries = new GFFEntrySet();
GFFFilterer filterer = new GFFFilterer(gffEntries.getAddHandler(),recFilt);
GFFParser parser = new GFFParser();
parser.parse(gffIn, filterer);
return gffEntries;
}
/**
* Writes a GFFEntrySet to a file.
*
* @param fileName the file to write to
* @param ents the entries to write
* @throws IOException if file writing fails
*/
public static void writeGFF(String fileName, GFFEntrySet ents)
throws IOException
{
PrintWriter pw = new PrintWriter(new FileWriter(fileName));
writeGFF(pw, ents);
pw.close();
}
/**
* Writes a GFFEntrySet to a file.
*
* @param outFile the file to write to
* @param ents the entry set to write
* @throws IOException if writing to the file fails
*/
public static void writeGFF(File outFile, GFFEntrySet ents)
throws IOException
{
PrintWriter pw = new PrintWriter(new FileWriter(outFile));
writeGFF(pw, ents);
pw.close();
}
/**
* Writes a GFFEntrySet to a PrintWriter.
*
* @param pw the PrintWriter to write to
* @param ents the entries to write
* @throws IOException if file writing fails
*/
public static void writeGFF(PrintWriter pw, GFFEntrySet ents)
throws IOException
{
GFFWriter writer = new GFFWriter(pw);
ents.streamRecords(writer);
}
/**
* Annotates a sequence with the features from a GFF entry set with sequence
* name matching this sequence.
*
* @param seq the <code>Sequence</code> to annotate.
* @param ents the the GFF features to annotate it with.
* @return a reference to a newly annotated sequence.
*/
public static Sequence annotateSequence(Sequence seq, GFFEntrySet ents){
Sequence annotated;
try {
annotated = ents.getAnnotator().annotate(seq);
}
catch (ChangeVetoException ex) {
throw new BioError("Assertion Error: Unable to annotate sequence",ex);
}catch (BioException ex) {
throw new BioError("Assertion Error: Unable to annotate sequence",ex);
}
return annotated;
}
/**
* Annotates a sequence with the features from a GFF entry set.
*
* @param seq the <code>Sequence</code> to annotate.
* @param ents the the GFF features to annotate it with.
* @param matchSeqName boolean flat, if true only annotte sequence with
* features that have matching sequence names, otherwise annotate
* all features
* @return a reference to a newly annotated sequence.
*/
public static Sequence annotateSequence(
Sequence seq,
GFFEntrySet ents,
boolean checkSeqName
) {
Sequence annotated;
try {
annotated = ents.getAnnotator(checkSeqName).annotate(seq);
}
catch (ChangeVetoException ex) {
throw new BioError("Assertion Error: Unable to annotate sequence",ex);
}catch (BioException ex) {
throw new BioError("Assertion Error: Unable to annotate sequence",ex);
}
return annotated;
}
/**
* Annotates all sequences in a sequence DB with features from a GFF entry set.
*
* @param seqs the SequenceDB to annotate
* @param ents the GFFEntrySet to annote with
* @return a SequenceDB with all the annotations on
*/
public static SequenceDB annotateSequences(SequenceDB seqs, GFFEntrySet ents)
throws IllegalIDException, BioException{
Set names = new HashSet();
//get the list of names for each sequence
for (Iterator i = ents.lineIterator(); i.hasNext(); ) {
- GFFRecord record = (GFFRecord)i.next();
- if(! names.contains(record.getSeqName())){
- names.add(record.getSeqName());
+ Object o = i.next();
+ if(o instanceof GFFRecord){//only process GFFRecords not comments
+ GFFRecord record = (GFFRecord)o;
+ if(! names.contains(record.getSeqName())){
+ names.add(record.getSeqName());
+ }
}
}
//filter entry set into subsets with same names, use that subset to annotate
//the correct sequence.
for (Iterator i = names.iterator(); i.hasNext(); ) {
final String name = (String)i.next();
GFFRecordFilter filt = new GFFRecordFilter(){
public boolean accept(GFFRecord rec){
return rec.getSeqName().equals(name);
}
};
GFFEntrySet filtered = ents.filter(filt);
Sequence seq = seqs.getSequence(name);
seq = GFFTools.annotateSequence(seq, filtered);
}
return seqs;
}
/**
* Creates a GFFEntrySet containing one entry for each feature on a sequence.
*
* @param seq the Sequence to create features for
* @return a new GFFEntrySet with gff records for each featre on the sequence
* @throws BioException if something went wrong GFF-ifying the sequences
* features
*/
public static GFFEntrySet gffFromSequence(Sequence seq)
throws BioException {
SequencesAsGFF sagff = new SequencesAsGFF();
GFFEntrySet gffES = new GFFEntrySet();
sagff.processSequence(seq, gffES.getAddHandler());
return gffES;
}
/**
* Creates a GFFEntrySet containing one entry for each feature on each
* sequence of a SequenceDB.
*
* <p><em>Note:</em> This converts all features in the whole database to
* in-memorey GFFRecord instances. This will take up considerable memory for
* large databases.</p>
*
* @param seqDB the SequenceDB to create features for
* @return a new GFFEntrySet with gff records for each feature on the database
* @throws BioException if something went wrong GFF-ifying the sequences
* features
*/
public static GFFEntrySet gffFromSeqDB(SequenceDB seqDB)
throws BioException {
GFFEntrySet gffES = new GFFEntrySet();
for(SequenceIterator si = seqDB.sequenceIterator(); si.hasNext(); ) {
Sequence seq = si.nextSequence();
SequencesAsGFF sagff = new SequencesAsGFF();
sagff.processSequence(seq, gffES.getAddHandler());
}
return gffES;
}
}
| true | true | public static SequenceDB annotateSequences(SequenceDB seqs, GFFEntrySet ents)
throws IllegalIDException, BioException{
Set names = new HashSet();
//get the list of names for each sequence
for (Iterator i = ents.lineIterator(); i.hasNext(); ) {
GFFRecord record = (GFFRecord)i.next();
if(! names.contains(record.getSeqName())){
names.add(record.getSeqName());
}
}
//filter entry set into subsets with same names, use that subset to annotate
//the correct sequence.
for (Iterator i = names.iterator(); i.hasNext(); ) {
final String name = (String)i.next();
GFFRecordFilter filt = new GFFRecordFilter(){
public boolean accept(GFFRecord rec){
return rec.getSeqName().equals(name);
}
};
GFFEntrySet filtered = ents.filter(filt);
Sequence seq = seqs.getSequence(name);
seq = GFFTools.annotateSequence(seq, filtered);
}
return seqs;
}
| public static SequenceDB annotateSequences(SequenceDB seqs, GFFEntrySet ents)
throws IllegalIDException, BioException{
Set names = new HashSet();
//get the list of names for each sequence
for (Iterator i = ents.lineIterator(); i.hasNext(); ) {
Object o = i.next();
if(o instanceof GFFRecord){//only process GFFRecords not comments
GFFRecord record = (GFFRecord)o;
if(! names.contains(record.getSeqName())){
names.add(record.getSeqName());
}
}
}
//filter entry set into subsets with same names, use that subset to annotate
//the correct sequence.
for (Iterator i = names.iterator(); i.hasNext(); ) {
final String name = (String)i.next();
GFFRecordFilter filt = new GFFRecordFilter(){
public boolean accept(GFFRecord rec){
return rec.getSeqName().equals(name);
}
};
GFFEntrySet filtered = ents.filter(filt);
Sequence seq = seqs.getSequence(name);
seq = GFFTools.annotateSequence(seq, filtered);
}
return seqs;
}
|
diff --git a/AeroControl/src/com/aero/control/fragments/GPUFragment.java b/AeroControl/src/com/aero/control/fragments/GPUFragment.java
index fe9255b..5469ea9 100644
--- a/AeroControl/src/com/aero/control/fragments/GPUFragment.java
+++ b/AeroControl/src/com/aero/control/fragments/GPUFragment.java
@@ -1,430 +1,431 @@
package com.aero.control.fragments;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceCategory;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.preference.PreferenceScreen;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.Toast;
import com.aero.control.AeroActivity;
import com.aero.control.R;
import com.aero.control.helpers.PreferenceHandler;
import java.io.File;
/**
* Created by ac on 16.09.13.
*/
public class GPUFragment extends PreferenceFragment implements Preference.OnPreferenceChangeListener {
public boolean checkGpuControl;
public boolean checkmSweep2wake;
public boolean checkDoubletap2wake;
public String[] mColorValues;
private SharedPreferences prefs;
private PreferenceCategory PrefCat;
private PreferenceScreen root;
private CheckBoxPreference mGPUControl, mSweep2wake, mDoubletap2Wake;
private ListPreference mGPUControlFrequencies, mGPUGovernor, mDisplayControl;
private Preference mColorControl;
public String gpu_file;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
// We have to load the xml layout first;
addPreferencesFromResource(R.layout.gpu_fragment);
root = this.getPreferenceScreen();
PreferenceCategory gpuCategory = (PreferenceCategory) findPreference("gpu_settings");
// If there are already some entries, kill them all (with fire)
if (PrefCat != null)
root.removePreference(PrefCat);
// Set our gpu control flag;
mGPUControl = (CheckBoxPreference)root.findPreference("gpu_control_enable");
mSweep2wake = (CheckBoxPreference)root.findPreference("sweeptowake");
mDoubletap2Wake = (CheckBoxPreference)root.findPreference("doubletaptowake");
// Find our ListPreference (max_frequency);
mGPUControlFrequencies = (ListPreference)root.findPreference("gpu_max_freq");
mGPUGovernor = (ListPreference)root.findPreference("set_gpu_governor");
mDisplayControl = (ListPreference)root.findPreference("display_control");
mColorControl = root.findPreference("display_color_control");
mGPUGovernor.setOnPreferenceChangeListener(this);
+ mGPUControlFrequencies.setOnPreferenceChangeListener(this);
/* Find correct gpu path */
for (String a : AeroActivity.files.GPU_FILES) {
if (new File(a).exists()) {
gpu_file = a;
break;
}
}
if(!(new File(AeroActivity.files.SWEEP2WAKE).exists()))
gpuCategory.removePreference(mSweep2wake);
if(!(new File(AeroActivity.files.DOUBLETAP2WAKE).exists()))
gpuCategory.removePreference(mDoubletap2Wake);
if(!(new File(AeroActivity.files.GPU_CONTROL_ACTIVE).exists()))
gpuCategory.removePreference(mGPUControl);
if (gpu_file == null)
gpuCategory.removePreference(mGPUControlFrequencies);
if (!(new File(AeroActivity.files.COLOR_CONTROL).exists()))
gpuCategory.removePreference(mColorControl);
if (AeroActivity.shell.getInfo(AeroActivity.files.DISPLAY_COLOR).equals("Unavailable"))
gpuCategory.removePreference(mDisplayControl);
final Preference gpu_gov_settings = root.findPreference("gpu_gov_settings");
if (new File("/sys/module/msm_kgsl_core/parameters").exists()) {
gpu_gov_settings.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
getFragmentManager()
.beginTransaction()
.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out)
.replace(R.id.content_frame, new GPUGovernorFragment())
.addToBackStack("GPU Governor")
.commit();
return true;
}
});
} else {
gpuCategory.removePreference(gpu_gov_settings);
}
// Get our strings;
CharSequence[] display_entries = {
getText(R.string.defy_red_colors),
getText(R.string.defy_green_colors),
getText(R.string.defy_energy_saver)
};
CharSequence[] display_values = {"31", "9", "0"};
mDisplayControl.setEntries(display_entries);
mDisplayControl.setEntryValues(display_values);
// Just throw in our frequencies;
if (new File(AeroActivity.files.GPU_FREQ_NEXUS4_VALUES).exists()) {
mGPUControlFrequencies.setEntries(AeroActivity.shell.getInfoArray(AeroActivity.files.GPU_FREQ_NEXUS4_VALUES, 1, 0));
mGPUControlFrequencies.setEntryValues(AeroActivity.shell.getInfoArray(AeroActivity.files.GPU_FREQ_NEXUS4_VALUES, 0, 0));
} else {
mGPUControlFrequencies.setEntries(R.array.gpu_frequency_list);
mGPUControlFrequencies.setEntryValues(R.array.gpu_frequency_list_values);
}
if (new File(AeroActivity.files.GPU_GOV_BASE + "governor").exists()) {
mGPUGovernor.setEntries(AeroActivity.shell.getInfoArray(AeroActivity.files.GPU_GOV_BASE + "available_governors", 0, 0));
mGPUGovernor.setEntryValues(AeroActivity.shell.getInfoArray(AeroActivity.files.GPU_GOV_BASE + "available_governors", 0, 0));
mGPUGovernor.setValue(AeroActivity.shell.getInfo(AeroActivity.files.GPU_GOV_BASE + "governor"));
mGPUGovernor.setSummary(AeroActivity.shell.getInfo(AeroActivity.files.GPU_GOV_BASE + "governor"));
mGPUGovernor.setDialogIcon(R.drawable.gpu_dark);
} else {
gpuCategory.removePreference(mGPUGovernor);
}
try {
if (gpu_file != null) {
mGPUControlFrequencies.setValue(AeroActivity.shell.getInfoArray(gpu_file, 0, 0)[0]);
mGPUControlFrequencies.setSummary(AeroActivity.shell.toMHz((AeroActivity.shell.getInfoArray(gpu_file, 0, 0)[0].substring(0,
AeroActivity.shell.getInfoArray(gpu_file, 0, 0)[0].length() - 3))));
}
// Check if enabled or not;
if (AeroActivity.shell.getInfo(AeroActivity.files.GPU_CONTROL_ACTIVE).equals("1"))
checkGpuControl = true;
else
checkGpuControl = false;
// Check if enabled or not;
if (AeroActivity.shell.getInfo(AeroActivity.files.SWEEP2WAKE).equals("1"))
checkmSweep2wake = true;
else
checkmSweep2wake = false;
if (AeroActivity.shell.getInfo(AeroActivity.files.DOUBLETAP2WAKE).equals("1"))
checkDoubletap2wake = true;
else
checkDoubletap2wake = false;
mSweep2wake.setChecked(checkmSweep2wake);
mDoubletap2Wake.setChecked(checkDoubletap2wake);
mGPUControl.setChecked(checkGpuControl);
} catch (ArrayIndexOutOfBoundsException e) {
/*
* If the folder is missing, disable this feature completely;
*/
mGPUControlFrequencies.setSummary("Unavailable");
mGPUControlFrequencies.setEnabled(false);
mGPUControl.setEnabled(false);
Toast.makeText(getActivity(), "GPU Control is not supported with your kernel.", Toast.LENGTH_LONG).show();
}
mGPUControlFrequencies.setDialogIcon(R.drawable.gpu_dark);
if (!(gpuCategory.getPreferenceCount() > 0)) {
gpuCategory.setTitle(R.string.nogpu_data);
}
}
private final void showColorControl() {
mColorValues = AeroActivity.shell.getInfoArray(AeroActivity.files.COLOR_CONTROL, 0, 0);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View layout = inflater.inflate(R.layout.gpu_color_control, null);
final SeekBar redValues = (SeekBar)layout.findViewById(R.id.redValues);
final SeekBar greenValues = (SeekBar)layout.findViewById(R.id.greenValues);
final SeekBar blueValues = (SeekBar)layout.findViewById(R.id.blueValues);
final EditText redValue = (EditText)layout.findViewById(R.id.redValue);
final EditText greenValue = (EditText)layout.findViewById(R.id.greenValue);
final EditText blueValue = (EditText)layout.findViewById(R.id.blueValue);
redValues.setProgress(Integer.parseInt(mColorValues[0]));
greenValues.setProgress(Integer.parseInt(mColorValues[1]));
blueValues.setProgress(Integer.parseInt(mColorValues[2]));
redValue.setText(mColorValues[0]);
greenValue.setText(mColorValues[1]);
blueValue.setText(mColorValues[2]);
redValues.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
redValue.setText("" + i);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {}
});
greenValues.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
greenValue.setText("" + i);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {}
});
blueValues.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
blueValue.setText("" + i);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {}
});
builder.setTitle(R.string.pref_display_color);
builder.setView(layout)
.setPositiveButton(R.string.apply, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
int red = Integer.parseInt(redValue.getText().toString());
int green = Integer.parseInt(greenValue.getText().toString());
int blue = Integer.parseInt(blueValue.getText().toString());
if (red > 255 || blue > 255 || green > 255 ) {
Toast.makeText(getActivity(), "The values are out of range!", Toast.LENGTH_LONG).show();
return;
} else if (red < 10 || blue < 10 || green < 100) {
Toast.makeText(getActivity(), "Those values are pretty low, are you sure?", Toast.LENGTH_LONG).show();
return;
}
String rgbValues = redValue.getText() + " " + greenValue.getText() + " " + blueValue.getText();
AeroActivity.shell.setRootInfo(rgbValues, AeroActivity.files.COLOR_CONTROL);
//** store preferences
SharedPreferences preference = PreferenceManager.getDefaultSharedPreferences(getActivity().getBaseContext());
preference.edit().putString("rgbValues", rgbValues).commit();
}
})
.setNegativeButton(R.string.maybe_later, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
}
});
builder.show();
}
@Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
if (preference == mSweep2wake) {
if (mSweep2wake.isChecked())
AeroActivity.shell.setRootInfo("1", AeroActivity.files.SWEEP2WAKE);
else
AeroActivity.shell.setRootInfo("0", AeroActivity.files.SWEEP2WAKE);
} else if (preference == mDoubletap2Wake) {
if (mDoubletap2Wake.isChecked())
AeroActivity.shell.setRootInfo("1", AeroActivity.files.DOUBLETAP2WAKE);
else
AeroActivity.shell.setRootInfo("0", AeroActivity.files.DOUBLETAP2WAKE);
} else if (preference == mColorControl) {
showColorControl();
}
preference.getEditor().commit();
return true;
}
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
String a = (String) newValue;
String newSummary = "";
String path = "";
if (preference == mGPUControlFrequencies) {
path = gpu_file;
newSummary = AeroActivity.shell.toMHz((a.substring(0, a.length() - 3)));
} else if (preference == mGPUGovernor) {
// If there are already some entries, kill them all (with fire)
if (PrefCat != null)
root.removePreference(PrefCat);
path = AeroActivity.files.GPU_GOV_BASE + "governor";
newSummary = a;
} else if (preference == mGPUControl) {
path = AeroActivity.files.GPU_CONTROL_ACTIVE;
} else if (preference == mDisplayControl) {
// Get Permissions first, then execute;
final String[] commands = new String[]
{
"chmod 0664 " + AeroActivity.files.DISPLAY_COLOR,
"echo " + a + " > " + AeroActivity.files.DISPLAY_COLOR,
};
AeroActivity.shell.setRootInfo(commands);
Toast.makeText(getActivity(), "Turn your display off/on :)", Toast.LENGTH_LONG).show();
// Return earlier, since we executed an array;
preference.getEditor().commit();
return true;
}
AeroActivity.shell.setRootInfo(a, path);
if(!newSummary.equals(""))
preference.setSummary(newSummary);
preference.getEditor().commit();
return true;
}
// Create our options menu;
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
if (new File(AeroActivity.files.GPU_GOV_BASE).exists()) {
prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String a = prefs.getString("app_theme", null);
if (a == null)
a = "";
if (a.equals("red"))
inflater.inflate(R.menu.cpu_menu, menu);
else if (a.equals("light"))
inflater.inflate(R.menu.cpu_menu, menu);
else if (a.equals("dark"))
inflater.inflate(R.menu.cpu_menu_light, menu);
else
inflater.inflate(R.menu.cpu_menu, menu);
}
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_governor_settings:
String[] completeParamterList;
try {
completeParamterList = AeroActivity.shell.getDirInfo(AeroActivity.files.GPU_GOV_BASE + AeroActivity.shell.getInfo(AeroActivity.files.GPU_GOV_BASE + "governor"), true);
} catch (NullPointerException e) {
Toast.makeText(getActivity(), "Looks like there are no parameter for this governor?", Toast.LENGTH_LONG).show();
Log.e("Aero", "Couldn't find any parameters for this governor!", e);
return true;
}
// If there are already some entries, kill them all (with fire)
if (PrefCat != null)
root.removePreference(PrefCat);
PrefCat = new PreferenceCategory(getActivity());
PrefCat.setTitle(R.string.perf_gpu_gov_settings);
root.addPreference(PrefCat);
try {
PreferenceHandler h = new PreferenceHandler(getActivity(), PrefCat, getPreferenceManager());
h.genPrefFromDictionary(completeParamterList, AeroActivity.files.GPU_GOV_BASE + AeroActivity.shell.getInfo(AeroActivity.files.GPU_GOV_BASE + "governor"));
} catch (NullPointerException e) {
Log.e("Aero", "I couldn't get any files!", e);
}
return true;
}
return super.onOptionsItemSelected(item);
}
}
| true | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
// We have to load the xml layout first;
addPreferencesFromResource(R.layout.gpu_fragment);
root = this.getPreferenceScreen();
PreferenceCategory gpuCategory = (PreferenceCategory) findPreference("gpu_settings");
// If there are already some entries, kill them all (with fire)
if (PrefCat != null)
root.removePreference(PrefCat);
// Set our gpu control flag;
mGPUControl = (CheckBoxPreference)root.findPreference("gpu_control_enable");
mSweep2wake = (CheckBoxPreference)root.findPreference("sweeptowake");
mDoubletap2Wake = (CheckBoxPreference)root.findPreference("doubletaptowake");
// Find our ListPreference (max_frequency);
mGPUControlFrequencies = (ListPreference)root.findPreference("gpu_max_freq");
mGPUGovernor = (ListPreference)root.findPreference("set_gpu_governor");
mDisplayControl = (ListPreference)root.findPreference("display_control");
mColorControl = root.findPreference("display_color_control");
mGPUGovernor.setOnPreferenceChangeListener(this);
/* Find correct gpu path */
for (String a : AeroActivity.files.GPU_FILES) {
if (new File(a).exists()) {
gpu_file = a;
break;
}
}
if(!(new File(AeroActivity.files.SWEEP2WAKE).exists()))
gpuCategory.removePreference(mSweep2wake);
if(!(new File(AeroActivity.files.DOUBLETAP2WAKE).exists()))
gpuCategory.removePreference(mDoubletap2Wake);
if(!(new File(AeroActivity.files.GPU_CONTROL_ACTIVE).exists()))
gpuCategory.removePreference(mGPUControl);
if (gpu_file == null)
gpuCategory.removePreference(mGPUControlFrequencies);
if (!(new File(AeroActivity.files.COLOR_CONTROL).exists()))
gpuCategory.removePreference(mColorControl);
if (AeroActivity.shell.getInfo(AeroActivity.files.DISPLAY_COLOR).equals("Unavailable"))
gpuCategory.removePreference(mDisplayControl);
final Preference gpu_gov_settings = root.findPreference("gpu_gov_settings");
if (new File("/sys/module/msm_kgsl_core/parameters").exists()) {
gpu_gov_settings.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
getFragmentManager()
.beginTransaction()
.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out)
.replace(R.id.content_frame, new GPUGovernorFragment())
.addToBackStack("GPU Governor")
.commit();
return true;
}
});
} else {
gpuCategory.removePreference(gpu_gov_settings);
}
// Get our strings;
CharSequence[] display_entries = {
getText(R.string.defy_red_colors),
getText(R.string.defy_green_colors),
getText(R.string.defy_energy_saver)
};
CharSequence[] display_values = {"31", "9", "0"};
mDisplayControl.setEntries(display_entries);
mDisplayControl.setEntryValues(display_values);
// Just throw in our frequencies;
if (new File(AeroActivity.files.GPU_FREQ_NEXUS4_VALUES).exists()) {
mGPUControlFrequencies.setEntries(AeroActivity.shell.getInfoArray(AeroActivity.files.GPU_FREQ_NEXUS4_VALUES, 1, 0));
mGPUControlFrequencies.setEntryValues(AeroActivity.shell.getInfoArray(AeroActivity.files.GPU_FREQ_NEXUS4_VALUES, 0, 0));
} else {
mGPUControlFrequencies.setEntries(R.array.gpu_frequency_list);
mGPUControlFrequencies.setEntryValues(R.array.gpu_frequency_list_values);
}
if (new File(AeroActivity.files.GPU_GOV_BASE + "governor").exists()) {
mGPUGovernor.setEntries(AeroActivity.shell.getInfoArray(AeroActivity.files.GPU_GOV_BASE + "available_governors", 0, 0));
mGPUGovernor.setEntryValues(AeroActivity.shell.getInfoArray(AeroActivity.files.GPU_GOV_BASE + "available_governors", 0, 0));
mGPUGovernor.setValue(AeroActivity.shell.getInfo(AeroActivity.files.GPU_GOV_BASE + "governor"));
mGPUGovernor.setSummary(AeroActivity.shell.getInfo(AeroActivity.files.GPU_GOV_BASE + "governor"));
mGPUGovernor.setDialogIcon(R.drawable.gpu_dark);
} else {
gpuCategory.removePreference(mGPUGovernor);
}
try {
if (gpu_file != null) {
mGPUControlFrequencies.setValue(AeroActivity.shell.getInfoArray(gpu_file, 0, 0)[0]);
mGPUControlFrequencies.setSummary(AeroActivity.shell.toMHz((AeroActivity.shell.getInfoArray(gpu_file, 0, 0)[0].substring(0,
AeroActivity.shell.getInfoArray(gpu_file, 0, 0)[0].length() - 3))));
}
// Check if enabled or not;
if (AeroActivity.shell.getInfo(AeroActivity.files.GPU_CONTROL_ACTIVE).equals("1"))
checkGpuControl = true;
else
checkGpuControl = false;
// Check if enabled or not;
if (AeroActivity.shell.getInfo(AeroActivity.files.SWEEP2WAKE).equals("1"))
checkmSweep2wake = true;
else
checkmSweep2wake = false;
if (AeroActivity.shell.getInfo(AeroActivity.files.DOUBLETAP2WAKE).equals("1"))
checkDoubletap2wake = true;
else
checkDoubletap2wake = false;
mSweep2wake.setChecked(checkmSweep2wake);
mDoubletap2Wake.setChecked(checkDoubletap2wake);
mGPUControl.setChecked(checkGpuControl);
} catch (ArrayIndexOutOfBoundsException e) {
/*
* If the folder is missing, disable this feature completely;
*/
mGPUControlFrequencies.setSummary("Unavailable");
mGPUControlFrequencies.setEnabled(false);
mGPUControl.setEnabled(false);
Toast.makeText(getActivity(), "GPU Control is not supported with your kernel.", Toast.LENGTH_LONG).show();
}
mGPUControlFrequencies.setDialogIcon(R.drawable.gpu_dark);
if (!(gpuCategory.getPreferenceCount() > 0)) {
gpuCategory.setTitle(R.string.nogpu_data);
}
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
// We have to load the xml layout first;
addPreferencesFromResource(R.layout.gpu_fragment);
root = this.getPreferenceScreen();
PreferenceCategory gpuCategory = (PreferenceCategory) findPreference("gpu_settings");
// If there are already some entries, kill them all (with fire)
if (PrefCat != null)
root.removePreference(PrefCat);
// Set our gpu control flag;
mGPUControl = (CheckBoxPreference)root.findPreference("gpu_control_enable");
mSweep2wake = (CheckBoxPreference)root.findPreference("sweeptowake");
mDoubletap2Wake = (CheckBoxPreference)root.findPreference("doubletaptowake");
// Find our ListPreference (max_frequency);
mGPUControlFrequencies = (ListPreference)root.findPreference("gpu_max_freq");
mGPUGovernor = (ListPreference)root.findPreference("set_gpu_governor");
mDisplayControl = (ListPreference)root.findPreference("display_control");
mColorControl = root.findPreference("display_color_control");
mGPUGovernor.setOnPreferenceChangeListener(this);
mGPUControlFrequencies.setOnPreferenceChangeListener(this);
/* Find correct gpu path */
for (String a : AeroActivity.files.GPU_FILES) {
if (new File(a).exists()) {
gpu_file = a;
break;
}
}
if(!(new File(AeroActivity.files.SWEEP2WAKE).exists()))
gpuCategory.removePreference(mSweep2wake);
if(!(new File(AeroActivity.files.DOUBLETAP2WAKE).exists()))
gpuCategory.removePreference(mDoubletap2Wake);
if(!(new File(AeroActivity.files.GPU_CONTROL_ACTIVE).exists()))
gpuCategory.removePreference(mGPUControl);
if (gpu_file == null)
gpuCategory.removePreference(mGPUControlFrequencies);
if (!(new File(AeroActivity.files.COLOR_CONTROL).exists()))
gpuCategory.removePreference(mColorControl);
if (AeroActivity.shell.getInfo(AeroActivity.files.DISPLAY_COLOR).equals("Unavailable"))
gpuCategory.removePreference(mDisplayControl);
final Preference gpu_gov_settings = root.findPreference("gpu_gov_settings");
if (new File("/sys/module/msm_kgsl_core/parameters").exists()) {
gpu_gov_settings.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
getFragmentManager()
.beginTransaction()
.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out)
.replace(R.id.content_frame, new GPUGovernorFragment())
.addToBackStack("GPU Governor")
.commit();
return true;
}
});
} else {
gpuCategory.removePreference(gpu_gov_settings);
}
// Get our strings;
CharSequence[] display_entries = {
getText(R.string.defy_red_colors),
getText(R.string.defy_green_colors),
getText(R.string.defy_energy_saver)
};
CharSequence[] display_values = {"31", "9", "0"};
mDisplayControl.setEntries(display_entries);
mDisplayControl.setEntryValues(display_values);
// Just throw in our frequencies;
if (new File(AeroActivity.files.GPU_FREQ_NEXUS4_VALUES).exists()) {
mGPUControlFrequencies.setEntries(AeroActivity.shell.getInfoArray(AeroActivity.files.GPU_FREQ_NEXUS4_VALUES, 1, 0));
mGPUControlFrequencies.setEntryValues(AeroActivity.shell.getInfoArray(AeroActivity.files.GPU_FREQ_NEXUS4_VALUES, 0, 0));
} else {
mGPUControlFrequencies.setEntries(R.array.gpu_frequency_list);
mGPUControlFrequencies.setEntryValues(R.array.gpu_frequency_list_values);
}
if (new File(AeroActivity.files.GPU_GOV_BASE + "governor").exists()) {
mGPUGovernor.setEntries(AeroActivity.shell.getInfoArray(AeroActivity.files.GPU_GOV_BASE + "available_governors", 0, 0));
mGPUGovernor.setEntryValues(AeroActivity.shell.getInfoArray(AeroActivity.files.GPU_GOV_BASE + "available_governors", 0, 0));
mGPUGovernor.setValue(AeroActivity.shell.getInfo(AeroActivity.files.GPU_GOV_BASE + "governor"));
mGPUGovernor.setSummary(AeroActivity.shell.getInfo(AeroActivity.files.GPU_GOV_BASE + "governor"));
mGPUGovernor.setDialogIcon(R.drawable.gpu_dark);
} else {
gpuCategory.removePreference(mGPUGovernor);
}
try {
if (gpu_file != null) {
mGPUControlFrequencies.setValue(AeroActivity.shell.getInfoArray(gpu_file, 0, 0)[0]);
mGPUControlFrequencies.setSummary(AeroActivity.shell.toMHz((AeroActivity.shell.getInfoArray(gpu_file, 0, 0)[0].substring(0,
AeroActivity.shell.getInfoArray(gpu_file, 0, 0)[0].length() - 3))));
}
// Check if enabled or not;
if (AeroActivity.shell.getInfo(AeroActivity.files.GPU_CONTROL_ACTIVE).equals("1"))
checkGpuControl = true;
else
checkGpuControl = false;
// Check if enabled or not;
if (AeroActivity.shell.getInfo(AeroActivity.files.SWEEP2WAKE).equals("1"))
checkmSweep2wake = true;
else
checkmSweep2wake = false;
if (AeroActivity.shell.getInfo(AeroActivity.files.DOUBLETAP2WAKE).equals("1"))
checkDoubletap2wake = true;
else
checkDoubletap2wake = false;
mSweep2wake.setChecked(checkmSweep2wake);
mDoubletap2Wake.setChecked(checkDoubletap2wake);
mGPUControl.setChecked(checkGpuControl);
} catch (ArrayIndexOutOfBoundsException e) {
/*
* If the folder is missing, disable this feature completely;
*/
mGPUControlFrequencies.setSummary("Unavailable");
mGPUControlFrequencies.setEnabled(false);
mGPUControl.setEnabled(false);
Toast.makeText(getActivity(), "GPU Control is not supported with your kernel.", Toast.LENGTH_LONG).show();
}
mGPUControlFrequencies.setDialogIcon(R.drawable.gpu_dark);
if (!(gpuCategory.getPreferenceCount() > 0)) {
gpuCategory.setTitle(R.string.nogpu_data);
}
}
|
diff --git a/modules/resin/src/com/caucho/jsf/html/HtmlCommandLinkRenderer.java b/modules/resin/src/com/caucho/jsf/html/HtmlCommandLinkRenderer.java
index b036724b3..7bf483133 100644
--- a/modules/resin/src/com/caucho/jsf/html/HtmlCommandLinkRenderer.java
+++ b/modules/resin/src/com/caucho/jsf/html/HtmlCommandLinkRenderer.java
@@ -1,441 +1,441 @@
/*
* Copyright (c) 1998-2008 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* Resin Open Source 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, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
*/
package com.caucho.jsf.html;
import java.io.*;
import java.util.*;
import java.net.URLEncoder;
import javax.faces.component.*;
import javax.faces.component.html.*;
import javax.faces.context.*;
import javax.faces.event.*;
import javax.faces.render.*;
/**
* The HTML command/link renderer
*/
class HtmlCommandLinkRenderer extends BaseRenderer
{
public static final Renderer RENDERER = new HtmlCommandLinkRenderer();
/**
* True if the renderer is responsible for rendering the children.
*/
@Override
public boolean getRendersChildren()
{
return true;
}
/**
* Decodes the data from the form.
*/
@Override
public void decode(FacesContext context, UIComponent component)
{
String formId = getFormId(context, component);
String clientId = component.getClientId(context);
String hiddenId = clientId + ":link";
ExternalContext ext = context.getExternalContext();
Map<String,String> paramMap = ext.getRequestParameterMap();
String value = paramMap.get(hiddenId);
if (value != null && ! "".equals(value)) {
ActionEvent event = new ActionEvent(component);
component.queueEvent(event);
}
else {
String valueX = clientId + ".x";
String valueY = clientId + ".y";
}
}
/**
* Renders the open tag for the text.
*/
@Override
public void encodeBegin(FacesContext context, UIComponent component)
throws IOException
{
ResponseWriter out = context.getResponseWriter();
String id = component.getId();
String accesskey;
String charset;
String coords;
String dir;
boolean disabled;
String hreflang;
String lang;
String onblur;
String onclick;
String ondblclick;
String onfocus;
String onkeydown;
String onkeypress;
String onkeyup;
String onmousedown;
String onmousemove;
String onmouseout;
String onmouseover;
String onmouseup;
String rel;
String rev;
String shape;
String style;
String styleClass;
String tabindex;
String target;
String title;
String type;
Object value;
if (component instanceof HtmlCommandLink) {
HtmlCommandLink htmlCommandLink = (HtmlCommandLink) component;
accesskey = htmlCommandLink.getAccesskey();
charset = htmlCommandLink.getCharset();
coords = htmlCommandLink.getCoords();
dir = htmlCommandLink.getDir();
disabled = htmlCommandLink.isDisabled();
hreflang = htmlCommandLink.getHreflang();
lang = htmlCommandLink.getLang();
onblur = htmlCommandLink.getOnblur();
onclick = htmlCommandLink.getOnclick();
ondblclick = htmlCommandLink.getOndblclick();
onfocus = htmlCommandLink.getOnfocus();
onkeydown = htmlCommandLink.getOnkeydown();
onkeypress = htmlCommandLink.getOnkeypress();
onkeyup = htmlCommandLink.getOnkeyup();
onmousedown = htmlCommandLink.getOnmousedown();
onmousemove = htmlCommandLink.getOnmousemove();
onmouseout = htmlCommandLink.getOnmouseout();
onmouseover = htmlCommandLink.getOnmouseover();
onmouseup = htmlCommandLink.getOnmouseup();
rel = htmlCommandLink.getRel();
rev = htmlCommandLink.getRev();
shape = htmlCommandLink.getShape();
style = htmlCommandLink.getStyle();
styleClass = htmlCommandLink.getStyleClass();
tabindex = htmlCommandLink.getTabindex();
title = htmlCommandLink.getTitle();
type = htmlCommandLink.getType();
target = htmlCommandLink.getTarget();
value = htmlCommandLink.getValue();
}
else {
Map<String,Object> attrMap = component.getAttributes();
accesskey = (String) attrMap.get("accesskey");
charset = (String) attrMap.get("charset");
coords = (String) attrMap.get("coords");
dir = (String) attrMap.get("dir");
disabled = (Boolean) attrMap.get("disabled");
hreflang = (String) attrMap.get("hreflang");
lang = (String) attrMap.get("lang");
onblur = (String) attrMap.get("onblur");
onclick = (String) attrMap.get("onclick");
ondblclick = (String) attrMap.get("ondblclick");
onfocus = (String) attrMap.get("onfocus");
onkeydown = (String) attrMap.get("onkeydown");
onkeypress = (String) attrMap.get("onkeypress");
onkeyup = (String) attrMap.get("onkeyup");
onmousedown = (String) attrMap.get("onmousedown");
onmousemove = (String) attrMap.get("onmousemove");
onmouseout = (String) attrMap.get("onmouseout");
onmouseover = (String) attrMap.get("onmouseover");
onmouseup = (String) attrMap.get("onmouseup");
rel = (String) attrMap.get("rel");
rev = (String) attrMap.get("rev");
shape = (String) attrMap.get("shape");
style = (String) attrMap.get("style");
styleClass = (String) attrMap.get("styleClass");
tabindex = (String) attrMap.get("tabindex");
title = (String) attrMap.get("title");
type = (String) attrMap.get("type");
target = (String)attrMap.get("target");
value = attrMap.get("value");
}
String clientId = component.getClientId(context);
String formClientId = getFormId(context, component);
String hiddenFieldName = clientId + ":link";
if (disabled) {
out.startElement("span", component);
if (target != null)
out.writeAttribute("target", target, "target");
}
else {
out.startElement("a", component);
out.writeAttribute("href", "#", "href");
}
if (id != null && ! id.startsWith(UIViewRoot.UNIQUE_ID_PREFIX))
out.writeAttribute("id", component.getClientId(context), "id");
if (accesskey != null)
out.writeAttribute("accesskey", accesskey, "accesskey");
if (charset != null)
out.writeAttribute("charset", charset, "charset");
if (coords != null)
out.writeAttribute("coords", coords, "coords");
if (dir != null)
out.writeAttribute("dir", dir, "dir");
if (hreflang != null)
out.writeAttribute("hreflang", hreflang, "hreflang");
if (lang != null)
out.writeAttribute("lang", lang, "lang");
if (onblur != null)
out.writeAttribute("onblur", onblur, "onblur");
if (disabled) {
}
else {
HtmlFormRenderer.addCommandLinkHiddenField(context,
formClientId,
hiddenFieldName);
StringBuilder clickJs = new StringBuilder();
clickJs.append("document.forms['");
clickJs.append(formClientId);
clickJs.append("']['");
clickJs.append(hiddenFieldName);
clickJs.append("'].value='");
clickJs.append(clientId);
clickJs.append("';");
final int childCount = component.getChildCount();
if (childCount > 0 && !disabled) {
List<UIComponent> children = component.getChildren();
for (int i = 0; i < childCount; i++) {
UIComponent child = children.get(i);
if (child instanceof UIParameter) {
UIParameter param = (UIParameter) child;
String enc = out.getCharacterEncoding();
clickJs.append("document.forms['");
clickJs.append(formClientId);
clickJs.append("']['");
String name = param.getName();
String encodedName = URLEncoder.encode(name, enc);
- HtmlFormRenderer.addCommandLinkParam(context, formClientId, name);
+ HtmlFormRenderer.addCommandLinkParam(context, formClientId, encodedName);
clickJs.append(encodedName);
clickJs.append("'].value='");
String val = toString(context, param, param.getValue());
String encodedVal = URLEncoder.encode(val, enc);
clickJs.append(encodedVal);
clickJs.append("';");
}
}
}
if (target != null) {
clickJs.append("document.forms['");
clickJs.append(formClientId);
clickJs.append("'].target='");
clickJs.append(target);
clickJs.append("';");
}
clickJs.append("document.forms['");
clickJs.append(formClientId);
clickJs.append("'].submit();");
clickJs.append("return false;");
if (onclick != null) {
String code = ("var a = function(){" + onclick + "};"
+ "var b = function() {" + clickJs + "};"
+ "return a() && b();");
out.writeAttribute("onclick", code, "onclick");
}
else
out.writeAttribute("onclick", clickJs.toString(), "onclick");
}
if (ondblclick != null)
out.writeAttribute("ondblclick", ondblclick, "ondblclick");
if (onfocus != null)
out.writeAttribute("onfocus", onfocus, "onfocus");
if (onkeydown != null)
out.writeAttribute("onkeydown", onkeydown, "onkeydown");
if (onkeypress != null)
out.writeAttribute("onkeypress", onkeypress, "onkeypress");
if (onkeyup != null)
out.writeAttribute("onkeyup", onkeyup, "onkeyup");
if (onmousedown != null)
out.writeAttribute("onmousedown", onmousedown, "onmousedown");
if (onmousemove != null)
out.writeAttribute("onmousemove", onmousemove, "onmousemove");
if (onmouseout != null)
out.writeAttribute("onmouseout", onmouseout, "onmouseout");
if (onmouseover != null)
out.writeAttribute("onmouseover", onmouseover, "onmouseover");
if (onmouseup != null)
out.writeAttribute("onmouseup", onmouseup, "onmouseup");
if (rel != null)
out.writeAttribute("rel", rel, "rel");
if (rev != null)
out.writeAttribute("rev", rev, "rev");
if (shape != null)
out.writeAttribute("shape", shape, "shape");
if (style != null)
out.writeAttribute("style", style, "style");
if (styleClass != null)
out.writeAttribute("class", styleClass, "class");
if (tabindex != null)
out.writeAttribute("tabindex", tabindex, "tabindex");
if (title != null)
out.writeAttribute("title", title, "title");
if (type != null)
out.writeAttribute("type", type, "type");
if (value != null)
out.writeText(toString(context, component, value), "value");
final int childCount = component.getChildCount();
if (childCount > 0) {
List<UIComponent> children = component.getChildren();
for (int i = 0; i < childCount; i++) {
UIComponent child = children.get(i);
if (child instanceof UIParameter) {
}
else if (child.isRendered()) {
child.encodeBegin(context);
child.encodeChildren(context);
child.encodeEnd(context);
}
}
}
if (disabled)
out.endElement("span");
else
out.endElement("a");
}
private String getFormId(FacesContext context, UIComponent component)
{
for (UIComponent ptr = component.getParent();
ptr != null;
ptr = ptr.getParent()) {
if (ptr instanceof UIForm) {
return ptr.getClientId(context);
}
}
return "";
}
/**
* Renders the content for the component.
*/
@Override
public void encodeChildren(FacesContext context, UIComponent component)
throws IOException
{
}
/**
* Renders the closing tag for the component.
*/
@Override
public void encodeEnd(FacesContext context, UIComponent component)
throws IOException
{
}
public String toString()
{
return "HtmlInputTextRenderer[]";
}
}
| true | true | public void encodeBegin(FacesContext context, UIComponent component)
throws IOException
{
ResponseWriter out = context.getResponseWriter();
String id = component.getId();
String accesskey;
String charset;
String coords;
String dir;
boolean disabled;
String hreflang;
String lang;
String onblur;
String onclick;
String ondblclick;
String onfocus;
String onkeydown;
String onkeypress;
String onkeyup;
String onmousedown;
String onmousemove;
String onmouseout;
String onmouseover;
String onmouseup;
String rel;
String rev;
String shape;
String style;
String styleClass;
String tabindex;
String target;
String title;
String type;
Object value;
if (component instanceof HtmlCommandLink) {
HtmlCommandLink htmlCommandLink = (HtmlCommandLink) component;
accesskey = htmlCommandLink.getAccesskey();
charset = htmlCommandLink.getCharset();
coords = htmlCommandLink.getCoords();
dir = htmlCommandLink.getDir();
disabled = htmlCommandLink.isDisabled();
hreflang = htmlCommandLink.getHreflang();
lang = htmlCommandLink.getLang();
onblur = htmlCommandLink.getOnblur();
onclick = htmlCommandLink.getOnclick();
ondblclick = htmlCommandLink.getOndblclick();
onfocus = htmlCommandLink.getOnfocus();
onkeydown = htmlCommandLink.getOnkeydown();
onkeypress = htmlCommandLink.getOnkeypress();
onkeyup = htmlCommandLink.getOnkeyup();
onmousedown = htmlCommandLink.getOnmousedown();
onmousemove = htmlCommandLink.getOnmousemove();
onmouseout = htmlCommandLink.getOnmouseout();
onmouseover = htmlCommandLink.getOnmouseover();
onmouseup = htmlCommandLink.getOnmouseup();
rel = htmlCommandLink.getRel();
rev = htmlCommandLink.getRev();
shape = htmlCommandLink.getShape();
style = htmlCommandLink.getStyle();
styleClass = htmlCommandLink.getStyleClass();
tabindex = htmlCommandLink.getTabindex();
title = htmlCommandLink.getTitle();
type = htmlCommandLink.getType();
target = htmlCommandLink.getTarget();
value = htmlCommandLink.getValue();
}
else {
Map<String,Object> attrMap = component.getAttributes();
accesskey = (String) attrMap.get("accesskey");
charset = (String) attrMap.get("charset");
coords = (String) attrMap.get("coords");
dir = (String) attrMap.get("dir");
disabled = (Boolean) attrMap.get("disabled");
hreflang = (String) attrMap.get("hreflang");
lang = (String) attrMap.get("lang");
onblur = (String) attrMap.get("onblur");
onclick = (String) attrMap.get("onclick");
ondblclick = (String) attrMap.get("ondblclick");
onfocus = (String) attrMap.get("onfocus");
onkeydown = (String) attrMap.get("onkeydown");
onkeypress = (String) attrMap.get("onkeypress");
onkeyup = (String) attrMap.get("onkeyup");
onmousedown = (String) attrMap.get("onmousedown");
onmousemove = (String) attrMap.get("onmousemove");
onmouseout = (String) attrMap.get("onmouseout");
onmouseover = (String) attrMap.get("onmouseover");
onmouseup = (String) attrMap.get("onmouseup");
rel = (String) attrMap.get("rel");
rev = (String) attrMap.get("rev");
shape = (String) attrMap.get("shape");
style = (String) attrMap.get("style");
styleClass = (String) attrMap.get("styleClass");
tabindex = (String) attrMap.get("tabindex");
title = (String) attrMap.get("title");
type = (String) attrMap.get("type");
target = (String)attrMap.get("target");
value = attrMap.get("value");
}
String clientId = component.getClientId(context);
String formClientId = getFormId(context, component);
String hiddenFieldName = clientId + ":link";
if (disabled) {
out.startElement("span", component);
if (target != null)
out.writeAttribute("target", target, "target");
}
else {
out.startElement("a", component);
out.writeAttribute("href", "#", "href");
}
if (id != null && ! id.startsWith(UIViewRoot.UNIQUE_ID_PREFIX))
out.writeAttribute("id", component.getClientId(context), "id");
if (accesskey != null)
out.writeAttribute("accesskey", accesskey, "accesskey");
if (charset != null)
out.writeAttribute("charset", charset, "charset");
if (coords != null)
out.writeAttribute("coords", coords, "coords");
if (dir != null)
out.writeAttribute("dir", dir, "dir");
if (hreflang != null)
out.writeAttribute("hreflang", hreflang, "hreflang");
if (lang != null)
out.writeAttribute("lang", lang, "lang");
if (onblur != null)
out.writeAttribute("onblur", onblur, "onblur");
if (disabled) {
}
else {
HtmlFormRenderer.addCommandLinkHiddenField(context,
formClientId,
hiddenFieldName);
StringBuilder clickJs = new StringBuilder();
clickJs.append("document.forms['");
clickJs.append(formClientId);
clickJs.append("']['");
clickJs.append(hiddenFieldName);
clickJs.append("'].value='");
clickJs.append(clientId);
clickJs.append("';");
final int childCount = component.getChildCount();
if (childCount > 0 && !disabled) {
List<UIComponent> children = component.getChildren();
for (int i = 0; i < childCount; i++) {
UIComponent child = children.get(i);
if (child instanceof UIParameter) {
UIParameter param = (UIParameter) child;
String enc = out.getCharacterEncoding();
clickJs.append("document.forms['");
clickJs.append(formClientId);
clickJs.append("']['");
String name = param.getName();
String encodedName = URLEncoder.encode(name, enc);
HtmlFormRenderer.addCommandLinkParam(context, formClientId, name);
clickJs.append(encodedName);
clickJs.append("'].value='");
String val = toString(context, param, param.getValue());
String encodedVal = URLEncoder.encode(val, enc);
clickJs.append(encodedVal);
clickJs.append("';");
}
}
}
if (target != null) {
clickJs.append("document.forms['");
clickJs.append(formClientId);
clickJs.append("'].target='");
clickJs.append(target);
clickJs.append("';");
}
clickJs.append("document.forms['");
clickJs.append(formClientId);
clickJs.append("'].submit();");
clickJs.append("return false;");
if (onclick != null) {
String code = ("var a = function(){" + onclick + "};"
+ "var b = function() {" + clickJs + "};"
+ "return a() && b();");
out.writeAttribute("onclick", code, "onclick");
}
else
out.writeAttribute("onclick", clickJs.toString(), "onclick");
}
if (ondblclick != null)
out.writeAttribute("ondblclick", ondblclick, "ondblclick");
if (onfocus != null)
out.writeAttribute("onfocus", onfocus, "onfocus");
if (onkeydown != null)
out.writeAttribute("onkeydown", onkeydown, "onkeydown");
if (onkeypress != null)
out.writeAttribute("onkeypress", onkeypress, "onkeypress");
if (onkeyup != null)
out.writeAttribute("onkeyup", onkeyup, "onkeyup");
if (onmousedown != null)
out.writeAttribute("onmousedown", onmousedown, "onmousedown");
if (onmousemove != null)
out.writeAttribute("onmousemove", onmousemove, "onmousemove");
if (onmouseout != null)
out.writeAttribute("onmouseout", onmouseout, "onmouseout");
if (onmouseover != null)
out.writeAttribute("onmouseover", onmouseover, "onmouseover");
if (onmouseup != null)
out.writeAttribute("onmouseup", onmouseup, "onmouseup");
if (rel != null)
out.writeAttribute("rel", rel, "rel");
if (rev != null)
out.writeAttribute("rev", rev, "rev");
if (shape != null)
out.writeAttribute("shape", shape, "shape");
if (style != null)
out.writeAttribute("style", style, "style");
if (styleClass != null)
out.writeAttribute("class", styleClass, "class");
if (tabindex != null)
out.writeAttribute("tabindex", tabindex, "tabindex");
if (title != null)
out.writeAttribute("title", title, "title");
if (type != null)
out.writeAttribute("type", type, "type");
if (value != null)
out.writeText(toString(context, component, value), "value");
final int childCount = component.getChildCount();
if (childCount > 0) {
List<UIComponent> children = component.getChildren();
for (int i = 0; i < childCount; i++) {
UIComponent child = children.get(i);
if (child instanceof UIParameter) {
}
else if (child.isRendered()) {
child.encodeBegin(context);
child.encodeChildren(context);
child.encodeEnd(context);
}
}
}
if (disabled)
out.endElement("span");
else
out.endElement("a");
}
| public void encodeBegin(FacesContext context, UIComponent component)
throws IOException
{
ResponseWriter out = context.getResponseWriter();
String id = component.getId();
String accesskey;
String charset;
String coords;
String dir;
boolean disabled;
String hreflang;
String lang;
String onblur;
String onclick;
String ondblclick;
String onfocus;
String onkeydown;
String onkeypress;
String onkeyup;
String onmousedown;
String onmousemove;
String onmouseout;
String onmouseover;
String onmouseup;
String rel;
String rev;
String shape;
String style;
String styleClass;
String tabindex;
String target;
String title;
String type;
Object value;
if (component instanceof HtmlCommandLink) {
HtmlCommandLink htmlCommandLink = (HtmlCommandLink) component;
accesskey = htmlCommandLink.getAccesskey();
charset = htmlCommandLink.getCharset();
coords = htmlCommandLink.getCoords();
dir = htmlCommandLink.getDir();
disabled = htmlCommandLink.isDisabled();
hreflang = htmlCommandLink.getHreflang();
lang = htmlCommandLink.getLang();
onblur = htmlCommandLink.getOnblur();
onclick = htmlCommandLink.getOnclick();
ondblclick = htmlCommandLink.getOndblclick();
onfocus = htmlCommandLink.getOnfocus();
onkeydown = htmlCommandLink.getOnkeydown();
onkeypress = htmlCommandLink.getOnkeypress();
onkeyup = htmlCommandLink.getOnkeyup();
onmousedown = htmlCommandLink.getOnmousedown();
onmousemove = htmlCommandLink.getOnmousemove();
onmouseout = htmlCommandLink.getOnmouseout();
onmouseover = htmlCommandLink.getOnmouseover();
onmouseup = htmlCommandLink.getOnmouseup();
rel = htmlCommandLink.getRel();
rev = htmlCommandLink.getRev();
shape = htmlCommandLink.getShape();
style = htmlCommandLink.getStyle();
styleClass = htmlCommandLink.getStyleClass();
tabindex = htmlCommandLink.getTabindex();
title = htmlCommandLink.getTitle();
type = htmlCommandLink.getType();
target = htmlCommandLink.getTarget();
value = htmlCommandLink.getValue();
}
else {
Map<String,Object> attrMap = component.getAttributes();
accesskey = (String) attrMap.get("accesskey");
charset = (String) attrMap.get("charset");
coords = (String) attrMap.get("coords");
dir = (String) attrMap.get("dir");
disabled = (Boolean) attrMap.get("disabled");
hreflang = (String) attrMap.get("hreflang");
lang = (String) attrMap.get("lang");
onblur = (String) attrMap.get("onblur");
onclick = (String) attrMap.get("onclick");
ondblclick = (String) attrMap.get("ondblclick");
onfocus = (String) attrMap.get("onfocus");
onkeydown = (String) attrMap.get("onkeydown");
onkeypress = (String) attrMap.get("onkeypress");
onkeyup = (String) attrMap.get("onkeyup");
onmousedown = (String) attrMap.get("onmousedown");
onmousemove = (String) attrMap.get("onmousemove");
onmouseout = (String) attrMap.get("onmouseout");
onmouseover = (String) attrMap.get("onmouseover");
onmouseup = (String) attrMap.get("onmouseup");
rel = (String) attrMap.get("rel");
rev = (String) attrMap.get("rev");
shape = (String) attrMap.get("shape");
style = (String) attrMap.get("style");
styleClass = (String) attrMap.get("styleClass");
tabindex = (String) attrMap.get("tabindex");
title = (String) attrMap.get("title");
type = (String) attrMap.get("type");
target = (String)attrMap.get("target");
value = attrMap.get("value");
}
String clientId = component.getClientId(context);
String formClientId = getFormId(context, component);
String hiddenFieldName = clientId + ":link";
if (disabled) {
out.startElement("span", component);
if (target != null)
out.writeAttribute("target", target, "target");
}
else {
out.startElement("a", component);
out.writeAttribute("href", "#", "href");
}
if (id != null && ! id.startsWith(UIViewRoot.UNIQUE_ID_PREFIX))
out.writeAttribute("id", component.getClientId(context), "id");
if (accesskey != null)
out.writeAttribute("accesskey", accesskey, "accesskey");
if (charset != null)
out.writeAttribute("charset", charset, "charset");
if (coords != null)
out.writeAttribute("coords", coords, "coords");
if (dir != null)
out.writeAttribute("dir", dir, "dir");
if (hreflang != null)
out.writeAttribute("hreflang", hreflang, "hreflang");
if (lang != null)
out.writeAttribute("lang", lang, "lang");
if (onblur != null)
out.writeAttribute("onblur", onblur, "onblur");
if (disabled) {
}
else {
HtmlFormRenderer.addCommandLinkHiddenField(context,
formClientId,
hiddenFieldName);
StringBuilder clickJs = new StringBuilder();
clickJs.append("document.forms['");
clickJs.append(formClientId);
clickJs.append("']['");
clickJs.append(hiddenFieldName);
clickJs.append("'].value='");
clickJs.append(clientId);
clickJs.append("';");
final int childCount = component.getChildCount();
if (childCount > 0 && !disabled) {
List<UIComponent> children = component.getChildren();
for (int i = 0; i < childCount; i++) {
UIComponent child = children.get(i);
if (child instanceof UIParameter) {
UIParameter param = (UIParameter) child;
String enc = out.getCharacterEncoding();
clickJs.append("document.forms['");
clickJs.append(formClientId);
clickJs.append("']['");
String name = param.getName();
String encodedName = URLEncoder.encode(name, enc);
HtmlFormRenderer.addCommandLinkParam(context, formClientId, encodedName);
clickJs.append(encodedName);
clickJs.append("'].value='");
String val = toString(context, param, param.getValue());
String encodedVal = URLEncoder.encode(val, enc);
clickJs.append(encodedVal);
clickJs.append("';");
}
}
}
if (target != null) {
clickJs.append("document.forms['");
clickJs.append(formClientId);
clickJs.append("'].target='");
clickJs.append(target);
clickJs.append("';");
}
clickJs.append("document.forms['");
clickJs.append(formClientId);
clickJs.append("'].submit();");
clickJs.append("return false;");
if (onclick != null) {
String code = ("var a = function(){" + onclick + "};"
+ "var b = function() {" + clickJs + "};"
+ "return a() && b();");
out.writeAttribute("onclick", code, "onclick");
}
else
out.writeAttribute("onclick", clickJs.toString(), "onclick");
}
if (ondblclick != null)
out.writeAttribute("ondblclick", ondblclick, "ondblclick");
if (onfocus != null)
out.writeAttribute("onfocus", onfocus, "onfocus");
if (onkeydown != null)
out.writeAttribute("onkeydown", onkeydown, "onkeydown");
if (onkeypress != null)
out.writeAttribute("onkeypress", onkeypress, "onkeypress");
if (onkeyup != null)
out.writeAttribute("onkeyup", onkeyup, "onkeyup");
if (onmousedown != null)
out.writeAttribute("onmousedown", onmousedown, "onmousedown");
if (onmousemove != null)
out.writeAttribute("onmousemove", onmousemove, "onmousemove");
if (onmouseout != null)
out.writeAttribute("onmouseout", onmouseout, "onmouseout");
if (onmouseover != null)
out.writeAttribute("onmouseover", onmouseover, "onmouseover");
if (onmouseup != null)
out.writeAttribute("onmouseup", onmouseup, "onmouseup");
if (rel != null)
out.writeAttribute("rel", rel, "rel");
if (rev != null)
out.writeAttribute("rev", rev, "rev");
if (shape != null)
out.writeAttribute("shape", shape, "shape");
if (style != null)
out.writeAttribute("style", style, "style");
if (styleClass != null)
out.writeAttribute("class", styleClass, "class");
if (tabindex != null)
out.writeAttribute("tabindex", tabindex, "tabindex");
if (title != null)
out.writeAttribute("title", title, "title");
if (type != null)
out.writeAttribute("type", type, "type");
if (value != null)
out.writeText(toString(context, component, value), "value");
final int childCount = component.getChildCount();
if (childCount > 0) {
List<UIComponent> children = component.getChildren();
for (int i = 0; i < childCount; i++) {
UIComponent child = children.get(i);
if (child instanceof UIParameter) {
}
else if (child.isRendered()) {
child.encodeBegin(context);
child.encodeChildren(context);
child.encodeEnd(context);
}
}
}
if (disabled)
out.endElement("span");
else
out.endElement("a");
}
|
diff --git a/src/plugin/jdbc/src/org/rapidcontext/app/plugin/jdbc/JdbcConnection.java b/src/plugin/jdbc/src/org/rapidcontext/app/plugin/jdbc/JdbcConnection.java
index 0648934..47ab9c5 100644
--- a/src/plugin/jdbc/src/org/rapidcontext/app/plugin/jdbc/JdbcConnection.java
+++ b/src/plugin/jdbc/src/org/rapidcontext/app/plugin/jdbc/JdbcConnection.java
@@ -1,264 +1,264 @@
/*
* RapidContext JDBC plug-in <http://www.rapidcontext.com/>
* Copyright (c) 2007-2010 Per Cederberg. All rights reserved.
*
* This program is free software: you can redistribute it and/or
* modify it under the terms of the BSD license.
*
* 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 RapidContext LICENSE.txt file for more details.
*/
package org.rapidcontext.app.plugin.jdbc;
import org.rapidcontext.app.ApplicationContext;
import org.rapidcontext.core.data.Dict;
import org.rapidcontext.core.data.PropertiesSerializer;
import org.rapidcontext.core.storage.StorageException;
import org.rapidcontext.core.type.Channel;
import org.rapidcontext.core.type.Connection;
import org.rapidcontext.core.type.ConnectionException;
import java.sql.Driver;
import java.util.Properties;
import java.util.logging.Logger;
/**
* A JDBC connectivity adapter. This adapter allows execution of SQL
* queries and statements to any JDBC data source. Connections may be
* pooled for maximum resource utilization.
*
* @author Per Cederberg
* @version 1.0
*/
public class JdbcConnection extends Connection {
/**
* The class logger.
*/
private static final Logger LOG =
Logger.getLogger(JdbcConnection.class.getName());
/**
* The JDBC driver configuration parameter name.
*/
protected static final String JDBC_DRIVER = "driver";
/**
* The JDBC URL configuration parameter name.
*/
protected static final String JDBC_URL = "url";
/**
* The JDBC user configuration parameter name.
*/
protected static final String JDBC_USER = "user";
/**
* The JDBC password configuration parameter name.
*/
protected static final String JDBC_PASSWORD = "password";
/**
* The JDBC SQL ping configuration parameter name (optional,
* defaults to 'SELECT 1').
*/
protected static final String JDBC_PING = "sqlping";
/**
* The JDBC auto-commit configuration parameter name (optional,
* defaults to false).
*/
protected static final String JDBC_AUTOCOMMIT = "autocommit";
/**
* The JDBC connection and query timeout configuration parameter name.
*/
protected static final String JDBC_TIMEOUT = "timeout";
/**
* Creates a new JDBC connection from a serialized representation.
*
* @param id the object identifier
* @param type the object type name
* @param dict the serialized representation
*/
public JdbcConnection(String id, String type, Dict dict) {
super(id, type, dict);
}
/**
* Initializes this connection after loading it from a storage.
*
* @throws StorageException if the initialization failed
*/
protected void init() throws StorageException {
String driver;
String url;
String ping;
driver = dict.getString(JDBC_DRIVER, "").trim();
url = dict.getString(JDBC_URL, "").trim().toLowerCase();
ping = dict.getString(JDBC_PING, "").trim();
if (driver.isEmpty()) {
if (url.startsWith("jdbc:odbc")) {
dict.set("_" + JDBC_DRIVER, "sun.jdbc.odbc.JdbcOdbcDriver");
} else if (url.startsWith("jdbc:mysql:")) {
dict.set("_" + JDBC_DRIVER, "com.mysql.jdbc.Driver");
} else if (url.startsWith("jdbc:postgresql:")) {
dict.set("_" + JDBC_DRIVER, "org.postgresql.Driver");
} else if (url.startsWith("jdbc:oracle:")) {
dict.set("_" + JDBC_DRIVER, "oracle.jdbc.driver.OracleDriver");
} else if (url.startsWith("jdbc:db2:")) {
dict.set("_" + JDBC_DRIVER, "COM.ibm.db2.jdbc.app.DB2Driver");
} else if (url.startsWith("jdbc:microsoft:")) {
dict.set("_" + JDBC_DRIVER, "com.microsoft.sqlserver.jdbc.SQLServerDriver");
}
} else {
dict.set("_" + JDBC_DRIVER, driver);
}
if (ping.isEmpty() && url.startsWith("jdbc:oracle:")) {
- dict.set("_" + JDBC_PING, "SELECT * FROM dual");
+ dict.set("_" + JDBC_PING, "SELECT 1 FROM dual");
} else if (ping.isEmpty()) {
dict.set("_" + JDBC_PING, "SELECT 1");
} else {
dict.set("_" + JDBC_PING, ping);
}
dict.setBoolean("_" + JDBC_AUTOCOMMIT, autoCommit());
dict.setInt("_" + JDBC_TIMEOUT, timeout());
super.init();
}
/**
* Destroys this connection. This method overrides the default to
* provide package access to it when testing connections.
*/
protected void destroy() {
super.destroy();
}
/**
* Returns the JDBC driver class for this connection. The class
* will be loaded using the application context class loader.
*
* @return the JDBC driver class
*
* @throws ConnectionException if the class couldn't be found
* or wasn't of the correct Java type
*/
public Driver driver() throws ConnectionException {
ClassLoader loader;
String driverClass;
String msg;
if (dict.containsKey("_" + JDBC_DRIVER)) {
driverClass = dict.getString("_" + JDBC_DRIVER, "");
} else {
driverClass = dict.getString(JDBC_DRIVER, "");
}
try {
loader = ApplicationContext.getInstance().getClassLoader();
return (Driver) loader.loadClass(driverClass).newInstance();
} catch (ClassNotFoundException e) {
msg = "couldn't find or load JDBC driver class " + driverClass +
": " + e.getMessage();
throw new ConnectionException(msg);
} catch (ClassCastException e) {
msg = "couldn't load JDBC driver, must be an instance of " +
"java.sql.Driver: " + driverClass;
throw new ConnectionException(msg);
} catch (Exception e) {
msg = "couldn't create JDBC driver instance of " + driverClass +
": " + e.getMessage();
throw new ConnectionException(msg);
}
}
/**
* Returns the JDBC connection URL.
*
* @return the JDBC connection URL
*/
public String url() {
return dict.getString(JDBC_URL, "");
}
/**
* Returns the SQL ping query.
*
* @return the SQL ping query, or
* null if not configured
*/
public String ping() {
if (dict.containsKey("_" + JDBC_PING)) {
return dict.getString("_" + JDBC_PING, null);
} else {
return dict.getString(JDBC_PING, null);
}
}
/**
* Returns the auto-commit (after each SQL) flag.
*
* @return the auto-commit flag
*/
public boolean autoCommit() {
if (dict.containsKey("_" + JDBC_AUTOCOMMIT)) {
return dict.getBoolean("_" + JDBC_AUTOCOMMIT, false);
} else {
return dict.getBoolean(JDBC_AUTOCOMMIT, false);
}
}
/**
* Returns the connection and query timeout (in seconds).
*
* @return the connection and query timeout (in seconds)
*/
public int timeout() {
try {
if (dict.containsKey("_" + JDBC_TIMEOUT)) {
return dict.getInt("_" + JDBC_TIMEOUT, 30);
} else {
return dict.getInt(JDBC_TIMEOUT, 30);
}
} catch (Exception e) {
LOG.warning(this + ": failed to parse timeout value: " +
dict.get(JDBC_TIMEOUT));
dict.setInt("_" + JDBC_TIMEOUT, 30);
return 30;
}
}
/**
* Creates a new connection channel.
*
* @return the channel created
*
* @throws ConnectionException if the channel couldn't be created
* properly
*/
protected Channel createChannel() throws ConnectionException {
Properties props;
props = PropertiesSerializer.toProperties(dict);
props.remove(KEY_ID);
props.remove(KEY_TYPE);
props.remove(KEY_MAX_OPEN);
props.remove(KEY_MAX_IDLE_SECS);
return new JdbcChannel(this, props);
}
/**
* Destroys a connection channel, freeing any resources used
* (such as database connections, networking sockets, etc).
*
* @param channel the channel to destroy
*/
protected void destroyChannel(Channel channel) {
((JdbcChannel) channel).close();
}
}
| true | true | protected void init() throws StorageException {
String driver;
String url;
String ping;
driver = dict.getString(JDBC_DRIVER, "").trim();
url = dict.getString(JDBC_URL, "").trim().toLowerCase();
ping = dict.getString(JDBC_PING, "").trim();
if (driver.isEmpty()) {
if (url.startsWith("jdbc:odbc")) {
dict.set("_" + JDBC_DRIVER, "sun.jdbc.odbc.JdbcOdbcDriver");
} else if (url.startsWith("jdbc:mysql:")) {
dict.set("_" + JDBC_DRIVER, "com.mysql.jdbc.Driver");
} else if (url.startsWith("jdbc:postgresql:")) {
dict.set("_" + JDBC_DRIVER, "org.postgresql.Driver");
} else if (url.startsWith("jdbc:oracle:")) {
dict.set("_" + JDBC_DRIVER, "oracle.jdbc.driver.OracleDriver");
} else if (url.startsWith("jdbc:db2:")) {
dict.set("_" + JDBC_DRIVER, "COM.ibm.db2.jdbc.app.DB2Driver");
} else if (url.startsWith("jdbc:microsoft:")) {
dict.set("_" + JDBC_DRIVER, "com.microsoft.sqlserver.jdbc.SQLServerDriver");
}
} else {
dict.set("_" + JDBC_DRIVER, driver);
}
if (ping.isEmpty() && url.startsWith("jdbc:oracle:")) {
dict.set("_" + JDBC_PING, "SELECT * FROM dual");
} else if (ping.isEmpty()) {
dict.set("_" + JDBC_PING, "SELECT 1");
} else {
dict.set("_" + JDBC_PING, ping);
}
dict.setBoolean("_" + JDBC_AUTOCOMMIT, autoCommit());
dict.setInt("_" + JDBC_TIMEOUT, timeout());
super.init();
}
| protected void init() throws StorageException {
String driver;
String url;
String ping;
driver = dict.getString(JDBC_DRIVER, "").trim();
url = dict.getString(JDBC_URL, "").trim().toLowerCase();
ping = dict.getString(JDBC_PING, "").trim();
if (driver.isEmpty()) {
if (url.startsWith("jdbc:odbc")) {
dict.set("_" + JDBC_DRIVER, "sun.jdbc.odbc.JdbcOdbcDriver");
} else if (url.startsWith("jdbc:mysql:")) {
dict.set("_" + JDBC_DRIVER, "com.mysql.jdbc.Driver");
} else if (url.startsWith("jdbc:postgresql:")) {
dict.set("_" + JDBC_DRIVER, "org.postgresql.Driver");
} else if (url.startsWith("jdbc:oracle:")) {
dict.set("_" + JDBC_DRIVER, "oracle.jdbc.driver.OracleDriver");
} else if (url.startsWith("jdbc:db2:")) {
dict.set("_" + JDBC_DRIVER, "COM.ibm.db2.jdbc.app.DB2Driver");
} else if (url.startsWith("jdbc:microsoft:")) {
dict.set("_" + JDBC_DRIVER, "com.microsoft.sqlserver.jdbc.SQLServerDriver");
}
} else {
dict.set("_" + JDBC_DRIVER, driver);
}
if (ping.isEmpty() && url.startsWith("jdbc:oracle:")) {
dict.set("_" + JDBC_PING, "SELECT 1 FROM dual");
} else if (ping.isEmpty()) {
dict.set("_" + JDBC_PING, "SELECT 1");
} else {
dict.set("_" + JDBC_PING, ping);
}
dict.setBoolean("_" + JDBC_AUTOCOMMIT, autoCommit());
dict.setInt("_" + JDBC_TIMEOUT, timeout());
super.init();
}
|
diff --git a/servers/sip-servlets/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/startup/SipStandardContext.java b/servers/sip-servlets/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/startup/SipStandardContext.java
index 8d600a960..a761317ed 100644
--- a/servers/sip-servlets/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/startup/SipStandardContext.java
+++ b/servers/sip-servlets/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/startup/SipStandardContext.java
@@ -1,854 +1,861 @@
/*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.mobicents.servlet.sip.startup;
import java.io.File;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import java.util.concurrent.CopyOnWriteArrayList;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.sip.SipServletRequest;
import javax.servlet.sip.SipSessionsUtil;
import javax.servlet.sip.TimerService;
import org.apache.catalina.Container;
import org.apache.catalina.Engine;
import org.apache.catalina.Globals;
import org.apache.catalina.Host;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.Manager;
import org.apache.catalina.Service;
import org.apache.catalina.Wrapper;
import org.apache.catalina.core.NamingContextListener;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.deploy.LoginConfig;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.mobicents.servlet.sip.annotations.SipAnnotationProcessor;
import org.mobicents.servlet.sip.core.SipApplicationDispatcher;
import org.mobicents.servlet.sip.core.session.SipListenersHolder;
import org.mobicents.servlet.sip.core.session.SipManager;
import org.mobicents.servlet.sip.core.session.SipSessionsUtilImpl;
import org.mobicents.servlet.sip.core.session.SipStandardManager;
import org.mobicents.servlet.sip.core.timers.TimerServiceImpl;
import org.mobicents.servlet.sip.message.SipFactoryFacade;
import org.mobicents.servlet.sip.message.SipFactoryImpl;
import org.mobicents.servlet.sip.startup.loading.SipLoginConfig;
import org.mobicents.servlet.sip.startup.loading.SipSecurityConstraint;
import org.mobicents.servlet.sip.startup.loading.SipServletImpl;
import org.mobicents.servlet.sip.startup.loading.SipServletMapping;
/**
* Sip implementation of the <b>Context</b> interface extending the standard
* tomcat context to allow deployment of converged applications (sip & web apps)
* as well as standalone sip servlets applications.
*
* @author Jean Deruelle
*
*/
public class SipStandardContext extends StandardContext implements SipContext {
// the logger
private static transient Log logger = LogFactory
.getLog(SipStandardContext.class);
/**
* The descriptive information string for this implementation.
*/
private static final String info =
"org.mobicents.servlet.sip.startup.SipStandardContext/1.0";
// as mentionned per JSR 289 Section 6.1.2.1 default lifetime for an
// application session is 3 minutes
private static int DEFAULT_LIFETIME = 3;
protected String applicationName;
protected String smallIcon;
protected String largeIcon;
protected String description;
protected int proxyTimeout;
protected int sipApplicationSessionTimeout;
protected SipListenersHolder listeners;
protected String mainServlet;
protected SipFactoryFacade sipFactoryFacade;
protected SipSessionsUtilImpl sipSessionsUtil;
protected SipLoginConfig sipLoginConfig;
protected String namingContextName;
protected Method sipApplicationKeyMethod;
/**
* The set of sip application listener class names configured for this
* application, in the order they were encountered in the sip.xml file.
*/
protected List<String> sipApplicationListeners = new CopyOnWriteArrayList<String>();
/**
* The set of sip servlet mapping configured for this
* application.
*/
protected List<SipServletMapping> sipServletMappings = new ArrayList<SipServletMapping>();
protected SipApplicationDispatcher sipApplicationDispatcher = null;
protected Map<String, Container> childrenMap;
/**
*
*/
public SipStandardContext() {
super();
sipApplicationSessionTimeout = DEFAULT_LIFETIME;
pipeline.setBasic(new SipStandardContextValve());
listeners = new SipListenersHolder(this);
childrenMap = new HashMap<String, Container>();
}
@Override
public void init() throws Exception {
if(logger.isInfoEnabled()) {
logger.info("Initializing the sip context");
}
// if (this.getParent() != null) {
// // Add the main configuration listener for sip applications
// LifecycleListener sipConfigurationListener = new SipContextConfig();
// this.addLifecycleListener(sipConfigurationListener);
// setDelegate(true);
// }
// call the super method to correctly initialize the context and fire
// up the
// init event on the new registered SipContextConfig, so that the
// standardcontextconfig
// is correctly initialized too
super.init();
prepareServletContext();
if(logger.isInfoEnabled()) {
logger.info("sip context Initialized");
}
}
protected void prepareServletContext() throws LifecycleException {
if(sipApplicationDispatcher == null) {
setApplicationDispatcher();
}
if(sipFactoryFacade == null) {
sipFactoryFacade = new SipFactoryFacade((SipFactoryImpl)sipApplicationDispatcher.getSipFactory(), this);
}
if(sipSessionsUtil == null) {
sipSessionsUtil = new SipSessionsUtilImpl(this);
}
//needed when restarting applications through the tomcat manager
this.getServletContext().setAttribute(javax.servlet.sip.SipServlet.SIP_FACTORY,
sipFactoryFacade);
this.getServletContext().setAttribute(javax.servlet.sip.SipServlet.TIMER_SERVICE,
TimerServiceImpl.getInstance());
this.getServletContext().setAttribute(javax.servlet.sip.SipServlet.SUPPORTED,
Arrays.asList(SipApplicationDispatcher.EXTENSIONS_SUPPORTED));
this.getServletContext().setAttribute("javax.servlet.sip.100rel", Boolean.TRUE);
this.getServletContext().setAttribute(javax.servlet.sip.SipServlet.SUPPORTED_RFCs,
Arrays.asList(SipApplicationDispatcher.RFC_SUPPORTED));
this.getServletContext().setAttribute(javax.servlet.sip.SipServlet.SIP_SESSIONS_UTIL,
sipSessionsUtil);
this.getServletContext().setAttribute(javax.servlet.sip.SipServlet.OUTBOUND_INTERFACES,
sipApplicationDispatcher.getOutboundInterfaces());
}
/**
* @throws Exception
*/
protected void setApplicationDispatcher() throws LifecycleException {
Container container = getParent().getParent();
if(container instanceof Engine) {
Service service = ((Engine)container).getService();
if(service instanceof SipService) {
sipApplicationDispatcher =
((SipService)service).getSipApplicationDispatcher();
}
}
if(sipApplicationDispatcher == null) {
throw new LifecycleException("cannot find any application dispatcher for this context " + name);
}
}
@Override
public synchronized void start() throws LifecycleException {
if(logger.isInfoEnabled()) {
logger.info("Starting the sip context");
}
if( initialized ) {
prepareServletContext();
}
// Add missing components as necessary
if (getResources() == null) { // (1) Required by Loader
if (logger.isDebugEnabled())
logger.debug("Configuring default Resources");
try {
if ((getDocBase() != null) && (getDocBase().endsWith(".sar")) && (!(new File(getBasePath())).isDirectory()))
setResources(new SARDirContext());
} catch (IllegalArgumentException e) {
logger.error("Error initializing resources: " + e.getMessage());
// ok = false;
}
}
// Configure default manager if none was specified
if (manager == null) {
if ((getCluster() != null) && getDistributable()) {
try {
manager = getCluster().createManager(getName());
} catch (Exception ex) {
logger.error("standardContext.clusterFail", ex);
// ok = false;
}
} else {
setManager(new SipStandardManager());
}
}
// Reading the "catalina.useNaming" environment variable
String useNamingProperty = System.getProperty("catalina.useNaming");
if ((useNamingProperty != null)
&& (useNamingProperty.equals("false"))) {
setUseNaming(false);
}
//activating our custom naming context to be able to set the sip factory in JNDI
if (isUseNaming()) {
if (getNamingContextListener() == null) {
NamingContextListener namingContextListener = new SipNamingContextListener();
namingContextListener.setName(getNamingContextName());
setNamingContextListener(namingContextListener);
addLifecycleListener(namingContextListener);
addContainerListener(namingContextListener);
}
// Replace the default annotation processor. This is needed to handle resource injection
// for SipFactory, Session utils and other objects residing in the servlet context space.
// Of course if the variable is not found in in the servet context it defaults to the
// normal lookup method - in the default naming context.
//tomcat naming
this.setAnnotationProcessor(
new SipAnnotationProcessor(
getNamingContextListener().getEnvContext(),
this));
} else {
// jboss or other kind of naming
try {
InitialContext iniCtx = new InitialContext();
Context envCtx = (Context) iniCtx.lookup("java:comp/env");
this.setAnnotationProcessor(
new SipAnnotationProcessor(
envCtx,
this));
} catch (NamingException e) {
logger.error("Impossible to get the naming context ", e);
}
}
//JSR 289 Section 2.1.1 Step 1.Deploy the application.
//This will make start the sip context config, which will in turn parse the sip descriptor deployment
//and call load on startup which is equivalent to
//JSR 289 Section 2.1.1 Step 2.Invoke servlet.init(), the initialization method on the Servlet. Invoke the init() on all the load-on-startup Servlets in the applicatio
super.start();
if(getAvailable()) {
// Replace the default annotation processor. This is needed to handle resource injection
// for SipFactory, Session utils and other objects residing in the servlet context space.
// Of course if the variable is not found in in the servet context it defaults to the
// normal lookup method - in the default naming context.
if(getAnnotationProcessor() == null || !(getAnnotationProcessor() instanceof SipAnnotationProcessor)) {
if(isUseNaming()) {
//tomcat naming
this.setAnnotationProcessor(
new SipAnnotationProcessor(
getNamingContextListener().getEnvContext(),
this));
} else {
// jboss or other kind of naming
try {
InitialContext iniCtx = new InitialContext();
Context envCtx = (Context) iniCtx.lookup("java:comp/env");
this.setAnnotationProcessor(
new SipAnnotationProcessor(
envCtx,
this));
} catch (NamingException e) {
logger.error("Impossible to get the naming context ", e);
}
}
}
//set the session manager on the specific sipstandardmanager to handle converged http sessions
if(getManager() instanceof SipManager) {
((SipManager)getManager()).setSipFactoryImpl(
((SipFactoryImpl)sipApplicationDispatcher.getSipFactory()));
((SipManager)manager).setContainer(this);
}
+ // JSR 289 16.2 Servlet Selection
+ // When using this mechanism (the main-servlet) for servlet selection,
+ // if there is only one servlet in the application then this
+ // declaration is optional and the lone servlet becomes the main servlet
+ if((mainServlet == null || mainServlet.length() < 1) && childrenMap.size() == 1) {
+ mainServlet = childrenMap.keySet().iterator().next();
+ }
//JSR 289 Section 2.1.1 Step 3.Invoke SipApplicationRouter.applicationDeployed() for this application.
//called implicitly within sipApplicationDispatcher.addSipApplication
sipApplicationDispatcher.addSipApplication(applicationName, this);
if(logger.isInfoEnabled()) {
logger.info("sip context started");
}
} else {
if(logger.isInfoEnabled()) {
logger.info("sip context didn't started due to errors");
}
}
}
@Override
public ServletContext getServletContext() {
if (context == null) {
context = new ConvergedApplicationContext(getBasePath(), this);
if (getAltDDName() != null)
context.setAttribute(Globals.ALT_DD_ATTR,getAltDDName());
}
return ((ConvergedApplicationContext)context).getFacade();
}
@Override
public boolean listenerStart() {
boolean ok = super.listenerStart();
//the web listeners couldn't be started so we don't even try to load the sip ones
if(!ok) {
return ok;
}
if (logger.isDebugEnabled())
logger.debug("Configuring sip listeners");
// Instantiate the required listeners
ClassLoader loader = getLoader().getClassLoader();
ok = listeners.loadListeners(findSipApplicationListeners(), loader);
if(!ok) {
return ok;
}
List<ServletContextListener> servletContextListeners = listeners.getServletContextListeners();
if (servletContextListeners != null) {
ServletContextEvent event =
new ServletContextEvent(getServletContext());
for (ServletContextListener servletContextListener : servletContextListeners) {
if (servletContextListener == null)
continue;
try {
fireContainerEvent("beforeContextInitialized", servletContextListener);
servletContextListener.contextInitialized(event);
fireContainerEvent("afterContextInitialized", servletContextListener);
} catch (Throwable t) {
fireContainerEvent("afterContextInitialized", servletContextListener);
getLogger().error
(sm.getString("standardContext.listenerStart",
servletContextListener.getClass().getName()), t);
ok = false;
}
// TODO Annotation processing
}
}
return ok;
}
@Override
public boolean listenerStop() {
boolean ok = super.listenerStop();
if (logger.isDebugEnabled())
logger.debug("Sending application stop events");
List<ServletContextListener> servletContextListeners = listeners.getServletContextListeners();
if (servletContextListeners != null) {
ServletContextEvent event =
new ServletContextEvent(getServletContext());
for (ServletContextListener servletContextListener : servletContextListeners) {
if (servletContextListener == null)
continue;
try {
fireContainerEvent("beforeContextDestroyed", servletContextListener);
servletContextListener.contextDestroyed(event);
fireContainerEvent("afterContextDestroyed", servletContextListener);
} catch (Throwable t) {
fireContainerEvent("afterContextDestroyed", servletContextListener);
getLogger().error
(sm.getString("standardContext.listenerStop",
servletContextListener.getClass().getName()), t);
ok = false;
}
// TODO Annotation processing
}
}
// TODO Annotation processing check super class on tomcat 6
listeners.clean();
return ok;
}
/**
* Get base path. Copy pasted from StandardContext Tomcat class
*/
protected String getBasePath() {
String docBase = null;
Container container = this;
while (container != null) {
if (container instanceof Host)
break;
container = container.getParent();
}
File file = new File(getDocBase());
if (!file.isAbsolute()) {
if (container == null) {
docBase = (new File(engineBase(), getDocBase())).getPath();
} else {
// Use the "appBase" property of this container
String appBase = ((Host) container).getAppBase();
file = new File(appBase);
if (!file.isAbsolute())
file = new File(engineBase(), appBase);
docBase = (new File(file, getDocBase())).getPath();
}
} else {
docBase = file.getPath();
}
return docBase;
}
@Override
public synchronized void stop() throws LifecycleException {
if(logger.isInfoEnabled()) {
logger.info("Stopping the sip context");
}
((SipManager)manager).dumpSipSessions();
((SipManager)manager).dumpSipApplicationSessions();
listeners.deallocateServletsActingAsListeners();
super.stop();
// this should happen after so that applications can still do some processing
// in destroy methods to notify that context is getting destroyed and app removed
if(sipApplicationDispatcher != null) {
if(applicationName != null) {
sipApplicationDispatcher.removeSipApplication(applicationName);
} else {
logger.error("the application name is null for the following context : " + name);
}
}
// not needed since the JNDI will be destroyed automatically
// if(isUseNaming()) {
// fireContainerEvent(SipNamingContextListener.NAMING_CONTEXT_SIP_FACTORY_REMOVED_EVENT, sipFactoryFacade);
// fireContainerEvent(SipNamingContextListener.NAMING_CONTEXT_SIP_SESSIONS_UTIL_REMOVED_EVENT, sipSessionsUtil);
// fireContainerEvent(SipNamingContextListener.NAMING_CONTEXT_TIMER_SERVICE_REMOVED_EVENT, TimerServiceImpl.getInstance());
// fireContainerEvent(SipNamingContextListener.NAMING_CONTEXT_SIP_SUBCONTEXT_REMOVED_EVENT, null);
// } else {
// try {
// InitialContext iniCtx = new InitialContext();
// Context envCtx = (Context) iniCtx.lookup("java:comp/env");
// // jboss or other kind of naming
// SipNamingContextListener.removeSipFactory(envCtx, sipFactoryFacade);
// SipNamingContextListener.removeSipSessionsUtil(envCtx, sipSessionsUtil);
// SipNamingContextListener.removeTimerService(envCtx, TimerServiceImpl.getInstance());
// SipNamingContextListener.removeSipSubcontext(envCtx);
// } catch (NamingException e) {
// //It is possible that the context has already been removed so no problem,
// //we are stopping anyway
//// logger.error("Impossible to get the naming context ", e);
// }
// }
logger.info("sip context stopped");
}
@Override
public void loadOnStartup(Container[] containers) {
if(getAnnotationProcessor() instanceof SipAnnotationProcessor) {
if(getNamingContextListener() != null) {
((SipAnnotationProcessor)getAnnotationProcessor()).setContext(getNamingContextListener().getEnvContext());
} else {
try {
InitialContext iniCtx = new InitialContext();
Context envCtx = (Context) iniCtx.lookup("java:comp/env");
((SipAnnotationProcessor)getAnnotationProcessor()).setContext(envCtx);
} catch (NamingException e) {
logger.error("Impossible to get the naming context ", e);
throw new IllegalStateException(e);
}
}
}
if(isUseNaming()) {
fireContainerEvent(SipNamingContextListener.NAMING_CONTEXT_SIP_SUBCONTEXT_ADDED_EVENT, null);
fireContainerEvent(SipNamingContextListener.NAMING_CONTEXT_APPNAME_SUBCONTEXT_ADDED_EVENT, null);
fireContainerEvent(SipNamingContextListener.NAMING_CONTEXT_SIP_FACTORY_ADDED_EVENT, sipFactoryFacade);
fireContainerEvent(SipNamingContextListener.NAMING_CONTEXT_SIP_SESSIONS_UTIL_ADDED_EVENT, sipSessionsUtil);
fireContainerEvent(SipNamingContextListener.NAMING_CONTEXT_TIMER_SERVICE_ADDED_EVENT, TimerServiceImpl.getInstance());
} else {
try {
InitialContext iniCtx = new InitialContext();
Context envCtx = (Context) iniCtx.lookup("java:comp/env");
// jboss or other kind of naming
SipNamingContextListener.addSipSubcontext(envCtx);
SipNamingContextListener.addAppNameSubContext(envCtx, applicationName);
SipNamingContextListener.addSipFactory(envCtx, applicationName, sipFactoryFacade);
SipNamingContextListener.addSipSessionsUtil(envCtx, applicationName, sipSessionsUtil);
SipNamingContextListener.addTimerService(envCtx, applicationName, TimerServiceImpl.getInstance());
} catch (NamingException e) {
logger.error("Impossible to get the naming context ", e);
throw new IllegalStateException(e);
}
}
super.loadOnStartup(containers);
}
@Override
public Wrapper createWrapper() {
return super.createWrapper();
}
public void addChild(SipServletImpl sipServletImpl) {
SipServletImpl existingSipServlet = (SipServletImpl )children.get(sipServletImpl.getName());
if(existingSipServlet != null) {
logger.warn(sipServletImpl.getName() + " servlet already present, removing the previous one. " +
"This might be due to the fact that the definition of the servlet " +
"is present both in annotations and in sip.xml");
//we remove the previous one (annoations) because it may not have init parameters that has been defined in sip.xml
//See TCK Test ContextTest.testContext1
childrenMap.remove(sipServletImpl.getName());
super.removeChild(existingSipServlet);
}
childrenMap.put(sipServletImpl.getName(), sipServletImpl);
super.addChild(sipServletImpl);
}
public void removeChild(SipServletImpl sipServletImpl) {
super.removeChild(sipServletImpl);
childrenMap.remove(sipServletImpl.getName());
}
/**
* {@inheritDoc}
*/
public Map<String, Container> getChildrenMap() {
return childrenMap;
}
/* (non-Javadoc)
* @see org.mobicents.servlet.sip.startup.SipContext#getApplicationName()
*/
public String getApplicationName() {
return applicationName;
}
/* (non-Javadoc)
* @see org.mobicents.servlet.sip.startup.SipContext#setApplicationName(java.lang.String)
*/
public void setApplicationName(String applicationName) {
this.applicationName = applicationName;
}
/* (non-Javadoc)
* @see org.mobicents.servlet.sip.startup.SipContext#getDescription()
*/
public String getDescription() {
return description;
}
/* (non-Javadoc)
* @see org.mobicents.servlet.sip.startup.SipContext#setDescription(java.lang.String)
*/
public void setDescription(String description) {
this.description = description;
}
/* (non-Javadoc)
* @see org.mobicents.servlet.sip.startup.SipContext#getLargeIcon()
*/
public String getLargeIcon() {
return largeIcon;
}
/* (non-Javadoc)
* @see org.mobicents.servlet.sip.startup.SipContext#setLargeIcon(java.lang.String)
*/
public void setLargeIcon(String largeIcon) {
this.largeIcon = largeIcon;
}
/* (non-Javadoc)
* @see org.mobicents.servlet.sip.startup.SipContext#getListeners()
*/
public SipListenersHolder getListeners() {
return listeners;
}
/* (non-Javadoc)
* @see org.mobicents.servlet.sip.startup.SipContext#setListeners(org.mobicents.servlet.sip.core.session.SipListenersHolder)
*/
public void setListeners(SipListenersHolder listeners) {
this.listeners = listeners;
}
/* (non-Javadoc)
* @see org.mobicents.servlet.sip.startup.SipContext#getMainServlet()
*/
public String getMainServlet() {
return mainServlet;
}
/* (non-Javadoc)
* @see org.mobicents.servlet.sip.startup.SipContext#setMainServlet(java.lang.String)
*/
public void setMainServlet(String mainServlet) {
this.mainServlet = mainServlet;
}
/* (non-Javadoc)
* @see org.mobicents.servlet.sip.startup.SipContext#getProxyTimeout()
*/
public int getProxyTimeout() {
return proxyTimeout;
}
/* (non-Javadoc)
* @see org.mobicents.servlet.sip.startup.SipContext#setProxyTimeout(int)
*/
public void setProxyTimeout(int proxyTimeout) {
this.proxyTimeout = proxyTimeout;
}
public void addConstraint(SipSecurityConstraint securityConstraint) {
super.addConstraint(securityConstraint);
}
public void removeConstraint(SipSecurityConstraint securityConstraint) {
super.removeConstraint(securityConstraint);
}
/* (non-Javadoc)
* @see org.mobicents.servlet.sip.startup.SipContext#getSmallIcon()
*/
public String getSmallIcon() {
return smallIcon;
}
/* (non-Javadoc)
* @see org.mobicents.servlet.sip.startup.SipContext#setSmallIcon(java.lang.String)
*/
public void setSmallIcon(String smallIcon) {
this.smallIcon = smallIcon;
}
@Override
public void setLoginConfig(LoginConfig config) {
super.setLoginConfig(config);
}
@Override
public LoginConfig getLoginConfig() {
return super.getLoginConfig();
}
public void setSipLoginConfig(SipLoginConfig config) {
this.sipLoginConfig = config;
}
public SipLoginConfig getSipLoginConfig() {
return this.sipLoginConfig;
}
/**
* Add a new Listener class name to the set of Listeners
* configured for this application.
*
* @param listener Java class name of a listener class
*/
public void addSipApplicationListener(String listener) {
sipApplicationListeners.add(listener);
fireContainerEvent("addSipApplicationListener", listener);
// FIXME - add instance if already started?
}
/**
* Remove the specified application listener class from the set of
* listeners for this application.
*
* @param listener Java class name of the listener to be removed
*/
public void removeSipApplicationListener(String listener) {
sipApplicationListeners.remove(listener);
// Inform interested listeners
fireContainerEvent("removeSipApplicationListener", listener);
// FIXME - behavior if already started?
}
/**
* Return the set of sip application listener class names configured
* for this application.
*/
public String[] findSipApplicationListeners() {
return sipApplicationListeners.toArray(new String[sipApplicationListeners.size()]);
}
/**
* @return the sipApplicationDispatcher
*/
public SipApplicationDispatcher getSipApplicationDispatcher() {
return sipApplicationDispatcher;
}
/**
* @return the sipFactoryFacade
*/
public SipFactoryFacade getSipFactoryFacade() {
return sipFactoryFacade;
}
/**
* @return the sipSessionsUtil
*/
public SipSessionsUtil getSipSessionsUtil() {
return sipSessionsUtil;
}
/**
* @return the timerService
*/
public TimerService getTimerService() {
return TimerServiceImpl.getInstance();
}
/**
* Get naming context full name.
*/
private String getNamingContextName() {
if (namingContextName == null) {
Container parent = getParent();
if (parent == null) {
namingContextName = getName();
} else {
Stack<String> stk = new Stack<String>();
StringBuffer buff = new StringBuffer();
while (parent != null) {
stk.push(parent.getName());
parent = parent.getParent();
}
while (!stk.empty()) {
buff.append("/" + stk.pop());
}
buff.append(getName());
namingContextName = buff.toString();
}
}
return namingContextName;
}
@Override
public synchronized void setManager(Manager manager) {
if(manager instanceof SipManager && sipApplicationDispatcher != null) {
((SipManager)manager).setSipFactoryImpl(
((SipFactoryImpl)sipApplicationDispatcher.getSipFactory()));
((SipManager)manager).setContainer(this);
}
super.setManager(manager);
}
@Override
public Manager getManager() {
return super.getManager();
}
/**
* @return the sipApplicationSessionTimeout in minutes
*/
public int getSipApplicationSessionTimeout() {
return sipApplicationSessionTimeout;
}
/**
* @param sipApplicationSessionTimeout the sipApplicationSessionTimeout to set in minutes
*/
public void setSipApplicationSessionTimeout(int sipApplicationSessionTimeout) {
this.sipApplicationSessionTimeout = sipApplicationSessionTimeout;
}
public Method getSipApplicationKeyMethod() {
return sipApplicationKeyMethod;
}
public void setSipApplicationKeyMethod(Method sipApplicationKeyMethod) {
this.sipApplicationKeyMethod = sipApplicationKeyMethod;
}
public String getJbossBasePath() {
return getBasePath();
}
/**
* {@inheritDoc}
*/
public void addSipServletMapping(SipServletMapping sipServletMapping) {
sipServletMappings.add(sipServletMapping);
}
/**
* {@inheritDoc}
*/
public List<SipServletMapping> findSipServletMappings() {
return sipServletMappings;
}
/**
* {@inheritDoc}
*/
public SipServletMapping findSipServletMappings(SipServletRequest sipServletRequest) {
if(logger.isDebugEnabled()) {
logger.debug("Checking sip Servlet Mapping for following request : " + sipServletRequest);
}
for (SipServletMapping sipServletMapping : sipServletMappings) {
if(sipServletMapping.getMatchingRule().matches(sipServletRequest)) {
return sipServletMapping;
} else {
logger.debug("Following mapping rule didn't match : servletName => " +
sipServletMapping.getServletName() + " | expression = "+
sipServletMapping.getMatchingRule().getExpression());
}
}
return null;
}
/**
* {@inheritDoc}
*/
public void removeSipServletMapping(SipServletMapping sipServletMapping) {
sipServletMappings.remove(sipServletMapping);
}
/**
* {@inheritDoc}
*/
public SipManager getSipManager() {
return (SipManager)manager;
}
@Override
public String getInfo() {
return info;
}
}
| true | true | public synchronized void start() throws LifecycleException {
if(logger.isInfoEnabled()) {
logger.info("Starting the sip context");
}
if( initialized ) {
prepareServletContext();
}
// Add missing components as necessary
if (getResources() == null) { // (1) Required by Loader
if (logger.isDebugEnabled())
logger.debug("Configuring default Resources");
try {
if ((getDocBase() != null) && (getDocBase().endsWith(".sar")) && (!(new File(getBasePath())).isDirectory()))
setResources(new SARDirContext());
} catch (IllegalArgumentException e) {
logger.error("Error initializing resources: " + e.getMessage());
// ok = false;
}
}
// Configure default manager if none was specified
if (manager == null) {
if ((getCluster() != null) && getDistributable()) {
try {
manager = getCluster().createManager(getName());
} catch (Exception ex) {
logger.error("standardContext.clusterFail", ex);
// ok = false;
}
} else {
setManager(new SipStandardManager());
}
}
// Reading the "catalina.useNaming" environment variable
String useNamingProperty = System.getProperty("catalina.useNaming");
if ((useNamingProperty != null)
&& (useNamingProperty.equals("false"))) {
setUseNaming(false);
}
//activating our custom naming context to be able to set the sip factory in JNDI
if (isUseNaming()) {
if (getNamingContextListener() == null) {
NamingContextListener namingContextListener = new SipNamingContextListener();
namingContextListener.setName(getNamingContextName());
setNamingContextListener(namingContextListener);
addLifecycleListener(namingContextListener);
addContainerListener(namingContextListener);
}
// Replace the default annotation processor. This is needed to handle resource injection
// for SipFactory, Session utils and other objects residing in the servlet context space.
// Of course if the variable is not found in in the servet context it defaults to the
// normal lookup method - in the default naming context.
//tomcat naming
this.setAnnotationProcessor(
new SipAnnotationProcessor(
getNamingContextListener().getEnvContext(),
this));
} else {
// jboss or other kind of naming
try {
InitialContext iniCtx = new InitialContext();
Context envCtx = (Context) iniCtx.lookup("java:comp/env");
this.setAnnotationProcessor(
new SipAnnotationProcessor(
envCtx,
this));
} catch (NamingException e) {
logger.error("Impossible to get the naming context ", e);
}
}
//JSR 289 Section 2.1.1 Step 1.Deploy the application.
//This will make start the sip context config, which will in turn parse the sip descriptor deployment
//and call load on startup which is equivalent to
//JSR 289 Section 2.1.1 Step 2.Invoke servlet.init(), the initialization method on the Servlet. Invoke the init() on all the load-on-startup Servlets in the applicatio
super.start();
if(getAvailable()) {
// Replace the default annotation processor. This is needed to handle resource injection
// for SipFactory, Session utils and other objects residing in the servlet context space.
// Of course if the variable is not found in in the servet context it defaults to the
// normal lookup method - in the default naming context.
if(getAnnotationProcessor() == null || !(getAnnotationProcessor() instanceof SipAnnotationProcessor)) {
if(isUseNaming()) {
//tomcat naming
this.setAnnotationProcessor(
new SipAnnotationProcessor(
getNamingContextListener().getEnvContext(),
this));
} else {
// jboss or other kind of naming
try {
InitialContext iniCtx = new InitialContext();
Context envCtx = (Context) iniCtx.lookup("java:comp/env");
this.setAnnotationProcessor(
new SipAnnotationProcessor(
envCtx,
this));
} catch (NamingException e) {
logger.error("Impossible to get the naming context ", e);
}
}
}
//set the session manager on the specific sipstandardmanager to handle converged http sessions
if(getManager() instanceof SipManager) {
((SipManager)getManager()).setSipFactoryImpl(
((SipFactoryImpl)sipApplicationDispatcher.getSipFactory()));
((SipManager)manager).setContainer(this);
}
//JSR 289 Section 2.1.1 Step 3.Invoke SipApplicationRouter.applicationDeployed() for this application.
//called implicitly within sipApplicationDispatcher.addSipApplication
sipApplicationDispatcher.addSipApplication(applicationName, this);
if(logger.isInfoEnabled()) {
logger.info("sip context started");
}
} else {
if(logger.isInfoEnabled()) {
logger.info("sip context didn't started due to errors");
}
}
}
| public synchronized void start() throws LifecycleException {
if(logger.isInfoEnabled()) {
logger.info("Starting the sip context");
}
if( initialized ) {
prepareServletContext();
}
// Add missing components as necessary
if (getResources() == null) { // (1) Required by Loader
if (logger.isDebugEnabled())
logger.debug("Configuring default Resources");
try {
if ((getDocBase() != null) && (getDocBase().endsWith(".sar")) && (!(new File(getBasePath())).isDirectory()))
setResources(new SARDirContext());
} catch (IllegalArgumentException e) {
logger.error("Error initializing resources: " + e.getMessage());
// ok = false;
}
}
// Configure default manager if none was specified
if (manager == null) {
if ((getCluster() != null) && getDistributable()) {
try {
manager = getCluster().createManager(getName());
} catch (Exception ex) {
logger.error("standardContext.clusterFail", ex);
// ok = false;
}
} else {
setManager(new SipStandardManager());
}
}
// Reading the "catalina.useNaming" environment variable
String useNamingProperty = System.getProperty("catalina.useNaming");
if ((useNamingProperty != null)
&& (useNamingProperty.equals("false"))) {
setUseNaming(false);
}
//activating our custom naming context to be able to set the sip factory in JNDI
if (isUseNaming()) {
if (getNamingContextListener() == null) {
NamingContextListener namingContextListener = new SipNamingContextListener();
namingContextListener.setName(getNamingContextName());
setNamingContextListener(namingContextListener);
addLifecycleListener(namingContextListener);
addContainerListener(namingContextListener);
}
// Replace the default annotation processor. This is needed to handle resource injection
// for SipFactory, Session utils and other objects residing in the servlet context space.
// Of course if the variable is not found in in the servet context it defaults to the
// normal lookup method - in the default naming context.
//tomcat naming
this.setAnnotationProcessor(
new SipAnnotationProcessor(
getNamingContextListener().getEnvContext(),
this));
} else {
// jboss or other kind of naming
try {
InitialContext iniCtx = new InitialContext();
Context envCtx = (Context) iniCtx.lookup("java:comp/env");
this.setAnnotationProcessor(
new SipAnnotationProcessor(
envCtx,
this));
} catch (NamingException e) {
logger.error("Impossible to get the naming context ", e);
}
}
//JSR 289 Section 2.1.1 Step 1.Deploy the application.
//This will make start the sip context config, which will in turn parse the sip descriptor deployment
//and call load on startup which is equivalent to
//JSR 289 Section 2.1.1 Step 2.Invoke servlet.init(), the initialization method on the Servlet. Invoke the init() on all the load-on-startup Servlets in the applicatio
super.start();
if(getAvailable()) {
// Replace the default annotation processor. This is needed to handle resource injection
// for SipFactory, Session utils and other objects residing in the servlet context space.
// Of course if the variable is not found in in the servet context it defaults to the
// normal lookup method - in the default naming context.
if(getAnnotationProcessor() == null || !(getAnnotationProcessor() instanceof SipAnnotationProcessor)) {
if(isUseNaming()) {
//tomcat naming
this.setAnnotationProcessor(
new SipAnnotationProcessor(
getNamingContextListener().getEnvContext(),
this));
} else {
// jboss or other kind of naming
try {
InitialContext iniCtx = new InitialContext();
Context envCtx = (Context) iniCtx.lookup("java:comp/env");
this.setAnnotationProcessor(
new SipAnnotationProcessor(
envCtx,
this));
} catch (NamingException e) {
logger.error("Impossible to get the naming context ", e);
}
}
}
//set the session manager on the specific sipstandardmanager to handle converged http sessions
if(getManager() instanceof SipManager) {
((SipManager)getManager()).setSipFactoryImpl(
((SipFactoryImpl)sipApplicationDispatcher.getSipFactory()));
((SipManager)manager).setContainer(this);
}
// JSR 289 16.2 Servlet Selection
// When using this mechanism (the main-servlet) for servlet selection,
// if there is only one servlet in the application then this
// declaration is optional and the lone servlet becomes the main servlet
if((mainServlet == null || mainServlet.length() < 1) && childrenMap.size() == 1) {
mainServlet = childrenMap.keySet().iterator().next();
}
//JSR 289 Section 2.1.1 Step 3.Invoke SipApplicationRouter.applicationDeployed() for this application.
//called implicitly within sipApplicationDispatcher.addSipApplication
sipApplicationDispatcher.addSipApplication(applicationName, this);
if(logger.isInfoEnabled()) {
logger.info("sip context started");
}
} else {
if(logger.isInfoEnabled()) {
logger.info("sip context didn't started due to errors");
}
}
}
|
diff --git a/src/tconstruct/common/TContent.java b/src/tconstruct/common/TContent.java
index c88d7f34f..4e9d2759a 100644
--- a/src/tconstruct/common/TContent.java
+++ b/src/tconstruct/common/TContent.java
@@ -1,2438 +1,2442 @@
package tconstruct.common;
import cpw.mods.fml.common.*;
import cpw.mods.fml.common.event.FMLInterModComms;
import cpw.mods.fml.common.registry.*;
import java.lang.reflect.Field;
import java.util.*;
import net.minecraft.block.*;
import net.minecraft.block.material.*;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.*;
import net.minecraft.item.crafting.*;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.potion.Potion;
import net.minecraft.util.WeightedRandomChestContent;
import net.minecraftforge.common.*;
import net.minecraftforge.fluids.*;
import net.minecraftforge.fluids.FluidContainerRegistry.FluidContainerData;
import net.minecraftforge.oredict.*;
import tconstruct.TConstruct;
import tconstruct.blocks.*;
import tconstruct.blocks.logic.*;
import tconstruct.blocks.slime.*;
import tconstruct.blocks.traps.*;
import tconstruct.client.StepSoundSlime;
import tconstruct.entity.*;
import tconstruct.entity.item.*;
import tconstruct.entity.projectile.*;
import tconstruct.items.*;
import tconstruct.items.armor.*;
import tconstruct.items.blocks.*;
import tconstruct.items.tools.*;
import tconstruct.library.TConstructRegistry;
import tconstruct.library.client.*;
import tconstruct.library.client.FluidRenderProperties.Applications;
import tconstruct.library.crafting.*;
import tconstruct.library.tools.ToolCore;
import tconstruct.library.util.IPattern;
import tconstruct.modifiers.*;
import tconstruct.util.*;
import tconstruct.util.config.*;
public class TContent implements IFuelHandler
{
//Patterns and other materials
public static Item blankPattern;
public static Item materials;
public static Item toolRod;
public static Item toolShard;
public static Item woodPattern;
public static Item metalPattern;
public static Item armorPattern;
public static Item manualBook;
public static Item buckets;
public static Item titleIcon;
public static Item strangeFood;
public static Item diamondApple;
public static Item jerky;
//public static Item stonePattern;
//public static Item netherPattern;
//Tools
public static ToolCore pickaxe;
public static ToolCore shovel;
public static ToolCore hatchet;
public static ToolCore broadsword;
public static ToolCore longsword;
public static ToolCore rapier;
public static ToolCore dagger;
public static ToolCore cutlass;
public static ToolCore frypan;
public static ToolCore battlesign;
public static ToolCore chisel;
public static ToolCore mattock;
public static ToolCore scythe;
public static ToolCore lumberaxe;
public static ToolCore cleaver;
public static ToolCore excavator;
public static ToolCore hammer;
public static ToolCore battleaxe;
public static ToolCore shortbow;
public static ToolCore arrow;
public static Item potionLauncher;
//Tool parts
public static Item binding;
public static Item toughBinding;
public static Item toughRod;
public static Item largePlate;
public static Item pickaxeHead;
public static Item shovelHead;
public static Item hatchetHead;
public static Item frypanHead;
public static Item signHead;
public static Item chiselHead;
public static Item scytheBlade;
public static Item broadAxeHead;
public static Item excavatorHead;
public static Item hammerHead;
public static Item swordBlade;
public static Item largeSwordBlade;
public static Item knifeBlade;
public static Item wideGuard;
public static Item handGuard;
public static Item crossbar;
public static Item fullGuard;
public static Item bowstring;
public static Item arrowhead;
public static Item fletching;
//Crafting blocks
public static Block toolStationWood;
public static Block toolStationStone;
public static Block toolForge;
public static Block craftingStationWood;
public static Block craftingSlabWood;
public static Block heldItemBlock;
public static Block craftedSoil;
public static Block smeltery;
public static Block lavaTank;
public static Block searedBlock;
public static Block castingChannel;
public static Block metalBlock;
public static Block tankAir;
public static Block redstoneMachine;
public static Block dryingRack;
//Decoration
public static Block stoneTorch;
public static Block stoneLadder;
public static Block multiBrick;
public static Block multiBrickFancy;
public static Block searedSlab;
public static Block speedSlab;
public static Block meatBlock;
public static Block woolSlab1;
public static Block woolSlab2;
//Traps
public static Block landmine;
public static Block punji;
public static Block barricadeOak;
public static Block barricadeSpruce;
public static Block barricadeBirch;
public static Block barricadeJungle;
public static Block slimeExplosive;
//InfiBlocks
public static Block speedBlock;
public static Block clearGlass;
//public static Block stainedGlass;
public static Block stainedGlassClear;
public static Block glassPane;
//public static Block stainedGlassPane;
public static Block stainedGlassClearPane;
public static Block glassMagicSlab;
public static Block stainedGlassMagicSlab;
public static Block stainedGlassClearMagicSlab;
//Crystalline
public static Block essenceExtractor;
public static Item essenceCrystal;
//Liquids
public static Material liquidMetal;
public static Fluid moltenIronFluid;
public static Fluid moltenGoldFluid;
public static Fluid moltenCopperFluid;
public static Fluid moltenTinFluid;
public static Fluid moltenAluminumFluid;
public static Fluid moltenCobaltFluid;
public static Fluid moltenArditeFluid;
public static Fluid moltenBronzeFluid;
public static Fluid moltenAlubrassFluid;
public static Fluid moltenManyullynFluid;
public static Fluid moltenAlumiteFluid;
public static Fluid moltenObsidianFluid;
public static Fluid moltenSteelFluid;
public static Fluid moltenGlassFluid;
public static Fluid moltenStoneFluid;
public static Fluid moltenEmeraldFluid;
public static Fluid bloodFluid;
public static Fluid moltenNickelFluid;
public static Fluid moltenLeadFluid;
public static Fluid moltenSilverFluid;
public static Fluid moltenShinyFluid;
public static Fluid moltenInvarFluid;
public static Fluid moltenElectrumFluid;
public static Fluid moltenEnderFluid;
public static Fluid blueSlimeFluid;
public static Block moltenIron;
public static Block moltenGold;
public static Block moltenCopper;
public static Block moltenTin;
public static Block moltenAluminum;
public static Block moltenCobalt;
public static Block moltenArdite;
public static Block moltenBronze;
public static Block moltenAlubrass;
public static Block moltenManyullyn;
public static Block moltenAlumite;
public static Block moltenObsidian;
public static Block moltenSteel;
public static Block moltenGlass;
public static Block moltenStone;
public static Block moltenEmerald;
public static Block blood;
public static Block moltenNickel;
public static Block moltenLead;
public static Block moltenSilver;
public static Block moltenShiny;
public static Block moltenInvar;
public static Block moltenElectrum;
public static Block moltenEnder;
//Slime
public static StepSound slimeStep;
public static Block slimePool;
public static Block slimeGel;
public static Block slimeGrass;
public static Block slimeTallGrass;
public static SlimeLeaves slimeLeaves;
public static SlimeSapling slimeSapling;
public static Block slimeChannel;
public static Block slimePad;
//Ores
public static Block oreSlag;
public static Block oreGravel;
public static OreberryBush oreBerry;
public static OreberryBush oreBerrySecond;
public static Item oreBerries;
//Tool modifiers
public static ModElectric modE;
public static ModLapis modL;
//Wearables
public static Item heavyHelmet;
public static Item heavyChestplate;
public static Item heavyPants;
public static Item heavyBoots;
public static Item glove;
public static Item knapsack;
public static Item heartCanister;
public static Item goldHead;
//Rail-related
public static Block woodenRail;
//Chest hooks
public static ChestGenHooks tinkerHouseChest;
public static ChestGenHooks tinkerHousePatterns;
//Armor - basic
public static Item helmetWood;
public static Item chestplateWood;
public static Item leggingsWood;
public static Item bootsWood;
public static EnumArmorMaterial materialWood;
//Signal & Logic
public static Block signalBus;
public static Block signalTerminal;
public static Item spoolWire;
public static Item lengthWire;
//Temporary items
//public static Item armorTest = new ArmorStandard(2445, 4, EnumArmorPart.HELMET).setCreativeTab(CreativeTabs.tabAllSearch);
public TContent()
{
registerItems();
registerBlocks();
registerMaterials();
addCraftingRecipes();
setupToolTabs();
addLoot();
}
public void createEntities ()
{
EntityRegistry.registerModEntity(FancyEntityItem.class, "Fancy Item", 0, TConstruct.instance, 32, 5, true);
EntityRegistry.registerModEntity(DaggerEntity.class, "Dagger", 1, TConstruct.instance, 32, 5, true);
EntityRegistry.registerModEntity(Crystal.class, "Crystal", 2, TConstruct.instance, 32, 3, true);
EntityRegistry.registerModEntity(LaunchedPotion.class, "Launched Potion", 3, TConstruct.instance, 32, 3, true);
EntityRegistry.registerModEntity(ArrowEntity.class, "Arrow", 4, TConstruct.instance, 32, 5, true);
EntityRegistry.registerModEntity(EntityLandmineFirework.class, "LandmineFirework", 5, TConstruct.instance, 32, 5, true);
EntityRegistry.registerModEntity(ExplosivePrimed.class, "SlimeExplosive", 6, TConstruct.instance, 32, 5, true);
//EntityRegistry.registerModEntity(CartEntity.class, "Small Wagon", 1, TConstruct.instance, 32, 5, true);
EntityRegistry.registerModEntity(BlueSlime.class, "EdibleSlime", 12, TConstruct.instance, 64, 5, true);
//EntityRegistry.registerModEntity(MetalSlime.class, "MetalSlime", 13, TConstruct.instance, 64, 5, true);
/*BiomeGenBase[] plains = BiomeDictionary.getBiomesForType(BiomeDictionary.Type.PLAINS);
BiomeGenBase[] mountain = BiomeDictionary.getBiomesForType(BiomeDictionary.Type.MOUNTAIN);
BiomeGenBase[] hills = BiomeDictionary.getBiomesForType(BiomeDictionary.Type.HILLS);
BiomeGenBase[] swamp = BiomeDictionary.getBiomesForType(BiomeDictionary.Type.SWAMP);
BiomeGenBase[] desert = BiomeDictionary.getBiomesForType(BiomeDictionary.Type.DESERT);
BiomeGenBase[] frozen = BiomeDictionary.getBiomesForType(BiomeDictionary.Type.FROZEN);
BiomeGenBase[] jungle = BiomeDictionary.getBiomesForType(BiomeDictionary.Type.JUNGLE);
BiomeGenBase[] wasteland = BiomeDictionary.getBiomesForType(BiomeDictionary.Type.WASTELAND);
BiomeGenBase[] nether = BiomeDictionary.getBiomesForType(BiomeDictionary.Type.NETHER);*/
/*if (PHConstruct.blueSlime)
{
EntityRegistry.addSpawn(BlueSlime.class, PHConstruct.blueSlimeWeight, 4, 4, EnumCreatureType.monster, plains);
EntityRegistry.addSpawn(BlueSlime.class, PHConstruct.blueSlimeWeight, 4, 4, EnumCreatureType.monster, mountain);
EntityRegistry.addSpawn(BlueSlime.class, PHConstruct.blueSlimeWeight, 4, 4, EnumCreatureType.monster, hills);
EntityRegistry.addSpawn(BlueSlime.class, PHConstruct.blueSlimeWeight, 4, 4, EnumCreatureType.monster, swamp);
EntityRegistry.addSpawn(BlueSlime.class, PHConstruct.blueSlimeWeight, 4, 4, EnumCreatureType.monster, desert);
EntityRegistry.addSpawn(BlueSlime.class, PHConstruct.blueSlimeWeight, 4, 4, EnumCreatureType.monster, frozen);
EntityRegistry.addSpawn(BlueSlime.class, PHConstruct.blueSlimeWeight, 4, 4, EnumCreatureType.monster, jungle);
EntityRegistry.addSpawn(BlueSlime.class, PHConstruct.blueSlimeWeight, 4, 4, EnumCreatureType.monster, wasteland);
}
try
{
Class.forName("extrabiomes.api.BiomeManager");
Collection<BiomeGenBase> ebxlCollection = BiomeManager.getBiomes();
BiomeGenBase[] ebxlBiomes = (BiomeGenBase[]) ebxlCollection.toArray();
EntityRegistry.addSpawn(BlueSlime.class, PHConstruct.blueSlimeWeight, 4, 4, EnumCreatureType.monster, ebxlBiomes);
}
catch (Exception e)
{
}*/
}
public static Fluid[] fluids = new Fluid[25];
public static Block[] fluidBlocks = new Block[25];
void registerBlocks ()
{
//Tool Station
toolStationWood = new ToolStationBlock(PHConstruct.woodStation, Material.wood).setUnlocalizedName("ToolStation");
GameRegistry.registerBlock(toolStationWood, ToolStationItemBlock.class, "ToolStationBlock");
GameRegistry.registerTileEntity(ToolStationLogic.class, "ToolStation");
GameRegistry.registerTileEntity(PartBuilderLogic.class, "PartCrafter");
GameRegistry.registerTileEntity(PatternChestLogic.class, "PatternHolder");
GameRegistry.registerTileEntity(StencilTableLogic.class, "PatternShaper");
toolForge = new ToolForgeBlock(PHConstruct.toolForge, Material.iron).setUnlocalizedName("ToolForge");
GameRegistry.registerBlock(toolForge, MetadataItemBlock.class, "ToolForgeBlock");
GameRegistry.registerTileEntity(ToolForgeLogic.class, "ToolForge");
craftingStationWood = new CraftingStationBlock(PHConstruct.woodCrafter, Material.wood).setUnlocalizedName("CraftingStation");
GameRegistry.registerBlock(craftingStationWood, "CraftingStation");
GameRegistry.registerTileEntity(CraftingStationLogic.class, "CraftingStation");
craftingSlabWood = new CraftingSlab(PHConstruct.woodCrafterSlab, Material.wood).setUnlocalizedName("CraftingSlab");
GameRegistry.registerBlock(craftingSlabWood, CraftingSlabItemBlock.class, "CraftingSlab");
heldItemBlock = new EquipBlock(PHConstruct.heldItemBlock, Material.wood).setUnlocalizedName("Frypan");
GameRegistry.registerBlock(heldItemBlock, "HeldItemBlock");
GameRegistry.registerTileEntity(FrypanLogic.class, "FrypanLogic");
craftedSoil = new SoilBlock(PHConstruct.craftedSoil).setLightOpacity(0).setUnlocalizedName("TConstruct.Soil");
craftedSoil.stepSound = Block.soundGravelFootstep;
GameRegistry.registerBlock(craftedSoil, CraftedSoilItemBlock.class, "CraftedSoil");
searedSlab = new SearedSlab(PHConstruct.searedSlab).setUnlocalizedName("SearedSlab");
searedSlab.stepSound = Block.soundStoneFootstep;
GameRegistry.registerBlock(searedSlab, SearedSlabItem.class, "SearedSlab");
speedSlab = new SpeedSlab(PHConstruct.speedSlab).setUnlocalizedName("SpeedSlab");
speedSlab.stepSound = Block.soundStoneFootstep;
GameRegistry.registerBlock(speedSlab, SpeedSlabItem.class, "SpeedSlab");
metalBlock = new TMetalBlock(PHConstruct.metalBlock, Material.iron, 10.0F).setUnlocalizedName("tconstruct.metalblock");
metalBlock.stepSound = Block.soundMetalFootstep;
GameRegistry.registerBlock(metalBlock, MetalItemBlock.class, "MetalBlock");
meatBlock = new MeatBlock(PHConstruct.meatBlock).setUnlocalizedName("tconstruct.meatblock");
GameRegistry.registerBlock(meatBlock, "MeatBlock");
OreDictionary.registerOre("hambone", new ItemStack(meatBlock));
LanguageRegistry.addName(meatBlock, "Hambone");
GameRegistry.addRecipe(new ItemStack(meatBlock), "mmm", "mbm", "mmm", 'b', new ItemStack(Item.bone), 'm', new ItemStack(Item.porkRaw));
woolSlab1 = new SlabBase(PHConstruct.woolSlab1, Material.cloth, Block.cloth, 0, 8).setUnlocalizedName("cloth");
woolSlab1.setStepSound(Block.soundClothFootstep).setCreativeTab(CreativeTabs.tabDecorations);
GameRegistry.registerBlock(woolSlab1, WoolSlab1Item.class, "WoolSlab1");
woolSlab2 = new SlabBase(PHConstruct.woolSlab2, Material.cloth, Block.cloth, 8, 8).setUnlocalizedName("cloth");
woolSlab2.setStepSound(Block.soundClothFootstep).setCreativeTab(CreativeTabs.tabDecorations);
GameRegistry.registerBlock(woolSlab2, WoolSlab2Item.class, "WoolSlab2");
//Smeltery
smeltery = new SmelteryBlock(PHConstruct.smeltery).setUnlocalizedName("Smeltery");
GameRegistry.registerBlock(smeltery, SmelteryItemBlock.class, "Smeltery");
if (PHConstruct.newSmeltery)
{
GameRegistry.registerTileEntity(AdaptiveSmelteryLogic.class, "TConstruct.Smeltery");
GameRegistry.registerTileEntity(AdaptiveDrainLogic.class, "TConstruct.SmelteryDrain");
}
else
{
GameRegistry.registerTileEntity(SmelteryLogic.class, "TConstruct.Smeltery");
GameRegistry.registerTileEntity(SmelteryDrainLogic.class, "TConstruct.SmelteryDrain");
}
GameRegistry.registerTileEntity(MultiServantLogic.class, "TConstruct.Servants");
lavaTank = new LavaTankBlock(PHConstruct.lavaTank).setUnlocalizedName("LavaTank");
lavaTank.setStepSound(Block.soundGlassFootstep);
GameRegistry.registerBlock(lavaTank, LavaTankItemBlock.class, "LavaTank");
GameRegistry.registerTileEntity(LavaTankLogic.class, "TConstruct.LavaTank");
searedBlock = new SearedBlock(PHConstruct.searedTable).setUnlocalizedName("SearedBlock");
GameRegistry.registerBlock(searedBlock, SearedTableItemBlock.class, "SearedBlock");
GameRegistry.registerTileEntity(CastingTableLogic.class, "CastingTable");
GameRegistry.registerTileEntity(FaucetLogic.class, "Faucet");
GameRegistry.registerTileEntity(CastingBasinLogic.class, "CastingBasin");
castingChannel = (new CastingChannelBlock(PHConstruct.castingChannel)).setUnlocalizedName("CastingChannel");
GameRegistry.registerBlock(castingChannel, CastingChannelItem.class, "CastingChannel");
GameRegistry.registerTileEntity(CastingChannelLogic.class, "CastingChannel");
tankAir = new TankAirBlock(PHConstruct.airTank, Material.leaves).setBlockUnbreakable().setUnlocalizedName("tconstruct.tank.air");
GameRegistry.registerBlock(tankAir, "TankAir");
GameRegistry.registerTileEntity(TankAirLogic.class, "tconstruct.tank.air");
//Redstone machines
redstoneMachine = new RedstoneMachine(PHConstruct.redstoneMachine).setUnlocalizedName("Redstone.Machine");
GameRegistry.registerBlock(redstoneMachine, RedstoneMachineItem.class, "Redstone.Machine");
GameRegistry.registerTileEntity(DrawbridgeLogic.class, "Drawbridge");
GameRegistry.registerTileEntity(FirestarterLogic.class, "Firestarter");
GameRegistry.registerTileEntity(AdvancedDrawbridgeLogic.class, "AdvDrawbridge");
//Traps
landmine = new BlockLandmine(PHConstruct.landmine).setHardness(0.5F).setResistance(0F).setStepSound(Block.soundMetalFootstep).setCreativeTab(CreativeTabs.tabRedstone)
.setUnlocalizedName("landmine");
GameRegistry.registerBlock(landmine, ItemBlockLandmine.class, "Redstone.Landmine");
GameRegistry.registerTileEntity(TileEntityLandmine.class, "Landmine");
punji = new Punji(PHConstruct.punji).setUnlocalizedName("trap.punji");
GameRegistry.registerBlock(punji, "trap.punji");
barricadeOak = new BarricadeBlock(PHConstruct.barricadeOak, Block.wood, 0).setUnlocalizedName("trap.barricade.oak");
GameRegistry.registerBlock(barricadeOak, BarricadeItem.class, "trap.barricade.oak");
barricadeSpruce = new BarricadeBlock(PHConstruct.barricadeSpruce, Block.wood, 1).setUnlocalizedName("trap.barricade.spruce");
GameRegistry.registerBlock(barricadeSpruce, BarricadeItem.class, "trap.barricade.spruce");
barricadeBirch = new BarricadeBlock(PHConstruct.barricadeBirch, Block.wood, 2).setUnlocalizedName("trap.barricade.birch");
GameRegistry.registerBlock(barricadeBirch, BarricadeItem.class, "trap.barricade.birch");
barricadeJungle = new BarricadeBlock(PHConstruct.barricadeJungle, Block.wood, 3).setUnlocalizedName("trap.barricade.jungle");
GameRegistry.registerBlock(barricadeJungle, BarricadeItem.class, "trap.barricade.jungle");
slimeExplosive = new SlimeExplosive(PHConstruct.slimeExplosive).setHardness(0.0F).setStepSound(Block.soundGrassFootstep).setUnlocalizedName("explosive.slime");
GameRegistry.registerBlock(slimeExplosive, MetadataItemBlock.class, "explosive.slime");
dryingRack = new DryingRack(PHConstruct.dryingRack).setUnlocalizedName("Armor.DryingRack");
GameRegistry.registerBlock(dryingRack, "Armor.DryingRack");
GameRegistry.registerTileEntity(DryingRackLogic.class, "Armor.DryingRack");
//Liquids
liquidMetal = new MaterialLiquid(MapColor.tntColor);
moltenIronFluid = new Fluid("iron.molten");
if (!FluidRegistry.registerFluid(moltenIronFluid))
moltenIronFluid = FluidRegistry.getFluid("iron.molten");
moltenIron = new TConstructFluid(PHConstruct.moltenIron, moltenIronFluid, Material.lava, "liquid_iron").setUnlocalizedName("metal.molten.iron");
GameRegistry.registerBlock(moltenIron, "metal.molten.iron");
fluids[0] = moltenIronFluid;
fluidBlocks[0] = moltenIron;
moltenIronFluid.setBlockID(moltenIron).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenIronFluid, 1000), new ItemStack(buckets, 1, 0), new ItemStack(Item.bucketEmpty)));
moltenGoldFluid = new Fluid("gold.molten");
if (!FluidRegistry.registerFluid(moltenGoldFluid))
moltenGoldFluid = FluidRegistry.getFluid("gold.molten");
moltenGold = new TConstructFluid(PHConstruct.moltenGold, moltenGoldFluid, Material.lava, "liquid_gold").setUnlocalizedName("metal.molten.gold");
GameRegistry.registerBlock(moltenGold, "metal.molten.gold");
fluids[1] = moltenGoldFluid;
fluidBlocks[1] = moltenGold;
moltenGoldFluid.setBlockID(moltenGold).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenGoldFluid, 1000), new ItemStack(buckets, 1, 1), new ItemStack(Item.bucketEmpty)));
moltenCopperFluid = new Fluid("copper.molten");
if (!FluidRegistry.registerFluid(moltenCopperFluid))
moltenCopperFluid = FluidRegistry.getFluid("copper.molten");
moltenCopper = new TConstructFluid(PHConstruct.moltenCopper, moltenCopperFluid, Material.lava, "liquid_copper").setUnlocalizedName("metal.molten.copper");
GameRegistry.registerBlock(moltenCopper, "metal.molten.copper");
fluids[2] = moltenCopperFluid;
fluidBlocks[2] = moltenCopper;
moltenCopperFluid.setBlockID(moltenCopper).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenCopperFluid, 1000), new ItemStack(buckets, 1, 2), new ItemStack(Item.bucketEmpty)));
moltenTinFluid = new Fluid("tin.molten");
if (!FluidRegistry.registerFluid(moltenTinFluid))
moltenTinFluid = FluidRegistry.getFluid("tin.molten");
moltenTin = new TConstructFluid(PHConstruct.moltenTin, moltenTinFluid, Material.lava, "liquid_tin").setUnlocalizedName("metal.molten.tin");
GameRegistry.registerBlock(moltenTin, "metal.molten.tin");
fluids[3] = moltenTinFluid;
fluidBlocks[3] = moltenTin;
moltenTinFluid.setBlockID(moltenTin).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenTinFluid, 1000), new ItemStack(buckets, 1, 3), new ItemStack(Item.bucketEmpty)));
moltenAluminumFluid = new Fluid("aluminum.molten");
if (!FluidRegistry.registerFluid(moltenAluminumFluid))
moltenAluminumFluid = FluidRegistry.getFluid("aluminum.molten");
moltenAluminum = new TConstructFluid(PHConstruct.moltenAluminum, moltenAluminumFluid, Material.lava, "liquid_aluminum").setUnlocalizedName("metal.molten.aluminum");
GameRegistry.registerBlock(moltenAluminum, "metal.molten.aluminum");
fluids[4] = moltenAluminumFluid;
fluidBlocks[4] = moltenAluminum;
moltenAluminumFluid.setBlockID(moltenAluminum).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenAluminumFluid, 1000), new ItemStack(buckets, 1, 4), new ItemStack(Item.bucketEmpty)));
moltenCobaltFluid = new Fluid("cobalt.molten");
if (!FluidRegistry.registerFluid(moltenCobaltFluid))
moltenCobaltFluid = FluidRegistry.getFluid("cobalt.molten");
moltenCobalt = new TConstructFluid(PHConstruct.moltenCobalt, moltenCobaltFluid, Material.lava, "liquid_cobalt").setUnlocalizedName("metal.molten.cobalt");
GameRegistry.registerBlock(moltenCobalt, "metal.molten.cobalt");
fluids[5] = moltenCobaltFluid;
fluidBlocks[5] = moltenCobalt;
moltenCobaltFluid.setBlockID(moltenCobalt).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenCobaltFluid, 1000), new ItemStack(buckets, 1, 5), new ItemStack(Item.bucketEmpty)));
moltenArditeFluid = new Fluid("ardite.molten");
if (!FluidRegistry.registerFluid(moltenArditeFluid))
moltenArditeFluid = FluidRegistry.getFluid("ardite.molten");
moltenArdite = new TConstructFluid(PHConstruct.moltenArdite, moltenArditeFluid, Material.lava, "liquid_ardite").setUnlocalizedName("metal.molten.ardite");
GameRegistry.registerBlock(moltenArdite, "metal.molten.ardite");
fluids[6] = moltenArditeFluid;
fluidBlocks[6] = moltenArdite;
moltenArditeFluid.setBlockID(moltenArdite).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenArditeFluid, 1000), new ItemStack(buckets, 1, 6), new ItemStack(Item.bucketEmpty)));
moltenBronzeFluid = new Fluid("bronze.molten");
if (!FluidRegistry.registerFluid(moltenBronzeFluid))
moltenBronzeFluid = FluidRegistry.getFluid("bronze.molten");
moltenBronze = new TConstructFluid(PHConstruct.moltenBronze, moltenBronzeFluid, Material.lava, "liquid_bronze").setUnlocalizedName("metal.molten.bronze");
GameRegistry.registerBlock(moltenBronze, "metal.molten.bronze");
fluids[7] = moltenBronzeFluid;
fluidBlocks[7] = moltenBronze;
moltenBronzeFluid.setBlockID(moltenBronze).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenBronzeFluid, 1000), new ItemStack(buckets, 1, 7), new ItemStack(Item.bucketEmpty)));
moltenAlubrassFluid = new Fluid("aluminumbrass.molten");
if (!FluidRegistry.registerFluid(moltenAlubrassFluid))
moltenAlubrassFluid = FluidRegistry.getFluid("aluminumbrass.molten");
moltenAlubrass = new TConstructFluid(PHConstruct.moltenAlubrass, moltenAlubrassFluid, Material.lava, "liquid_alubrass").setUnlocalizedName("metal.molten.alubrass");
GameRegistry.registerBlock(moltenAlubrass, "metal.molten.alubrass");
fluids[8] = moltenAlubrassFluid;
fluidBlocks[8] = moltenAlubrass;
moltenAlubrassFluid.setBlockID(moltenAlubrass).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenAlubrassFluid, 1000), new ItemStack(buckets, 1, 8), new ItemStack(Item.bucketEmpty)));
moltenManyullynFluid = new Fluid("manyullyn.molten");
if (!FluidRegistry.registerFluid(moltenManyullynFluid))
moltenManyullynFluid = FluidRegistry.getFluid("manyullyn.molten");
moltenManyullyn = new TConstructFluid(PHConstruct.moltenManyullyn, moltenManyullynFluid, Material.lava, "liquid_manyullyn").setUnlocalizedName("metal.molten.manyullyn");
GameRegistry.registerBlock(moltenManyullyn, "metal.molten.manyullyn");
fluids[9] = moltenManyullynFluid;
fluidBlocks[9] = moltenManyullyn;
moltenManyullynFluid.setBlockID(moltenManyullyn).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenManyullynFluid, 1000), new ItemStack(buckets, 1, 9), new ItemStack(Item.bucketEmpty)));
moltenAlumiteFluid = new Fluid("alumite.molten");
if (!FluidRegistry.registerFluid(moltenAlumiteFluid))
moltenAlumiteFluid = FluidRegistry.getFluid("alumite.molten");
moltenAlumite = new TConstructFluid(PHConstruct.moltenAlumite, moltenAlumiteFluid, Material.lava, "liquid_alumite").setUnlocalizedName("metal.molten.alumite");
GameRegistry.registerBlock(moltenAlumite, "metal.molten.alumite");
fluids[10] = moltenAlumiteFluid;
fluidBlocks[10] = moltenAlumite;
moltenAlumiteFluid.setBlockID(moltenAlumite).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenAlumiteFluid, 1000), new ItemStack(buckets, 1, 10), new ItemStack(Item.bucketEmpty)));
moltenObsidianFluid = new Fluid("obsidian.molten");
if (!FluidRegistry.registerFluid(moltenObsidianFluid))
moltenObsidianFluid = FluidRegistry.getFluid("obsidian.molten");
moltenObsidian = new TConstructFluid(PHConstruct.moltenObsidian, moltenObsidianFluid, Material.lava, "liquid_obsidian").setUnlocalizedName("metal.molten.obsidian");
GameRegistry.registerBlock(moltenObsidian, "metal.molten.obsidian");
fluids[11] = moltenObsidianFluid;
fluidBlocks[11] = moltenObsidian;
moltenObsidianFluid.setBlockID(moltenObsidian).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenObsidianFluid, 1000), new ItemStack(buckets, 1, 11), new ItemStack(Item.bucketEmpty)));
moltenSteelFluid = new Fluid("steel.molten");
if (!FluidRegistry.registerFluid(moltenSteelFluid))
moltenSteelFluid = FluidRegistry.getFluid("steel.molten");
moltenSteel = new TConstructFluid(PHConstruct.moltenSteel, moltenSteelFluid, Material.lava, "liquid_steel").setUnlocalizedName("metal.molten.steel");
GameRegistry.registerBlock(moltenSteel, "metal.molten.steel");
fluids[12] = moltenSteelFluid;
fluidBlocks[12] = moltenSteel;
moltenSteelFluid.setBlockID(moltenSteel).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenSteelFluid, 1000), new ItemStack(buckets, 1, 12), new ItemStack(Item.bucketEmpty)));
moltenGlassFluid = new Fluid("glass.molten");
if (!FluidRegistry.registerFluid(moltenGlassFluid))
moltenGlassFluid = FluidRegistry.getFluid("glass.molten");
moltenGlass = new TConstructFluid(PHConstruct.moltenGlass, moltenGlassFluid, Material.lava, "liquid_glass", true).setUnlocalizedName("metal.molten.glass");
GameRegistry.registerBlock(moltenGlass, "metal.molten.glass");
fluids[13] = moltenGlassFluid;
fluidBlocks[13] = moltenGlass;
moltenGlassFluid.setBlockID(moltenGlass).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenGlassFluid, 1000), new ItemStack(buckets, 1, 13), new ItemStack(Item.bucketEmpty)));
moltenStoneFluid = new Fluid("stone.seared");
if (!FluidRegistry.registerFluid(moltenStoneFluid))
moltenStoneFluid = FluidRegistry.getFluid("stone.seared");
moltenStone = new TConstructFluid(PHConstruct.moltenStone, moltenStoneFluid, Material.lava, "liquid_stone").setUnlocalizedName("molten.stone");
GameRegistry.registerBlock(moltenStone, "molten.stone");
fluids[14] = moltenStoneFluid;
fluidBlocks[14] = moltenStone;
moltenStoneFluid.setBlockID(moltenStone).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenStoneFluid, 1000), new ItemStack(buckets, 1, 14), new ItemStack(Item.bucketEmpty)));
moltenEmeraldFluid = new Fluid("emerald.liquid");
if (!FluidRegistry.registerFluid(moltenEmeraldFluid))
moltenEmeraldFluid = FluidRegistry.getFluid("emerald.liquid");
moltenEmerald = new TConstructFluid(PHConstruct.moltenEmerald, moltenEmeraldFluid, Material.water, "liquid_villager").setUnlocalizedName("molten.emerald");
GameRegistry.registerBlock(moltenEmerald, "molten.emerald");
fluids[15] = moltenEmeraldFluid;
fluidBlocks[15] = moltenEmerald;
moltenEmeraldFluid.setBlockID(moltenEmerald).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenEmeraldFluid, 1000), new ItemStack(buckets, 1, 15), new ItemStack(Item.bucketEmpty)));
bloodFluid = new Fluid("blood");
if (!FluidRegistry.registerFluid(bloodFluid))
bloodFluid = FluidRegistry.getFluid("blood");
blood = new TConstructFluid(PHConstruct.blood, bloodFluid, Material.water, "liquid_cow").setUnlocalizedName("liquid.blood");
GameRegistry.registerBlock(blood, "liquid.blood");
fluids[16] = bloodFluid;
fluidBlocks[16] = blood;
bloodFluid.setBlockID(blood).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(bloodFluid, 1000), new ItemStack(buckets, 1, 16), new ItemStack(Item.bucketEmpty)));
moltenNickelFluid = new Fluid("nickel.molten");
if (!FluidRegistry.registerFluid(moltenNickelFluid))
moltenNickelFluid = FluidRegistry.getFluid("nickel.molten");
moltenNickel = new TConstructFluid(PHConstruct.moltenNickel, moltenNickelFluid, Material.lava, "liquid_ferrous").setUnlocalizedName("metal.molten.nickel");
GameRegistry.registerBlock(moltenNickel, "metal.molten.nickel");
fluids[17] = moltenNickelFluid;
fluidBlocks[17] = moltenNickel;
moltenNickelFluid.setBlockID(moltenNickel).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenNickelFluid, 1000), new ItemStack(buckets, 1, 17), new ItemStack(Item.bucketEmpty)));
moltenLeadFluid = new Fluid("lead.molten");
if (!FluidRegistry.registerFluid(moltenLeadFluid))
moltenLeadFluid = FluidRegistry.getFluid("lead.molten");
moltenLead = new TConstructFluid(PHConstruct.moltenLead, moltenLeadFluid, Material.lava, "liquid_lead").setUnlocalizedName("metal.molten.lead");
GameRegistry.registerBlock(moltenLead, "metal.molten.lead");
fluids[18] = moltenLeadFluid;
fluidBlocks[18] = moltenLead;
moltenLeadFluid.setBlockID(moltenLead).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenLeadFluid, 1000), new ItemStack(buckets, 1, 18), new ItemStack(Item.bucketEmpty)));
moltenSilverFluid = new Fluid("silver.molten");
if (!FluidRegistry.registerFluid(moltenSilverFluid))
moltenSilverFluid = FluidRegistry.getFluid("silver.molten");
moltenSilver = new TConstructFluid(PHConstruct.moltenSilver, moltenSilverFluid, Material.lava, "liquid_silver").setUnlocalizedName("metal.molten.silver");
GameRegistry.registerBlock(moltenSilver, "metal.molten.silver");
fluids[19] = moltenSilverFluid;
fluidBlocks[19] = moltenSilver;
moltenSilverFluid.setBlockID(moltenSilver).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenSilverFluid, 1000), new ItemStack(buckets, 1, 19), new ItemStack(Item.bucketEmpty)));
moltenShinyFluid = new Fluid("platinum.molten");
if (!FluidRegistry.registerFluid(moltenShinyFluid))
moltenShinyFluid = FluidRegistry.getFluid("platinum.molten");
moltenShiny = new TConstructFluid(PHConstruct.moltenShiny, moltenShinyFluid, Material.lava, "liquid_shiny").setUnlocalizedName("metal.molten.shiny");
GameRegistry.registerBlock(moltenShiny, "metal.molten.shiny");
fluids[20] = moltenLeadFluid;
fluidBlocks[20] = moltenShiny;
moltenShinyFluid.setBlockID(moltenShiny).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenShinyFluid, 1000), new ItemStack(buckets, 1, 20), new ItemStack(Item.bucketEmpty)));
moltenInvarFluid = new Fluid("invar.molten");
if (!FluidRegistry.registerFluid(moltenInvarFluid))
moltenInvarFluid = FluidRegistry.getFluid("invar.molten");
moltenInvar = new TConstructFluid(PHConstruct.moltenInvar, moltenInvarFluid, Material.lava, "liquid_invar").setUnlocalizedName("metal.molten.invar");
GameRegistry.registerBlock(moltenInvar, "metal.molten.invar");
fluids[21] = moltenInvarFluid;
fluidBlocks[21] = moltenInvar;
moltenInvarFluid.setBlockID(moltenInvar).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenInvarFluid, 1000), new ItemStack(buckets, 1, 21), new ItemStack(Item.bucketEmpty)));
moltenElectrumFluid = new Fluid("electrum.molten");
if (!FluidRegistry.registerFluid(moltenElectrumFluid))
moltenElectrumFluid = FluidRegistry.getFluid("electrum.molten");
moltenElectrum = new TConstructFluid(PHConstruct.moltenElectrum, moltenElectrumFluid, Material.lava, "liquid_electrum").setUnlocalizedName("metal.molten.electrum");
GameRegistry.registerBlock(moltenElectrum, "metal.molten.electrum");
fluids[22] = moltenElectrumFluid;
fluidBlocks[22] = moltenElectrum;
moltenElectrumFluid.setBlockID(moltenElectrum).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenElectrumFluid, 1000), new ItemStack(buckets, 1, 22), new ItemStack(Item.bucketEmpty)));
moltenEnderFluid = new Fluid("ender");
if (GameRegistry.findBlock("ThermalExpansion", "fluid.ender") == null)
{
if (FluidRegistry.registerFluid(moltenEnderFluid))
{
moltenEnder = new TConstructFluid(PHConstruct.moltenEnder, moltenEnderFluid, Material.water, "liquid_ender").setUnlocalizedName("fluid.ender");
- //TConstruct.logger.info("Registering Molten Ender Stuff.");
GameRegistry.registerBlock(moltenEnder, "fluid.ender");
moltenEnderFluid.setBlockID(moltenEnder).setDensity(3000).setViscosity(6000);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenEnderFluid, 1000), new ItemStack(buckets, 1, 23), new ItemStack(Item.bucketEmpty)));
}
+ else
+ {
+ moltenEnderFluid = FluidRegistry.getFluid("ender");
+ moltenEnder = new TConstructFluid(PHConstruct.moltenEnder, moltenEnderFluid, Material.water, "liquid_ender").setUnlocalizedName("fluid.ender");
+ }
}
else
{
moltenEnderFluid = FluidRegistry.getFluid("ender");
moltenEnder = GameRegistry.findBlock("ThermalExpansion", "fluid.ender");
}
fluids[23] = moltenEnderFluid;
fluidBlocks[23] = moltenEnder;
//Slime
slimeStep = new StepSoundSlime("mob.slime", 1.0f, 1.0f);
blueSlimeFluid = new Fluid("slime.blue");
if (!FluidRegistry.registerFluid(blueSlimeFluid))
blueSlimeFluid = FluidRegistry.getFluid("slime.blue");
slimePool = new SlimeFluid(PHConstruct.slimePoolBlue, blueSlimeFluid, Material.water).setCreativeTab(TConstructRegistry.blockTab).setStepSound(slimeStep).setUnlocalizedName("liquid.slime");
GameRegistry.registerBlock(slimePool, "liquid.slime");
fluids[24] = blueSlimeFluid;
fluidBlocks[24] = slimePool;
blueSlimeFluid.setBlockID(slimePool);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(blueSlimeFluid, 1000), new ItemStack(buckets, 1, 24), new ItemStack(Item.bucketEmpty)));
slimeGel = new SlimeGel(PHConstruct.slimeGel).setStepSound(slimeStep).setLightOpacity(0).setUnlocalizedName("slime.gel");
GameRegistry.registerBlock(slimeGel, SlimeGelItemBlock.class, "slime.gel");
slimeGrass = new SlimeGrass(PHConstruct.slimeGrass).setStepSound(Block.soundGrassFootstep).setLightOpacity(0).setUnlocalizedName("slime.grass");
GameRegistry.registerBlock(slimeGrass, SlimeGrassItemBlock.class, "slime.grass");
slimeTallGrass = new SlimeTallGrass(PHConstruct.slimeTallGrass).setStepSound(Block.soundGrassFootstep).setUnlocalizedName("slime.grass.tall");
GameRegistry.registerBlock(slimeTallGrass, SlimeTallGrassItem.class, "slime.grass.tall");
slimeLeaves = (SlimeLeaves) new SlimeLeaves(PHConstruct.slimeLeaves).setStepSound(slimeStep).setLightOpacity(0).setUnlocalizedName("slime.leaves");
GameRegistry.registerBlock(slimeLeaves, SlimeLeavesItemBlock.class, "slime.leaves");
slimeSapling = (SlimeSapling) new SlimeSapling(PHConstruct.slimeSapling).setStepSound(slimeStep).setUnlocalizedName("slime.sapling");
GameRegistry.registerBlock(slimeSapling, SlimeSaplingItemBlock.class, "slime.sapling");
slimeChannel = new ConveyorBase(PHConstruct.slimeChannel, Material.water).setStepSound(slimeStep).setUnlocalizedName("slime.channel");
GameRegistry.registerBlock(slimeChannel, "slime.channel");
TConstructRegistry.drawbridgeState[slimeChannel.blockID] = 1;
slimePad = new SlimePad(PHConstruct.slimePad, Material.cloth).setStepSound(slimeStep).setUnlocalizedName("slime.pad");
GameRegistry.registerBlock(slimePad, "slime.pad");
TConstructRegistry.drawbridgeState[slimePad.blockID] = 1;
//Decoration
stoneTorch = new StoneTorch(PHConstruct.stoneTorch).setUnlocalizedName("decoration.stonetorch");
GameRegistry.registerBlock(stoneTorch, "decoration.stonetorch");
stoneLadder = new StoneLadder(PHConstruct.stoneLadder).setUnlocalizedName("decoration.stoneladder");
GameRegistry.registerBlock(stoneLadder, "decoration.stoneladder");
multiBrick = new MultiBrick(PHConstruct.multiBrick).setUnlocalizedName("Decoration.Brick");
GameRegistry.registerBlock(multiBrick, MultiBrickItem.class, "decoration.multibrick");
multiBrickFancy = new MultiBrickFancy(PHConstruct.multiBrickFancy).setUnlocalizedName("Decoration.BrickFancy");
GameRegistry.registerBlock(multiBrickFancy, MultiBrickFancyItem.class, "decoration.multibrickfancy");
//Ores
String[] berryOres = new String[] { "berry_iron", "berry_gold", "berry_copper", "berry_tin", "berry_iron_ripe", "berry_gold_ripe", "berry_copper_ripe", "berry_tin_ripe" };
oreBerry = (OreberryBush) new OreberryBush(PHConstruct.oreBerry, berryOres, 0, 4, new String[] { "oreIron", "oreGold", "oreCopper", "oreTin" }).setUnlocalizedName("ore.berries.one");
GameRegistry.registerBlock(oreBerry, OreberryBushItem.class, "ore.berries.one");
String[] berryOresTwo = new String[] { "berry_aluminum", "berry_essence", "", "", "berry_aluminum_ripe", "berry_essence_ripe", "", "" };
oreBerrySecond = (OreberryBush) new OreberryBushEssence(PHConstruct.oreBerrySecond, berryOresTwo, 4, 2, new String[] { "oreAluminum", "oreSilver" }).setUnlocalizedName("ore.berries.two");
GameRegistry.registerBlock(oreBerrySecond, OreberryBushSecondItem.class, "ore.berries.two");
String[] oreTypes = new String[] { "nether_slag", "nether_cobalt", "nether_ardite", "ore_copper", "ore_tin", "ore_aluminum", "ore_slag" };
oreSlag = new MetalOre(PHConstruct.oreSlag, Material.iron, 10.0F, oreTypes).setUnlocalizedName("tconstruct.stoneore");
GameRegistry.registerBlock(oreSlag, MetalOreItemBlock.class, "SearedBrick");
MinecraftForge.setBlockHarvestLevel(oreSlag, 1, "pickaxe", 4);
MinecraftForge.setBlockHarvestLevel(oreSlag, 2, "pickaxe", 4);
MinecraftForge.setBlockHarvestLevel(oreSlag, 3, "pickaxe", 1);
MinecraftForge.setBlockHarvestLevel(oreSlag, 4, "pickaxe", 1);
MinecraftForge.setBlockHarvestLevel(oreSlag, 5, "pickaxe", 1);
oreGravel = new GravelOre(PHConstruct.oreGravel).setUnlocalizedName("GravelOre").setUnlocalizedName("tconstruct.gravelore");
GameRegistry.registerBlock(oreGravel, GravelOreItem.class, "GravelOre");
MinecraftForge.setBlockHarvestLevel(oreGravel, 0, "shovel", 1);
MinecraftForge.setBlockHarvestLevel(oreGravel, 1, "shovel", 2);
MinecraftForge.setBlockHarvestLevel(oreGravel, 2, "shovel", 1);
MinecraftForge.setBlockHarvestLevel(oreGravel, 3, "shovel", 1);
MinecraftForge.setBlockHarvestLevel(oreGravel, 4, "shovel", 1);
MinecraftForge.setBlockHarvestLevel(oreGravel, 5, "shovel", 4);
speedBlock = new SpeedBlock(PHConstruct.speedBlock).setUnlocalizedName("SpeedBlock");
GameRegistry.registerBlock(speedBlock, SpeedBlockItem.class, "SpeedBlock");
//Glass
clearGlass = new GlassBlockConnected(PHConstruct.glass, "clear", false).setUnlocalizedName("GlassBlock");
clearGlass.stepSound = Block.soundGlassFootstep;
GameRegistry.registerBlock(clearGlass, GlassBlockItem.class, "GlassBlock");
glassPane = new GlassPaneConnected(PHConstruct.glassPane, "clear", false);
GameRegistry.registerBlock(glassPane, GlassPaneItem.class, "GlassPane");
stainedGlassClear = new GlassBlockConnectedMeta(PHConstruct.stainedGlassClear, "stained", true, "white", "orange", "magenta", "light_blue", "yellow", "lime", "pink", "gray", "light_gray",
"cyan", "purple", "blue", "brown", "green", "red", "black").setUnlocalizedName("GlassBlock.StainedClear");
stainedGlassClear.stepSound = Block.soundGlassFootstep;
GameRegistry.registerBlock(stainedGlassClear, StainedGlassClearItem.class, "GlassBlock.StainedClear");
stainedGlassClearPane = new GlassPaneStained(PHConstruct.stainedGlassClearPane);
GameRegistry.registerBlock(stainedGlassClearPane, StainedGlassClearPaneItem.class, "GlassPaneClearStained");
//Crystalline
essenceExtractor = new EssenceExtractor(PHConstruct.essenceExtractor).setHardness(12f).setUnlocalizedName("extractor.essence");
GameRegistry.registerBlock(essenceExtractor, "extractor.essence");
GameRegistry.registerTileEntity(EssenceExtractorLogic.class, "extractor.essence");
//Rail
woodenRail = new WoodRail(PHConstruct.woodenRail).setStepSound(Block.soundWoodFootstep).setCreativeTab(TConstructRegistry.blockTab).setUnlocalizedName("rail.wood");
GameRegistry.registerBlock(woodenRail, "rail.wood");
//Signal & Logic
signalBus = (new SignalBus(PHConstruct.signalBus)).setUnlocalizedName("tconstruct.signalbus");
GameRegistry.registerBlock(signalBus, SignalBusItem.class, "SignalBus");
GameRegistry.registerTileEntity(SignalBusLogic.class, "SignalBus");
signalTerminal = (new SignalTerminal(PHConstruct.signalTerminal)).setUnlocalizedName("tconstruct.signalterminal");
GameRegistry.registerBlock(signalTerminal, SignalTerminalItem.class, "SignalTerminal");
GameRegistry.registerTileEntity(SignalTerminalLogic.class, "SignalTerminal");
}
void registerItems ()
{
titleIcon = new TitleIcon(PHConstruct.uselessItem).setUnlocalizedName("tconstruct.titleicon");
String[] blanks = new String[] { "blank_pattern", "blank_cast", "blank_cast" };
blankPattern = new CraftingItem(PHConstruct.blankPattern, blanks, blanks, "materials/").setUnlocalizedName("tconstruct.Pattern");
materials = new MaterialItem(PHConstruct.materials).setUnlocalizedName("tconstruct.Materials");
toolRod = new ToolPart(PHConstruct.toolRod, "_rod", "ToolRod").setUnlocalizedName("tconstruct.ToolRod");
toolShard = new ToolShard(PHConstruct.toolShard, "_chunk").setUnlocalizedName("tconstruct.ToolShard");
woodPattern = new Pattern(PHConstruct.woodPattern, "WoodPattern", "pattern_", "materials/").setUnlocalizedName("tconstruct.Pattern");
metalPattern = new MetalPattern(PHConstruct.metalPattern, "MetalPattern", "cast_", "materials/").setUnlocalizedName("tconstruct.MetalPattern");
armorPattern = new ArmorPattern(PHConstruct.armorPattern, "ArmorPattern", "armorcast_", "materials/").setUnlocalizedName("tconstruct.ArmorPattern");
TConstructRegistry.addItemToDirectory("blankPattern", blankPattern);
TConstructRegistry.addItemToDirectory("woodPattern", woodPattern);
TConstructRegistry.addItemToDirectory("metalPattern", metalPattern);
TConstructRegistry.addItemToDirectory("armorPattern", armorPattern);
String[] patternTypes = { "ingot", "toolRod", "pickaxeHead", "shovelHead", "hatchetHead", "swordBlade", "wideGuard", "handGuard", "crossbar", "binding", "frypanHead", "signHead",
"knifeBlade", "chiselHead", "toughRod", "toughBinding", "largePlate", "broadAxeHead", "scytheHead", "excavatorHead", "largeBlade", "hammerHead", "fullGuard" };
for (int i = 1; i < patternTypes.length; i++)
{
TConstructRegistry.addItemStackToDirectory(patternTypes[i] + "Pattern", new ItemStack(woodPattern, 1, i));
}
for (int i = 0; i < patternTypes.length; i++)
{
TConstructRegistry.addItemStackToDirectory(patternTypes[i] + "Cast", new ItemStack(metalPattern, 1, i));
}
String[] armorPartTypes = { "helmet", "chestplate", "leggings", "boots" };
for (int i = 1; i < armorPartTypes.length; i++)
{
TConstructRegistry.addItemStackToDirectory(armorPartTypes[i] + "Cast", new ItemStack(armorPattern, 1, i));
}
manualBook = new Manual(PHConstruct.manual);
buckets = new FilledBucket(PHConstruct.buckets);
pickaxe = new Pickaxe(PHConstruct.pickaxe);
shovel = new Shovel(PHConstruct.shovel);
hatchet = new Hatchet(PHConstruct.axe);
broadsword = new Broadsword(PHConstruct.broadsword);
longsword = new Longsword(PHConstruct.longsword);
rapier = new Rapier(PHConstruct.rapier);
dagger = new Dagger(PHConstruct.dagger);
cutlass = new Cutlass(PHConstruct.cutlass);
frypan = new FryingPan(PHConstruct.frypan);
battlesign = new BattleSign(PHConstruct.battlesign);
mattock = new Mattock(PHConstruct.mattock);
chisel = new Chisel(PHConstruct.chisel);
lumberaxe = new LumberAxe(PHConstruct.lumberaxe);
cleaver = new Cleaver(PHConstruct.cleaver);
scythe = new Scythe(PHConstruct.scythe);
excavator = new Excavator(PHConstruct.excavator);
hammer = new Hammer(PHConstruct.hammer);
battleaxe = new Battleaxe(PHConstruct.battleaxe);
shortbow = new Shortbow(PHConstruct.shortbow);
arrow = new Arrow(PHConstruct.arrow);
Item[] tools = { pickaxe, shovel, hatchet, broadsword, longsword, rapier, cutlass, frypan, battlesign, mattock, chisel, lumberaxe, cleaver, scythe, excavator, hammer, battleaxe };
String[] toolStrings = { "pickaxe", "shovel", "hatchet", "broadsword", "longsword", "rapier", "cutlass", "frypan", "battlesign", "mattock", "chisel", "lumberaxe", "cleaver", "scythe",
"excavator", "hammer", "battleaxe" };
for (int i = 0; i < tools.length; i++)
{
TConstructRegistry.addItemToDirectory(toolStrings[i], tools[i]);
}
potionLauncher = new PotionLauncher(PHConstruct.potionLauncher).setUnlocalizedName("tconstruct.PotionLauncher");
pickaxeHead = new ToolPart(PHConstruct.pickaxeHead, "_pickaxe_head", "PickHead").setUnlocalizedName("tconstruct.PickaxeHead");
shovelHead = new ToolPart(PHConstruct.shovelHead, "_shovel_head", "ShovelHead").setUnlocalizedName("tconstruct.ShovelHead");
hatchetHead = new ToolPart(PHConstruct.axeHead, "_axe_head", "AxeHead").setUnlocalizedName("tconstruct.AxeHead");
binding = new ToolPart(PHConstruct.binding, "_binding", "Binding").setUnlocalizedName("tconstruct.Binding");
toughBinding = new ToolPart(PHConstruct.toughBinding, "_toughbind", "ToughBind").setUnlocalizedName("tconstruct.ThickBinding");
toughRod = new ToolPart(PHConstruct.toughRod, "_toughrod", "ToughRod").setUnlocalizedName("tconstruct.ThickRod");
largePlate = new ToolPart(PHConstruct.largePlate, "_largeplate", "LargePlate").setUnlocalizedName("tconstruct.LargePlate");
swordBlade = new ToolPart(PHConstruct.swordBlade, "_sword_blade", "SwordBlade").setUnlocalizedName("tconstruct.SwordBlade");
wideGuard = new ToolPart(PHConstruct.largeGuard, "_large_guard", "LargeGuard").setUnlocalizedName("tconstruct.LargeGuard");
handGuard = new ToolPart(PHConstruct.medGuard, "_medium_guard", "MediumGuard").setUnlocalizedName("tconstruct.MediumGuard");
crossbar = new ToolPart(PHConstruct.crossbar, "_crossbar", "Crossbar").setUnlocalizedName("tconstruct.Crossbar");
knifeBlade = new ToolPart(PHConstruct.knifeBlade, "_knife_blade", "KnifeBlade").setUnlocalizedName("tconstruct.KnifeBlade");
fullGuard = new ToolPartHidden(PHConstruct.fullGuard, "_full_guard", "FullGuard").setUnlocalizedName("tconstruct.FullGuard");
frypanHead = new ToolPart(PHConstruct.frypanHead, "_frypan_head", "FrypanHead").setUnlocalizedName("tconstruct.FrypanHead");
signHead = new ToolPart(PHConstruct.signHead, "_battlesign_head", "SignHead").setUnlocalizedName("tconstruct.SignHead");
chiselHead = new ToolPart(PHConstruct.chiselHead, "_chisel_head", "ChiselHead").setUnlocalizedName("tconstruct.ChiselHead");
scytheBlade = new ToolPart(PHConstruct.scytheBlade, "_scythe_head", "ScytheHead").setUnlocalizedName("tconstruct.ScytheBlade");
broadAxeHead = new ToolPart(PHConstruct.lumberHead, "_lumberaxe_head", "LumberHead").setUnlocalizedName("tconstruct.LumberHead");
excavatorHead = new ToolPart(PHConstruct.excavatorHead, "_excavator_head", "ExcavatorHead").setUnlocalizedName("tconstruct.ExcavatorHead");
largeSwordBlade = new ToolPart(PHConstruct.largeSwordBlade, "_large_sword_blade", "LargeSwordBlade").setUnlocalizedName("tconstruct.LargeSwordBlade");
hammerHead = new ToolPart(PHConstruct.hammerHead, "_hammer_head", "HammerHead").setUnlocalizedName("tconstruct.HammerHead");
bowstring = new Bowstring(PHConstruct.bowstring).setUnlocalizedName("tconstruct.Bowstring");
arrowhead = new ToolPart(PHConstruct.arrowhead, "_arrowhead", "ArrowHead").setUnlocalizedName("tconstruct.Arrowhead");
fletching = new Fletching(PHConstruct.fletching).setUnlocalizedName("tconstruct.Fletching");
Item[] toolParts = { toolRod, toolShard, pickaxeHead, shovelHead, hatchetHead, binding, toughBinding, toughRod, largePlate, swordBlade, wideGuard, handGuard, crossbar, knifeBlade, fullGuard,
frypanHead, signHead, chiselHead, scytheBlade, broadAxeHead, excavatorHead, largeSwordBlade, hammerHead, bowstring, fletching, arrowhead };
String[] toolPartStrings = { "toolRod", "toolShard", "pickaxeHead", "shovelHead", "hatchetHead", "binding", "toughBinding", "toughRod", "heavyPlate", "swordBlade", "wideGuard", "handGuard",
"crossbar", "knifeBlade", "fullGuard", "frypanHead", "signHead", "chiselHead", "scytheBlade", "broadAxeHead", "excavatorHead", "largeSwordBlade", "hammerHead", "bowstring",
"fletching", "arrowhead" };
for (int i = 0; i < toolParts.length; i++)
{
TConstructRegistry.addItemToDirectory(toolPartStrings[i], toolParts[i]);
}
diamondApple = new DiamondApple(PHConstruct.diamondApple).setUnlocalizedName("tconstruct.apple.diamond");
strangeFood = new StrangeFood(PHConstruct.slimefood).setUnlocalizedName("tconstruct.strangefood");
oreBerries = new OreBerries(PHConstruct.oreChunks).setUnlocalizedName("oreberry");
jerky = new Jerky(PHConstruct.jerky, Loader.isModLoaded("HungerOverhaul")).setUnlocalizedName("tconstruct.jerky");
//Wearables
//heavyHelmet = new TArmorBase(PHConstruct.heavyHelmet, 0).setUnlocalizedName("tconstruct.HeavyHelmet");
heartCanister = new HeartCanister(PHConstruct.heartCanister).setUnlocalizedName("tconstruct.canister");
//heavyBoots = new TArmorBase(PHConstruct.heavyBoots, 3).setUnlocalizedName("tconstruct.HeavyBoots");
//glove = new Glove(PHConstruct.glove).setUnlocalizedName("tconstruct.Glove");
knapsack = new Knapsack(PHConstruct.knapsack).setUnlocalizedName("tconstruct.storage");
//Crystalline
essenceCrystal = new EssenceCrystal(PHConstruct.essenceCrystal).setUnlocalizedName("tconstruct.crystal.essence");
goldHead = new GoldenHead(PHConstruct.goldHead, 4, 1.2F, false).setAlwaysEdible().setPotionEffect(Potion.regeneration.id, 10, 0, 1.0F).setUnlocalizedName("goldenhead");
LiquidCasting basinCasting = TConstruct.getBasinCasting();
materialWood = EnumHelper.addArmorMaterial("WOOD", 2, new int[] { 1, 2, 2, 1 }, 3);
helmetWood = new ArmorBasic(PHConstruct.woodHelmet, materialWood, 0, "wood").setUnlocalizedName("tconstruct.helmetWood");
chestplateWood = new ArmorBasic(PHConstruct.woodChestplate, materialWood, 1, "wood").setUnlocalizedName("tconstruct.chestplateWood");
leggingsWood = new ArmorBasic(PHConstruct.woodPants, materialWood, 2, "wood").setUnlocalizedName("tconstruct.leggingsWood");
bootsWood = new ArmorBasic(PHConstruct.woodBoots, materialWood, 3, "wood").setUnlocalizedName("tconstruct.bootsWood");
spoolWire = new SpoolOfWire(PHConstruct.spoolWire).setUnlocalizedName("spoolwire");
lengthWire = new LengthWire(PHConstruct.lengthWire).setUnlocalizedName("lengthwire");
// essenceCrystal = new EssenceCrystal(PHConstruct.essenceCrystal).setUnlocalizedName("tconstruct.crystal.essence");
String[] materialStrings = { "paperStack", "greenSlimeCrystal", "searedBrick", "ingotCobalt", "ingotArdite", "ingotManyullyn", "mossBall", "lavaCrystal", "necroticBone", "ingotCopper",
"ingotTin", "ingotAluminum", "rawAluminum", "ingotBronze", "ingotAluminumBrass", "ingotAlumite", "ingotSteel", "blueSlimeCrystal", "ingotObsidian", "nuggetIron", "nuggetCopper",
"nuggetTin", "nuggetAluminum", "nuggetSilver", "nuggetAluminumBrass", "silkyCloth", "silkyJewel", "nuggetObsidian", "nuggetCobalt", "nuggetArdite", "nuggetManyullyn", "nuggetBronze",
"nuggetAlumite", "nuggetSteel" };
for (int i = 0; i < materialStrings.length; i++)
{
TConstructRegistry.addItemStackToDirectory(materialStrings[i], new ItemStack(materials, 1, i));
}
String[] oreberries = { "Iron", "Gold", "Copper", "Tin", "Aluminum", "Essence" };
for (int i = 0; i < oreberries.length; i++)
{
TConstructRegistry.addItemStackToDirectory("oreberry" + oreberries[i], new ItemStack(oreBerries, 1, i));
}
TConstructRegistry.addItemStackToDirectory("diamondApple", new ItemStack(diamondApple, 1, 0));
TConstructRegistry.addItemStackToDirectory("blueSlimeFood", new ItemStack(strangeFood, 1, 0));
TConstructRegistry.addItemStackToDirectory("canisterEmpty", new ItemStack(heartCanister, 1, 0));
TConstructRegistry.addItemStackToDirectory("miniRedHeart", new ItemStack(heartCanister, 1, 1));
TConstructRegistry.addItemStackToDirectory("canisterRedHeart", new ItemStack(heartCanister, 1, 2));
TConstructRegistry.addItemStackToDirectory("spoolWire", new ItemStack(spoolWire, 1, 0));
TConstructRegistry.addItemStackToDirectory("lengthWire", new ItemStack(lengthWire, 1, 0));
//Vanilla stack sizes
Item.doorWood.setMaxStackSize(16);
Item.doorIron.setMaxStackSize(16);
Item.snowball.setMaxStackSize(64);
Item.boat.setMaxStackSize(16);
Item.minecartEmpty.setMaxStackSize(3);
Item.minecartCrate.setMaxStackSize(3);
Item.minecartPowered.setMaxStackSize(3);
Item.itemsList[Block.cake.blockID].setMaxStackSize(16);
//Block.torchWood.setTickRandomly(false);
}
void registerMaterials ()
{
TConstructRegistry.addToolMaterial(0, "Wood", "Wooden ", 0, 59, 200, 0, 1.0F, 0, 0f, "\u00A7e", "");
TConstructRegistry.addToolMaterial(1, "Stone", 1, 131, 400, 1, 0.5F, 0, 1f, "", "Stonebound");
TConstructRegistry.addToolMaterial(2, "Iron", 2, 250, 600, 2, 1.3F, 1, 0f, "\u00A7f", "");
TConstructRegistry.addToolMaterial(3, "Flint", 1, 171, 525, 2, 0.7F, 0, 0f, "\u00A78", "");
TConstructRegistry.addToolMaterial(4, "Cactus", 1, 150, 500, 2, 1.0F, 0, -1f, "\u00A72", "Jagged");
TConstructRegistry.addToolMaterial(5, "Bone", 1, 200, 400, 1, 1.0F, 0, 0f, "\u00A7e", "");
TConstructRegistry.addToolMaterial(6, "Obsidian", 3, 89, 700, 2, 0.8F, 3, 0f, "\u00A7d", "");
TConstructRegistry.addToolMaterial(7, "Netherrack", 2, 131, 400, 1, 1.2F, 0, 1f, "\u00A74", "Stonebound");
TConstructRegistry.addToolMaterial(8, "Slime", 0, 500, 150, 0, 1.5F, 0, 0f, "\u00A7a", "");
TConstructRegistry.addToolMaterial(9, "Paper", 0, 30, 200, 0, 0.3F, 0, 0f, "\u00A7f", "Writable");
TConstructRegistry.addToolMaterial(10, "Cobalt", 4, 800, 1100, 3, 1.75F, 2, 0f, "\u00A73", "");
TConstructRegistry.addToolMaterial(11, "Ardite", 4, 600, 800, 3, 2.0F, 0, 2f, "\u00A74", "Stonebound");
TConstructRegistry.addToolMaterial(12, "Manyullyn", 5, 1200, 900, 4, 2.5F, 0, 0f, "\u00A75", "");
TConstructRegistry.addToolMaterial(13, "Copper", 1, 180, 500, 2, 1.15F, 0, 0f, "\u00A7c", "");
TConstructRegistry.addToolMaterial(14, "Bronze", 2, 350, 700, 2, 1.3F, 1, 0f, "\u00A76", "");
TConstructRegistry.addToolMaterial(15, "Alumite", 4, 550, 800, 3, 1.3F, 2, 0f, "\u00A7d", "");
TConstructRegistry.addToolMaterial(16, "Steel", 4, 750, 800, 3, 1.3F, 2, 0f, "", "");
TConstructRegistry.addToolMaterial(17, "BlueSlime", "Slime ", 0, 1200, 150, 0, 2.0F, 0, 0f, "\u00A7b", "");
TConstructRegistry.addBowMaterial(0, 384, 20, 1.0f); //Wood
TConstructRegistry.addBowMaterial(1, 10, 80, 0.2f); //Stone
TConstructRegistry.addBowMaterial(2, 576, 40, 1.2f); //Iron
TConstructRegistry.addBowMaterial(3, 10, 80, 0.2f); //Flint
TConstructRegistry.addBowMaterial(4, 384, 20, 1.0f); //Cactus
TConstructRegistry.addBowMaterial(5, 192, 30, 1.0f); //Bone
TConstructRegistry.addBowMaterial(6, 10, 80, 0.2f); //Obsidian
TConstructRegistry.addBowMaterial(7, 10, 80, 0.2f); //Netherrack
TConstructRegistry.addBowMaterial(8, 1536, 20, 1.2f); //Slime
TConstructRegistry.addBowMaterial(9, 48, 25, 0.5f); //Paper
TConstructRegistry.addBowMaterial(10, 1152, 40, 1.2f); //Cobalt
TConstructRegistry.addBowMaterial(11, 960, 40, 1.2f); //Ardite
TConstructRegistry.addBowMaterial(12, 1536, 40, 1.2f); //Manyullyn
TConstructRegistry.addBowMaterial(13, 384, 40, 1.2f); //Copper
TConstructRegistry.addBowMaterial(14, 576, 40, 1.2f); //Bronze
TConstructRegistry.addBowMaterial(15, 768, 40, 1.2f); //Alumite
TConstructRegistry.addBowMaterial(16, 768, 40, 1.2f); //Steel
TConstructRegistry.addBowMaterial(17, 576, 20, 1.2f); //Blue Slime
//Material ID, mass, fragility
TConstructRegistry.addArrowMaterial(0, 0.69F, 1.0F, 100F); //Wood
TConstructRegistry.addArrowMaterial(1, 2.5F, 5.0F, 100F); //Stone
TConstructRegistry.addArrowMaterial(2, 7.2F, 0.5F, 100F); //Iron
TConstructRegistry.addArrowMaterial(3, 2.65F, 1.0F, 100F); //Flint
TConstructRegistry.addArrowMaterial(4, 0.76F, 1.0F, 100F); //Cactus
TConstructRegistry.addArrowMaterial(5, 0.69F, 1.0F, 100); //Bone
TConstructRegistry.addArrowMaterial(6, 2.4F, 1.0F, 100F); //Obsidian
TConstructRegistry.addArrowMaterial(7, 3.5F, 1.0F, 100F); //Netherrack
TConstructRegistry.addArrowMaterial(8, 0.42F, 0.0F, 100F); //Slime
TConstructRegistry.addArrowMaterial(9, 1.1F, 3.0F, 90F); //Paper
TConstructRegistry.addArrowMaterial(10, 8.9F, 0.25F, 100F); //Cobalt
TConstructRegistry.addArrowMaterial(11, 7.2F, 0.25F, 100F); //Ardite
TConstructRegistry.addArrowMaterial(12, 10.6F, 0.1F, 100F); //Manyullyn
TConstructRegistry.addArrowMaterial(13, 8.96F, 0.5F, 100F); //Copper
TConstructRegistry.addArrowMaterial(14, 7.9F, 0.25F, 100F); //Bronze
TConstructRegistry.addArrowMaterial(15, 4.7F, 0.25F, 100F); //Alumite
TConstructRegistry.addArrowMaterial(16, 7.6F, 0.25F, 100F); //Steel
TConstructRegistry.addArrowMaterial(17, 0.42F, 0.0F, 100F); //Blue Slime
TConstructRegistry.addBowstringMaterial(0, 2, new ItemStack(Item.silk), new ItemStack(bowstring, 1, 0), 1F, 1F, 1f); //String
TConstructRegistry.addFletchingMaterial(0, 2, new ItemStack(Item.feather), new ItemStack(fletching, 1, 0), 100F, 0F, 0.05F); //Feather
for (int i = 0; i < 4; i++)
TConstructRegistry.addFletchingMaterial(1, 2, new ItemStack(Block.leaves, 1, i), new ItemStack(fletching, 1, 1), 75F, 0F, 0.2F); //All four vanialla Leaves
TConstructRegistry.addFletchingMaterial(2, 2, new ItemStack(materials, 1, 1), new ItemStack(fletching, 1, 2), 100F, 0F, 0.12F); //Slime
TConstructRegistry.addFletchingMaterial(3, 2, new ItemStack(materials, 1, 17), new ItemStack(fletching, 1, 3), 100F, 0F, 0.12F); //BlueSlime
PatternBuilder pb = PatternBuilder.instance;
if (PHConstruct.enableTWood)
pb.registerFullMaterial(Block.planks, 2, "Wood", new ItemStack(Item.stick), new ItemStack(Item.stick), 0);
else
pb.registerMaterialSet("Wood", new ItemStack(Item.stick, 2), new ItemStack(Item.stick), 0);
if (PHConstruct.enableTStone)
{
pb.registerFullMaterial(Block.stone, 2, "Stone", new ItemStack(TContent.toolShard, 1, 1), new ItemStack(TContent.toolRod, 1, 1), 1);
pb.registerMaterial(Block.cobblestone, 2, "Stone");
}
else
pb.registerMaterialSet("Stone", new ItemStack(TContent.toolShard, 1, 1), new ItemStack(TContent.toolRod, 1, 1), 0);
pb.registerFullMaterial(Item.ingotIron, 2, "Iron", new ItemStack(TContent.toolShard, 1, 2), new ItemStack(TContent.toolRod, 1, 2), 2);
if (PHConstruct.enableTFlint)
pb.registerFullMaterial(Item.flint, 2, "Flint", new ItemStack(TContent.toolShard, 1, 3), new ItemStack(TContent.toolRod, 1, 3), 3);
else
pb.registerMaterialSet("Flint", new ItemStack(TContent.toolShard, 1, 3), new ItemStack(TContent.toolRod, 1, 3), 3);
if (PHConstruct.enableTCactus)
pb.registerFullMaterial(Block.cactus, 2, "Cactus", new ItemStack(TContent.toolShard, 1, 4), new ItemStack(TContent.toolRod, 1, 4), 4);
else
pb.registerMaterialSet("Cactus", new ItemStack(TContent.toolShard, 1, 4), new ItemStack(TContent.toolRod, 1, 4), 4);
if (PHConstruct.enableTBone)
pb.registerFullMaterial(Item.bone, 2, "Bone", new ItemStack(Item.dyePowder, 1, 15), new ItemStack(Item.bone), 5);
else
pb.registerMaterialSet("Bone", new ItemStack(Item.dyePowder, 1, 15), new ItemStack(Item.bone), 5);
pb.registerFullMaterial(Block.obsidian, 2, "Obsidian", new ItemStack(TContent.toolShard, 1, 6), new ItemStack(TContent.toolRod, 1, 6), 6);
pb.registerMaterial(new ItemStack(materials, 1, 18), 2, "Obsidian");
if (PHConstruct.enableTNetherrack)
pb.registerFullMaterial(Block.netherrack, 2, "Netherrack", new ItemStack(TContent.toolShard, 1, 7), new ItemStack(TContent.toolRod, 1, 7), 7);
else
pb.registerMaterialSet("Netherrack", new ItemStack(TContent.toolShard, 1, 7), new ItemStack(TContent.toolRod, 1, 7), 7);
if (PHConstruct.enableTSlime)
pb.registerFullMaterial(new ItemStack(materials, 1, 1), 2, "Slime", new ItemStack(toolShard, 1, 8), new ItemStack(toolRod, 1, 8), 8);
else
pb.registerMaterialSet("Slime", new ItemStack(TContent.toolShard, 1, 8), new ItemStack(TContent.toolRod, 1, 17), 8);
if (PHConstruct.enableTPaper)
pb.registerFullMaterial(new ItemStack(materials, 1, 0), 2, "Paper", new ItemStack(Item.paper, 2), new ItemStack(toolRod, 1, 9), 9);
else
pb.registerMaterialSet("BlueSlime", new ItemStack(Item.paper, 2), new ItemStack(TContent.toolRod, 1, 9), 9);
pb.registerMaterialSet("Cobalt", new ItemStack(toolShard, 1, 10), new ItemStack(toolRod, 1, 10), 10);
pb.registerMaterialSet("Ardite", new ItemStack(toolShard, 1, 11), new ItemStack(toolRod, 1, 11), 11);
pb.registerMaterialSet("Manyullyn", new ItemStack(toolShard, 1, 12), new ItemStack(toolRod, 1, 12), 12);
pb.registerMaterialSet("Copper", new ItemStack(toolShard, 1, 13), new ItemStack(toolRod, 1, 13), 13);
pb.registerMaterialSet("Bronze", new ItemStack(toolShard, 1, 14), new ItemStack(toolRod, 1, 14), 14);
pb.registerMaterialSet("Alumite", new ItemStack(toolShard, 1, 15), new ItemStack(toolRod, 1, 15), 15);
pb.registerMaterialSet("Steel", new ItemStack(toolShard, 1, 16), new ItemStack(toolRod, 1, 16), 16);
if (PHConstruct.enableTBlueSlime)
pb.registerFullMaterial(new ItemStack(materials, 1, 17), 2, "BlueSlime", new ItemStack(toolShard, 1, 17), new ItemStack(toolRod, 1, 17), 17);
else
pb.registerMaterialSet("BlueSlime", new ItemStack(TContent.toolShard, 1, 17), new ItemStack(TContent.toolRod, 1, 17), 17);
pb.addToolPattern((IPattern) woodPattern);
}
public static Item[] patternOutputs;
public static FluidStack[] liquids;
void addCraftingRecipes ()
{
addPartMapping();
addRecipesForToolBuilder();
addRecipesForTableCasting();
addRecipesForBasinCasting();
addRecipesForSmeltery();
addRecipesForChisel();
addRecipesForFurnace();
addRecipesForCraftingTable();
addRecipesForDryingRack();
}
private void addRecipesForCraftingTable ()
{
String[] patBlock = { "###", "###", "###" };
String[] patSurround = { "###", "#m#", "###" };
Object[] toolForgeBlocks = { "blockIron", "blockGold", Block.blockDiamond, Block.blockEmerald, "blockCobalt", "blockArdite", "blockManyullyn", "blockCopper", "blockBronze", "blockTin",
"blockNaturalAluminum", "blockAluminumBrass", "blockAlumite", "blockSteel" };
// ToolForge Recipes (Metal Version)
for (int sc = 0; sc < toolForgeBlocks.length; sc++)
{
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolForge, 1, sc), "bbb", "msm", "m m", 'b', new ItemStack(smeltery, 1, 2), 's', new ItemStack(toolStationWood, 1, 0), 'm',
toolForgeBlocks[sc]));
// adding slab version recipe
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(craftingSlabWood, 1, 5), "bbb", "msm", "m m", 'b', new ItemStack(smeltery, 1, 2), 's', new ItemStack(craftingSlabWood, 1, 1), 'm',
toolForgeBlocks[sc]));
}
// Drawbridge Recipes
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(redstoneMachine, 1, 0), "aca", "#d#", "#r#", '#', "ingotBronze", 'a', "ingotAluminumBrass", 'c', new ItemStack(blankPattern, 1, 1),
'r', new ItemStack(Item.redstone), 'd', new ItemStack(Block.dispenser)));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(redstoneMachine, 1, 0), "aca", "#d#", "#r#", '#', "ingotBronze", 'a', "ingotAluminumBrass", 'c', new ItemStack(blankPattern, 1, 2),
'r', new ItemStack(Item.redstone), 'd', new ItemStack(Block.dispenser)));
// Igniter Recipes
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(redstoneMachine, 1, 1), "aca", "#d#", "#r#", '#', "ingotBronze", 'a', "ingotAluminumBrass", 'c', new ItemStack(largePlate, 1, 7), 'r',
new ItemStack(Item.redstone), 'd', new ItemStack(Item.flintAndSteel)));
// Advanced Drawbridge Recipes
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(redstoneMachine, 1, 2), " c ", "rdr", " a ", 'a', "ingotAluminumBrass", 'c', new ItemStack(blankPattern, 1, 1), 'r', new ItemStack(
Item.redstone), 'd', new ItemStack(redstoneMachine, 1, 0)));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(redstoneMachine, 1, 2), " c ", "rdr", " a ", 'a', "ingotAluminumBrass", 'c', new ItemStack(blankPattern, 1, 2), 'r', new ItemStack(
Item.redstone), 'd', new ItemStack(redstoneMachine, 1, 0)));
// ToolStation Recipes (Wooden Version)
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolStationWood, 1, 0), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', "crafterWood"));
GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 0), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(craftingStationWood, 1, 0));
GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 0), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(craftingSlabWood, 1, 0));
GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 2), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.wood, 1, 1));
GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 3), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.wood, 1, 2));
GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 4), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.wood, 1, 3));
GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 5), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', Block.chest);
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolStationWood, 1, 1), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', "logWood"));
if (PHConstruct.stencilTableCrafting)
{
GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 10), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.planks, 1, 0));
GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 11), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.planks, 1, 1));
GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 12), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.planks, 1, 2));
GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 13), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.planks, 1, 3));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolStationWood, 1, 10), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', "plankWood"));
}
// Blank Pattern Recipe
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(blankPattern, 1, 0), "ps", "sp", 'p', "plankWood", 's', "stickWood"));
// Manual Book Recipes
GameRegistry.addRecipe(new ItemStack(manualBook), "wp", 'w', new ItemStack(blankPattern, 1, 0), 'p', Item.paper);
GameRegistry.addShapelessRecipe(new ItemStack(manualBook, 2, 0), new ItemStack(manualBook, 1, 0), Item.book);
GameRegistry.addShapelessRecipe(new ItemStack(manualBook, 1, 1), new ItemStack(manualBook, 1, 0));
GameRegistry.addShapelessRecipe(new ItemStack(manualBook, 2, 1), new ItemStack(manualBook, 1, 1), Item.book);
GameRegistry.addShapelessRecipe(new ItemStack(manualBook, 1, 2), new ItemStack(manualBook, 1, 1));
GameRegistry.addShapelessRecipe(new ItemStack(manualBook, 2, 2), new ItemStack(manualBook, 1, 2), Item.book);
// alternativ Vanilla Book Recipe
GameRegistry.addShapelessRecipe(new ItemStack(Item.book), Item.paper, Item.paper, Item.paper, Item.silk, blankPattern, blankPattern);
// Paperstack Recipe
GameRegistry.addRecipe(new ItemStack(materials, 1, 0), "pp", "pp", 'p', Item.paper);
// Mossball Recipe
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(materials, 1, 6), patBlock, '#', "stoneMossy"));
// LavaCrystal Recipes -Auto-smelt
GameRegistry.addRecipe(new ItemStack(materials, 1, 7), "xcx", "cbc", "xcx", 'b', Item.bucketLava, 'c', Item.fireballCharge, 'x', Item.blazeRod);
GameRegistry.addRecipe(new ItemStack(materials, 1, 7), "xcx", "cbc", "xcx", 'b', Item.bucketLava, 'x', Item.fireballCharge, 'c', Item.blazeRod);
// Slimy sand Recipes
GameRegistry.addShapelessRecipe(new ItemStack(craftedSoil, 1, 0), Item.slimeBall, Item.slimeBall, Item.slimeBall, Item.slimeBall, Block.sand, Block.dirt);
GameRegistry.addShapelessRecipe(new ItemStack(craftedSoil, 1, 2), strangeFood, strangeFood, strangeFood, strangeFood, Block.sand, Block.dirt);
// Grout Recipes
GameRegistry.addShapelessRecipe(new ItemStack(craftedSoil, 2, 1), Item.clay, Block.sand, Block.gravel);
GameRegistry.addRecipe(new ItemStack(craftedSoil, 8, 1), "sgs", "gcg", "sgs", 'c', new ItemStack(Block.stainedClay, 1, Short.MAX_VALUE), 's', Block.sand, 'g', Block.gravel);
GameRegistry.addRecipe(new ItemStack(craftedSoil, 8, 1), "sgs", "gcg", "sgs", 'c', new ItemStack(Block.blockClay, 1, Short.MAX_VALUE), 's', Block.sand, 'g', Block.gravel);
// Graveyard Soil Recipes
GameRegistry.addShapelessRecipe(new ItemStack(craftedSoil, 1, 3), Block.dirt, Item.rottenFlesh, new ItemStack(Item.dyePowder, 1, 15));
// Silky Cloth Recipes
GameRegistry.addRecipe(new ItemStack(materials, 1, 25), patSurround, 'm', new ItemStack(materials, 1, 24), '#', new ItemStack(Item.silk));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(materials, 1, 25), patSurround, 'm', "nuggetGold", '#', new ItemStack(Item.silk)));
// Silky Jewel Recipes
GameRegistry.addRecipe(new ItemStack(materials, 1, 26), " c ", "cec", " c ", 'c', new ItemStack(materials, 1, 25), 'e', new ItemStack(Item.emerald));
// Ender Stuff
GameRegistry.addRecipe(new ItemStack(Item.enderPearl, 9), "m", 'm', new ItemStack(metalBlock.blockID, 1, 10));
// Wooden Armor Recipes
GameRegistry.addRecipe(new ShapedOreRecipe(helmetWood, new Object[] { "www", "w w", 'w', "logWood" }));
GameRegistry.addRecipe(new ShapedOreRecipe(chestplateWood, new Object[] { "w w", "www", "www", 'w', "logWood" }));
GameRegistry.addRecipe(new ShapedOreRecipe(leggingsWood, new Object[] { "www", "w w", "w w", 'w', "logWood" }));
GameRegistry.addRecipe(new ShapedOreRecipe(bootsWood, new Object[] { "w w", "w w", 'w', "logWood" }));
// Metal conversion Recipes
GameRegistry.addRecipe(new ItemStack(materials, 9, 9), "m", 'm', new ItemStack(metalBlock, 1, 3)); //Copper
GameRegistry.addRecipe(new ItemStack(materials, 9, 10), "m", 'm', new ItemStack(metalBlock, 1, 5)); //Tin
GameRegistry.addRecipe(new ItemStack(materials, 9, 12), "m", 'm', new ItemStack(metalBlock, 1, 6)); //Aluminum
GameRegistry.addRecipe(new ItemStack(materials, 9, 13), "m", 'm', new ItemStack(metalBlock, 1, 4)); //Bronze
GameRegistry.addRecipe(new ItemStack(materials, 9, 14), "m", 'm', new ItemStack(metalBlock, 1, 7)); //AluBrass
GameRegistry.addRecipe(new ItemStack(materials, 9, 3), "m", 'm', new ItemStack(metalBlock, 1, 0)); //Cobalt
GameRegistry.addRecipe(new ItemStack(materials, 9, 4), "m", 'm', new ItemStack(metalBlock, 1, 1)); //Ardite
GameRegistry.addRecipe(new ItemStack(materials, 9, 5), "m", 'm', new ItemStack(metalBlock, 1, 2)); //Manyullyn
GameRegistry.addRecipe(new ItemStack(materials, 9, 15), "m", 'm', new ItemStack(metalBlock, 1, 8)); //Alumite
GameRegistry.addRecipe(new ItemStack(materials, 9, 16), "m", 'm', new ItemStack(metalBlock, 1, 9)); //Steel
GameRegistry.addRecipe(new ItemStack(Item.ingotIron), patBlock, '#', new ItemStack(materials, 1, 19)); //Iron
GameRegistry.addRecipe(new ItemStack(materials, 1, 9), patBlock, '#', new ItemStack(materials, 1, 20)); //Copper
GameRegistry.addRecipe(new ItemStack(materials, 1, 10), patBlock, '#', new ItemStack(materials, 1, 21)); //Tin
GameRegistry.addRecipe(new ItemStack(materials, 1, 12), patBlock, '#', new ItemStack(materials, 1, 22)); //Aluminum
GameRegistry.addRecipe(new ItemStack(materials, 1, 14), patBlock, '#', new ItemStack(materials, 1, 24)); //Aluminum Brass
GameRegistry.addRecipe(new ItemStack(materials, 1, 18), patBlock, '#', new ItemStack(materials, 1, 27)); //Obsidian
GameRegistry.addRecipe(new ItemStack(materials, 1, 3), patBlock, '#', new ItemStack(materials, 1, 28)); //Cobalt
GameRegistry.addRecipe(new ItemStack(materials, 1, 4), patBlock, '#', new ItemStack(materials, 1, 29)); //Ardite
GameRegistry.addRecipe(new ItemStack(materials, 1, 5), patBlock, '#', new ItemStack(materials, 1, 30)); //Manyullyn
GameRegistry.addRecipe(new ItemStack(materials, 1, 13), patBlock, '#', new ItemStack(materials, 1, 31)); //Bronze
GameRegistry.addRecipe(new ItemStack(materials, 1, 15), patBlock, '#', new ItemStack(materials, 1, 32)); //Alumite
GameRegistry.addRecipe(new ItemStack(materials, 1, 16), patBlock, '#', new ItemStack(materials, 1, 33)); //Steel
GameRegistry.addRecipe(new ItemStack(materials, 9, 19), "m", 'm', new ItemStack(Item.ingotIron)); //Iron
GameRegistry.addRecipe(new ItemStack(materials, 9, 20), "m", 'm', new ItemStack(materials, 1, 9)); //Copper
GameRegistry.addRecipe(new ItemStack(materials, 9, 21), "m", 'm', new ItemStack(materials, 1, 10)); //Tin
GameRegistry.addRecipe(new ItemStack(materials, 9, 22), "m", 'm', new ItemStack(materials, 1, 12)); //Aluminum
GameRegistry.addRecipe(new ItemStack(materials, 9, 24), "m", 'm', new ItemStack(materials, 1, 14)); //Aluminum Brass
GameRegistry.addRecipe(new ItemStack(materials, 9, 27), "m", 'm', new ItemStack(materials, 1, 18)); //Obsidian
GameRegistry.addRecipe(new ItemStack(materials, 9, 28), "m", 'm', new ItemStack(materials, 1, 3)); //Cobalt
GameRegistry.addRecipe(new ItemStack(materials, 9, 29), "m", 'm', new ItemStack(materials, 1, 4)); //Ardite
GameRegistry.addRecipe(new ItemStack(materials, 9, 30), "m", 'm', new ItemStack(materials, 1, 5)); //Manyullyn
GameRegistry.addRecipe(new ItemStack(materials, 9, 31), "m", 'm', new ItemStack(materials, 1, 13)); //Bronze
GameRegistry.addRecipe(new ItemStack(materials, 9, 32), "m", 'm', new ItemStack(materials, 1, 15)); //Alumite
GameRegistry.addRecipe(new ItemStack(materials, 9, 33), "m", 'm', new ItemStack(materials, 1, 16)); //Steel
// stained Glass Recipes
String[] dyeTypes = { "dyeBlack", "dyeRed", "dyeGreen", "dyeBrown", "dyeBlue", "dyePurple", "dyeCyan", "dyeLightGray", "dyeGray", "dyePink", "dyeLime", "dyeYellow", "dyeLightBlue",
"dyeMagenta", "dyeOrange", "dyeWhite" };
String color = "";
for (int i = 0; i < 16; i++)
{
color = dyeTypes[15 - i];
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(Block.cloth, 8, i), patSurround, 'm', color, '#', new ItemStack(Block.cloth, 1, Short.MAX_VALUE)));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(stainedGlassClear, 8, i), patSurround, 'm', color, '#', clearGlass));
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(stainedGlassClear, 1, i), color, clearGlass));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(stainedGlassClear, 8, i), patSurround, 'm', color, '#', new ItemStack(stainedGlassClear, 1, Short.MAX_VALUE)));
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(stainedGlassClear, 1, i), color, new ItemStack(stainedGlassClear, 1, Short.MAX_VALUE)));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(stainedGlassClearPane, 8, i), patSurround, 'm', color, '#', glassPane));
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(stainedGlassClearPane, 1, i), color, glassPane));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(stainedGlassClearPane, 8, i), patSurround, 'm', color, '#', new ItemStack(stainedGlassClearPane, 1, Short.MAX_VALUE)));
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(stainedGlassClearPane, 1, i), color, new ItemStack(stainedGlassClearPane, 1, Short.MAX_VALUE)));
}
// Glass Recipes
GameRegistry.addRecipe(new ItemStack(Item.glassBottle, 3), new Object[] { "# #", " # ", '#', clearGlass });
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(Block.daylightSensor), new Object[] { "GGG", "QQQ", "WWW", 'G', "glass", 'Q', Item.netherQuartz, 'W', "slabWood" }));
GameRegistry.addRecipe(new ItemStack(Block.beacon, 1), new Object[] { "GGG", "GSG", "OOO", 'G', clearGlass, 'S', Item.netherStar, 'O', Block.obsidian });
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(glassPane, 16, 0), "GGG", "GGG", 'G', clearGlass));
// Smeltery Components Recipes
ItemStack searedBrick = new ItemStack(materials, 1, 2);
GameRegistry.addRecipe(new ItemStack(smeltery, 1, 0), "bbb", "b b", "bbb", 'b', searedBrick); //Controller
GameRegistry.addRecipe(new ItemStack(smeltery, 1, 1), "b b", "b b", "b b", 'b', searedBrick); //Drain
GameRegistry.addRecipe(new ItemStack(smeltery, 1, 2), "bb", "bb", 'b', searedBrick); //Bricks
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(lavaTank, 1, 0), patSurround, '#', searedBrick, 'm', "glass")); //Tank
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(lavaTank, 1, 1), "bgb", "ggg", "bgb", 'b', searedBrick, 'g', "glass")); //Glass
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(lavaTank, 1, 2), "bgb", "bgb", "bgb", 'b', searedBrick, 'g', "glass")); //Window
GameRegistry.addRecipe(new ItemStack(searedBlock, 1, 0), "bbb", "b b", "b b", 'b', searedBrick); //Table
GameRegistry.addRecipe(new ItemStack(searedBlock, 1, 1), "b b", " b ", 'b', searedBrick); //Faucet
GameRegistry.addRecipe(new ItemStack(searedBlock, 1, 2), "b b", "b b", "bbb", 'b', searedBrick); //Basin
GameRegistry.addRecipe(new ItemStack(castingChannel, 4, 0), "b b", "bbb", 'b', searedBrick); //Channel
// Jack o'Latern Recipe - Stone Torch
GameRegistry.addRecipe(new ItemStack(Block.pumpkinLantern, 1, 0), "p", "s", 'p', new ItemStack(Block.pumpkin), 's', new ItemStack(stoneTorch));
// Stone Torch Recipe
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(stoneTorch, 4), "p", "w", 'p', new ItemStack(Item.coal, 1, Short.MAX_VALUE), 'w', "stoneRod"));
// Stone Ladder Recipe
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(stoneLadder, 3), "w w", "www", "w w", 'w', "stoneRod"));
// Wooden Rail Recipe
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(woodenRail, 4, 0), "b b", "bxb", "b b", 'b', "plankWood", 'x', "stickWood"));
// Stonesticks Recipes
GameRegistry.addRecipe(new ItemStack(toolRod, 4, 1), "c", "c", 'c', new ItemStack(Block.stone));
GameRegistry.addRecipe(new ItemStack(toolRod, 2, 1), "c", "c", 'c', new ItemStack(Block.cobblestone));
//
ItemStack aluBrass = new ItemStack(materials, 1, 14);
// Clock Recipe - Vanilla alternativ
GameRegistry.addRecipe(new ItemStack(Item.pocketSundial), " i ", "iri", " i ", 'i', aluBrass, 'r', new ItemStack(Item.redstone));
// Gold Pressure Plate - Vanilla alternativ
GameRegistry.addRecipe(new ItemStack(Block.pressurePlateGold), "ii", 'i', aluBrass);
//Accessories
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(heartCanister, 1, 0), "##", "##", '#', "ingotNaturalAluminum"));
GameRegistry.addRecipe(new ItemStack(diamondApple), " d ", "d#d", " d ", 'd', new ItemStack(Item.diamond), '#', new ItemStack(Item.appleRed));
GameRegistry.addShapelessRecipe(new ItemStack(heartCanister, 1, 2), new ItemStack(diamondApple), new ItemStack(materials, 1, 8), new ItemStack(heartCanister, 1, 0), new ItemStack(
heartCanister, 1, 1));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(knapsack, 1, 0), "###", "rmr", "###", '#', new ItemStack(Item.leather), 'r', new ItemStack(toughRod, 1, 2), 'm', "ingotGold"));
GameRegistry.addRecipe(new ItemStack(knapsack, 1, 0), "###", "rmr", "###", '#', new ItemStack(Item.leather), 'r', new ItemStack(toughRod, 1, 2), 'm', aluBrass);
// Drying Rack Recipes
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(dryingRack, 1, 0), "bbb", 'b', "slabWood"));
//Landmine Recipes
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(landmine, 1, 0), "mcm", "rpr", 'm', "plankWood", 'c', new ItemStack(blankPattern, 1, 1), 'r', Item.redstone, 'p',
Block.pressurePlateStone));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(landmine, 1, 1), "mcm", "rpr", 'm', Block.stone, 'c', new ItemStack(blankPattern, 1, 1), 'r', Item.redstone, 'p',
Block.pressurePlateStone));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(landmine, 1, 2), "mcm", "rpr", 'm', Block.obsidian, 'c', new ItemStack(blankPattern, 1, 1), 'r', Item.redstone, 'p',
Block.pressurePlateStone));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(landmine, 1, 3), "mcm", "rpr", 'm', Item.redstoneRepeater, 'c', new ItemStack(blankPattern, 1, 1), 'r', Item.redstone, 'p',
Block.pressurePlateStone));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(signalBus.blockID, 1, 0), "www", "sss", 'w', lengthWire, 's', new ItemStack(Block.stoneSingleSlab, 1, OreDictionary.WILDCARD_VALUE)));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(signalTerminal.blockID, 1, 0), "b", "g", "b", 'b', new ItemStack(signalBus.blockID, 1, 0), 'g', new ItemStack(Block.glass, 1,
OreDictionary.WILDCARD_VALUE)));
GameRegistry.addRecipe(new ItemStack(lengthWire, 8), "a", "a", 'a', aluBrass);
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(spoolWire, 1, 256 - 8), "www", "wrw", "www", 'w', lengthWire, 'r', "stoneRod"));
GameRegistry.addRecipe(new SpoolRepairRecipe(new ItemStack(spoolWire, 1, 256), new ItemStack(lengthWire, 1)));
//Ultra hardcore recipes
GameRegistry.addRecipe(new ItemStack(goldHead), patSurround, '#', new ItemStack(Item.ingotGold), 'm', new ItemStack(Item.skull, 1, 3));
// Slab Smeltery Components Recipes
for (int i = 0; i < 7; i++)
{
GameRegistry.addRecipe(new ItemStack(speedSlab, 6, i), "bbb", 'b', new ItemStack(speedBlock, 1, i));
}
GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 0), "bbb", 'b', new ItemStack(smeltery, 1, 2));
GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 1), "bbb", 'b', new ItemStack(smeltery, 1, 4));
GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 2), "bbb", 'b', new ItemStack(smeltery, 1, 5));
GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 3), "bbb", 'b', new ItemStack(smeltery, 1, 6));
GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 4), "bbb", 'b', new ItemStack(smeltery, 1, 8));
GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 5), "bbb", 'b', new ItemStack(smeltery, 1, 9));
GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 6), "bbb", 'b', new ItemStack(smeltery, 1, 10));
GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 7), "bbb", 'b', new ItemStack(smeltery, 1, 11));
// Wool Slab Recipes
for (int sc = 0; sc <= 7; sc++)
{
GameRegistry.addRecipe(new ItemStack(woolSlab1, 6, sc), "www", 'w', new ItemStack(Block.cloth, 1, sc));
GameRegistry.addRecipe(new ItemStack(woolSlab2, 6, sc), "www", 'w', new ItemStack(Block.cloth, 1, sc + 8));
GameRegistry.addShapelessRecipe(new ItemStack(Block.cloth, 1, sc), new ItemStack(woolSlab1, 1, sc), new ItemStack(woolSlab1, 1, sc));
GameRegistry.addShapelessRecipe(new ItemStack(Block.cloth, 1, sc + 8), new ItemStack(woolSlab2, 1, sc), new ItemStack(woolSlab2, 1, sc));
}
GameRegistry.addRecipe(new ItemStack(woolSlab1, 6, 0), "www", 'w', new ItemStack(Block.cloth, 1, Short.MAX_VALUE));
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(Block.cloth, 1, 0), "slabCloth", "slabCloth"));
//Trap Recipes
GameRegistry.addRecipe(new ItemStack(punji, 5, 0), "b b", " b ", "b b", 'b', new ItemStack(Item.reed));
GameRegistry.addRecipe(new ItemStack(barricadeSpruce, 1, 0), "b", "b", 'b', new ItemStack(Block.wood, 1, 1));
GameRegistry.addRecipe(new ItemStack(barricadeBirch, 1, 0), "b", "b", 'b', new ItemStack(Block.wood, 1, 2));
GameRegistry.addRecipe(new ItemStack(barricadeJungle, 1, 0), "b", "b", 'b', new ItemStack(Block.wood, 1, 3));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(barricadeOak, 1, 0), "b", "b", 'b', "logWood"));
// Advanced WorkBench Recipes
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(craftingStationWood, 1, 0), "b", 'b', "crafterWood"));
//Slab crafters
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(craftingSlabWood, 6, 0), "bbb", 'b', "crafterWood"));
GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 0), "b", 'b', new ItemStack(craftingStationWood, 1, 0));
GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 1), "b", 'b', new ItemStack(toolStationWood, 1, 0));
GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 2), "b", 'b', new ItemStack(toolStationWood, 1, 1));
GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 2), "b", 'b', new ItemStack(toolStationWood, 1, 2));
GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 2), "b", 'b', new ItemStack(toolStationWood, 1, 3));
GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 2), "b", 'b', new ItemStack(toolStationWood, 1, 4));
GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 4), "b", 'b', new ItemStack(toolStationWood, 1, 5));
GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 3), "b", 'b', new ItemStack(toolStationWood, 1, 10));
GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 3), "b", 'b', new ItemStack(toolStationWood, 1, 11));
GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 3), "b", 'b', new ItemStack(toolStationWood, 1, 12));
GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 3), "b", 'b', new ItemStack(toolStationWood, 1, 13));
GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 5), "b", 'b', new ItemStack(toolForge, 1, Short.MAX_VALUE));
// EssenceExtractor Recipe
GameRegistry.addRecipe(new ItemStack(essenceExtractor, 1, 0), " b ", "eme", "mmm", 'b', Item.book, 'e', Item.emerald, 'm', Block.whiteStone);
//Slime Recipes
GameRegistry.addRecipe(new ItemStack(slimeGel, 1, 0), "##", "##", '#', strangeFood);
GameRegistry.addRecipe(new ItemStack(strangeFood, 4, 0), "#", '#', new ItemStack(slimeGel, 1, 0));
GameRegistry.addRecipe(new ItemStack(slimeGel, 1, 1), "##", "##", '#', Item.slimeBall);
GameRegistry.addRecipe(new ItemStack(Item.slimeBall, 4, 0), "#", '#', new ItemStack(slimeGel, 1, 1));
//slimeExplosive
GameRegistry.addShapelessRecipe(new ItemStack(slimeExplosive, 1, 0), Item.slimeBall, Block.tnt);
GameRegistry.addShapelessRecipe(new ItemStack(slimeExplosive, 1, 2), strangeFood, Block.tnt);
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(slimeExplosive, 1, 0), "slimeball", Block.tnt));
GameRegistry.addShapelessRecipe(new ItemStack(slimeChannel, 1, 0), new ItemStack(slimeGel, 1, Short.MAX_VALUE), new ItemStack(Item.redstone));
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(slimePad, 1, 0), slimeChannel, new ItemStack(slimeGel, 1, Short.MAX_VALUE), "slimeBall"));
}
private void addRecipesForFurnace ()
{
FurnaceRecipes.smelting().addSmelting(craftedSoil.blockID, 3, new ItemStack(craftedSoil, 1, 4), 0.2f); //Concecrated Soil
FurnaceRecipes.smelting().addSmelting(craftedSoil.blockID, 0, new ItemStack(materials, 1, 1), 2f); //Slime
FurnaceRecipes.smelting().addSmelting(craftedSoil.blockID, 1, new ItemStack(materials, 1, 2), 2f); //Seared brick item
FurnaceRecipes.smelting().addSmelting(craftedSoil.blockID, 2, new ItemStack(materials, 1, 17), 2f); //Blue Slime
//FurnaceRecipes.smelting().addSmelting(oreSlag.blockID, 1, new ItemStack(materials, 1, 3), 3f);
//FurnaceRecipes.smelting().addSmelting(oreSlag.blockID, 2, new ItemStack(materials, 1, 4), 3f);
FurnaceRecipes.smelting().addSmelting(oreSlag.blockID, 3, new ItemStack(materials, 1, 9), 0.5f);
FurnaceRecipes.smelting().addSmelting(oreSlag.blockID, 4, new ItemStack(materials, 1, 10), 0.5f);
FurnaceRecipes.smelting().addSmelting(oreSlag.blockID, 5, new ItemStack(materials, 1, 12), 0.5f);
FurnaceRecipes.smelting().addSmelting(oreBerries.itemID, 0, new ItemStack(materials, 1, 19), 0.2f);
FurnaceRecipes.smelting().addSmelting(oreBerries.itemID, 1, new ItemStack(Item.goldNugget), 0.2f);
FurnaceRecipes.smelting().addSmelting(oreBerries.itemID, 2, new ItemStack(materials, 1, 20), 0.2f);
FurnaceRecipes.smelting().addSmelting(oreBerries.itemID, 3, new ItemStack(materials, 1, 21), 0.2f);
FurnaceRecipes.smelting().addSmelting(oreBerries.itemID, 4, new ItemStack(materials, 1, 22), 0.2f);
//FurnaceRecipes.smelting().addSmelting(oreBerries.itemID, 5, new ItemStack(materials, 1, 23), 0.2f);
FurnaceRecipes.smelting().addSmelting(oreGravel.blockID, 0, new ItemStack(Item.ingotIron), 0.2f);
FurnaceRecipes.smelting().addSmelting(oreGravel.blockID, 1, new ItemStack(Item.ingotGold), 0.2f);
FurnaceRecipes.smelting().addSmelting(oreGravel.blockID, 2, new ItemStack(materials, 1, 9), 0.2f);
FurnaceRecipes.smelting().addSmelting(oreGravel.blockID, 3, new ItemStack(materials, 1, 10), 0.2f);
FurnaceRecipes.smelting().addSmelting(oreGravel.blockID, 4, new ItemStack(materials, 1, 12), 0.2f);
FurnaceRecipes.smelting().addSmelting(speedBlock.blockID, 0, new ItemStack(speedBlock, 1, 2), 0.2f);
}
private void addPartMapping ()
{
/* Tools */
patternOutputs = new Item[] { toolRod, pickaxeHead, shovelHead, hatchetHead, swordBlade, wideGuard, handGuard, crossbar, binding, frypanHead, signHead, knifeBlade, chiselHead, toughRod,
toughBinding, largePlate, broadAxeHead, scytheBlade, excavatorHead, largeSwordBlade, hammerHead, fullGuard, null, null, arrowhead };
int[] nonMetals = { 0, 1, 3, 4, 5, 6, 7, 8, 9 };
if (PHConstruct.craftMetalTools)
{
for (int mat = 0; mat < 18; mat++)
{
for (int meta = 0; meta < patternOutputs.length; meta++)
{
if (patternOutputs[meta] != null)
TConstructRegistry.addPartMapping(woodPattern.itemID, meta + 1, mat, new ItemStack(patternOutputs[meta], 1, mat));
}
}
}
else
{
for (int mat = 0; mat < nonMetals.length; mat++)
{
for (int meta = 0; meta < patternOutputs.length; meta++)
{
if (patternOutputs[meta] != null)
TConstructRegistry.addPartMapping(woodPattern.itemID, meta + 1, nonMetals[mat], new ItemStack(patternOutputs[meta], 1, nonMetals[mat]));
}
}
}
}
private void addRecipesForToolBuilder ()
{
ToolBuilder tb = ToolBuilder.instance;
tb.addNormalToolRecipe(pickaxe, pickaxeHead, toolRod, binding);
tb.addNormalToolRecipe(broadsword, swordBlade, toolRod, wideGuard);
tb.addNormalToolRecipe(hatchet, hatchetHead, toolRod);
tb.addNormalToolRecipe(shovel, shovelHead, toolRod);
tb.addNormalToolRecipe(longsword, swordBlade, toolRod, handGuard);
tb.addNormalToolRecipe(rapier, swordBlade, toolRod, crossbar);
tb.addNormalToolRecipe(frypan, frypanHead, toolRod);
tb.addNormalToolRecipe(battlesign, signHead, toolRod);
tb.addNormalToolRecipe(mattock, hatchetHead, toolRod, shovelHead);
tb.addNormalToolRecipe(dagger, knifeBlade, toolRod, crossbar);
tb.addNormalToolRecipe(cutlass, swordBlade, toolRod, fullGuard);
tb.addNormalToolRecipe(chisel, chiselHead, toolRod);
tb.addNormalToolRecipe(scythe, scytheBlade, toughRod, toughBinding, toughRod);
tb.addNormalToolRecipe(lumberaxe, broadAxeHead, toughRod, largePlate, toughBinding);
tb.addNormalToolRecipe(cleaver, largeSwordBlade, toughRod, largePlate, toughRod);
tb.addNormalToolRecipe(excavator, excavatorHead, toughRod, largePlate, toughBinding);
tb.addNormalToolRecipe(hammer, hammerHead, toughRod, largePlate, largePlate);
tb.addNormalToolRecipe(battleaxe, broadAxeHead, toughRod, broadAxeHead, toughBinding);
//tb.addNormalToolRecipe(shortbow, toolRod, bowstring, toolRod);
BowRecipe recipe = new BowRecipe(toolRod, bowstring, toolRod, shortbow);
tb.addCustomToolRecipe(recipe);
tb.addNormalToolRecipe(arrow, arrowhead, toolRod, fletching);
ItemStack diamond = new ItemStack(Item.diamond);
tb.registerToolMod(new ModRepair());
tb.registerToolMod(new ModDurability(new ItemStack[] { diamond }, 0, 500, 0f, 3, "Diamond", "\u00a7bDurability +500", "\u00a7b"));
tb.registerToolMod(new ModDurability(new ItemStack[] { new ItemStack(Item.emerald) }, 1, 0, 0.5f, 2, "Emerald", "\u00a72Durability +50%", "\u00a72"));
modE = new ModElectric();
tb.registerToolMod(modE);
ItemStack redstoneItem = new ItemStack(Item.redstone);
ItemStack redstoneBlock = new ItemStack(Block.blockRedstone);
tb.registerToolMod(new ModRedstone(new ItemStack[] { redstoneItem }, 2, 1));
tb.registerToolMod(new ModRedstone(new ItemStack[] { redstoneItem, redstoneItem }, 2, 2));
tb.registerToolMod(new ModRedstone(new ItemStack[] { redstoneBlock }, 2, 9));
tb.registerToolMod(new ModRedstone(new ItemStack[] { redstoneItem, redstoneBlock }, 2, 10));
tb.registerToolMod(new ModRedstone(new ItemStack[] { redstoneBlock, redstoneBlock }, 2, 18));
ItemStack lapisItem = new ItemStack(Item.dyePowder, 1, 4);
ItemStack lapisBlock = new ItemStack(Block.blockLapis);
modL = new ModLapis(new ItemStack[] { lapisItem }, 10, 1);
tb.registerToolMod(modL);
tb.registerToolMod(new ModLapis(new ItemStack[] { lapisItem, lapisItem }, 10, 2));
tb.registerToolMod(new ModLapis(new ItemStack[] { lapisBlock }, 10, 9));
tb.registerToolMod(new ModLapis(new ItemStack[] { lapisItem, lapisBlock }, 10, 10));
tb.registerToolMod(new ModLapis(new ItemStack[] { lapisBlock, lapisBlock }, 10, 18));
tb.registerToolMod(new ModInteger(new ItemStack[] { new ItemStack(materials, 1, 6) }, 4, "Moss", 3, "\u00a72", "Auto-Repair"));
ItemStack blazePowder = new ItemStack(Item.blazePowder);
tb.registerToolMod(new ModBlaze(new ItemStack[] { blazePowder }, 7, 1));
tb.registerToolMod(new ModBlaze(new ItemStack[] { blazePowder, blazePowder }, 7, 2));
tb.registerToolMod(new ModAutoSmelt(new ItemStack[] { new ItemStack(materials, 1, 7) }, 6, "Lava", "\u00a74", "Auto-Smelt"));
tb.registerToolMod(new ModInteger(new ItemStack[] { new ItemStack(materials, 1, 8) }, 8, "Necrotic", 1, "\u00a78", "Life Steal"));
ItemStack quartzItem = new ItemStack(Item.netherQuartz);
ItemStack quartzBlock = new ItemStack(Block.blockNetherQuartz, 1, Short.MAX_VALUE);
tb.registerToolMod(new ModAttack("Quartz", new ItemStack[] { quartzItem }, 11, 1));
tb.registerToolMod(new ModAttack("Quartz", new ItemStack[] { quartzItem, quartzItem }, 11, 2));
tb.registerToolMod(new ModAttack("Quartz", new ItemStack[] { quartzBlock }, 11, 4));
tb.registerToolMod(new ModAttack("Quartz", new ItemStack[] { quartzItem, quartzBlock }, 11, 5));
tb.registerToolMod(new ModAttack("Quartz", new ItemStack[] { quartzBlock, quartzBlock }, 11, 8));
tb.registerToolMod(new ModExtraModifier(new ItemStack[] { diamond, new ItemStack(Block.blockGold) }, "Tier1Free"));
tb.registerToolMod(new ModExtraModifier(new ItemStack[] { new ItemStack(Item.netherStar) }, "Tier2Free"));
ItemStack silkyJewel = new ItemStack(materials, 1, 26);
tb.registerToolMod(new ModButtertouch(new ItemStack[] { silkyJewel }, 12));
ItemStack piston = new ItemStack(Block.pistonBase);
tb.registerToolMod(new ModPiston(new ItemStack[] { piston }, 3, 1));
tb.registerToolMod(new ModPiston(new ItemStack[] { piston, piston }, 3, 2));
tb.registerToolMod(new ModInteger(new ItemStack[] { new ItemStack(Block.obsidian), new ItemStack(Item.enderPearl) }, 13, "Beheading", 1, "\u00a7d", "Beheading"));
ItemStack holySoil = new ItemStack(craftedSoil, 1, 4);
tb.registerToolMod(new ModSmite("Smite", new ItemStack[] { holySoil }, 14, 1));
tb.registerToolMod(new ModSmite("Smite", new ItemStack[] { holySoil, holySoil }, 14, 2));
ItemStack spidereyeball = new ItemStack(Item.fermentedSpiderEye);
tb.registerToolMod(new ModAntiSpider("Anti-Spider", new ItemStack[] { spidereyeball }, 15, 1));
tb.registerToolMod(new ModAntiSpider("Anti-Spider", new ItemStack[] { spidereyeball, spidereyeball }, 15, 2));
ItemStack obsidianPlate = new ItemStack(largePlate, 1, 6);
tb.registerToolMod(new ModReinforced(new ItemStack[] { obsidianPlate }, 16, 1));
TConstructRegistry.registerActiveToolMod(new TActiveOmniMod());
}
private void addRecipesForTableCasting ()
{
/* Smeltery */
ItemStack ingotcast = new ItemStack(metalPattern, 1, 0);
LiquidCasting tableCasting = TConstructRegistry.instance.getTableCasting();
//Blank
tableCasting.addCastingRecipe(new ItemStack(blankPattern, 1, 1), new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue), 80);
tableCasting.addCastingRecipe(new ItemStack(blankPattern, 1, 2), new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2), 80);
//Ingots
tableCasting.addCastingRecipe(new ItemStack(materials, 1, 2), new FluidStack(moltenStoneFluid, TConstruct.ingotLiquidValue), ingotcast, 80); //stone
//Buckets
ItemStack bucket = new ItemStack(Item.bucketEmpty);
for (int sc = 0; sc < 24; sc++)
{
tableCasting.addCastingRecipe(new ItemStack(buckets, 1, sc), new FluidStack(fluids[sc], FluidContainerRegistry.BUCKET_VOLUME), bucket, true, 10);
}
// Clear glass pane casting
tableCasting.addCastingRecipe(new ItemStack(glassPane), new FluidStack(moltenGlassFluid, 250), null, 80);
// Metal toolpart casting
liquids = new FluidStack[] { new FluidStack(moltenIronFluid, 1), new FluidStack(moltenCopperFluid, 1), new FluidStack(moltenCobaltFluid, 1), new FluidStack(moltenArditeFluid, 1),
new FluidStack(moltenManyullynFluid, 1), new FluidStack(moltenBronzeFluid, 1), new FluidStack(moltenAlumiteFluid, 1), new FluidStack(moltenObsidianFluid, 1),
new FluidStack(moltenSteelFluid, 1) };
int[] liquidDamage = new int[] { 2, 13, 10, 11, 12, 14, 15, 6, 16 };
int fluidAmount = 0;
Fluid fs = null;
for (int iter = 0; iter < patternOutputs.length; iter++)
{
if (patternOutputs[iter] != null)
{
ItemStack cast = new ItemStack(metalPattern, 1, iter + 1);
tableCasting.addCastingRecipe(cast, new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue), new ItemStack(patternOutputs[iter], 1, Short.MAX_VALUE), false, 50);
tableCasting.addCastingRecipe(cast, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2), new ItemStack(patternOutputs[iter], 1, Short.MAX_VALUE), false, 50);
for (int iterTwo = 0; iterTwo < liquids.length; iterTwo++)
{
fs = liquids[iterTwo].getFluid();
fluidAmount = ((IPattern) metalPattern).getPatternCost(cast) * TConstruct.ingotLiquidValue / 2;
ItemStack metalCast = new ItemStack(patternOutputs[iter], 1, liquidDamage[iterTwo]);
tableCasting.addCastingRecipe(metalCast, new FluidStack(fs, fluidAmount), cast, 50);
Smeltery.addMelting(FluidType.getFluidType(fs), metalCast, 0, fluidAmount);
}
}
}
ItemStack[] ingotShapes = { new ItemStack(Item.brick), new ItemStack(Item.netherrackBrick), new ItemStack(materials, 1, 2) };
for (int i = 0; i < ingotShapes.length; i++)
{
tableCasting.addCastingRecipe(ingotcast, new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue), ingotShapes[i], false, 50);
tableCasting.addCastingRecipe(ingotcast, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2), ingotShapes[i], false, 50);
}
ItemStack fullguardCast = new ItemStack(metalPattern, 1, 22);
tableCasting.addCastingRecipe(fullguardCast, new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue), new ItemStack(fullGuard, 1, Short.MAX_VALUE), false, 50);
tableCasting.addCastingRecipe(fullguardCast, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2), new ItemStack(fullGuard, 1, Short.MAX_VALUE), false, 50);
// Golden Food Stuff
FluidStack goldAmount = null;
if (PHConstruct.goldAppleRecipe)
{
goldAmount = new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 8);
}
else
{
goldAmount = new FluidStack(moltenGoldFluid, TConstruct.nuggetLiquidValue * 8);
}
tableCasting.addCastingRecipe(new ItemStack(Item.appleGold, 1), goldAmount, new ItemStack(Item.appleRed), true, 50);
tableCasting.addCastingRecipe(new ItemStack(Item.goldenCarrot, 1), goldAmount, new ItemStack(Item.carrot), true, 50);
tableCasting.addCastingRecipe(new ItemStack(Item.speckledMelon, 1), goldAmount, new ItemStack(Item.melon), true, 50);
tableCasting.addCastingRecipe(new ItemStack(goldHead), goldAmount, new ItemStack(Item.skull, 1, 3), true, 50);
}
private void addRecipesForBasinCasting ()
{
LiquidCasting basinCasting = TConstructRegistry.getBasinCasting();
// Block Casting
basinCasting.addCastingRecipe(new ItemStack(Block.blockIron), new FluidStack(moltenIronFluid, TConstruct.blockLiquidValue), null, true, 100); //Iron
basinCasting.addCastingRecipe(new ItemStack(Block.blockGold), new FluidStack(moltenGoldFluid, TConstruct.blockLiquidValue), null, true, 100); //gold
basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 3), new FluidStack(moltenCopperFluid, TConstruct.blockLiquidValue), null, true, 100); //copper
basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 5), new FluidStack(moltenTinFluid, TConstruct.blockLiquidValue), null, true, 100); //tin
basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 6), new FluidStack(moltenAluminumFluid, TConstruct.blockLiquidValue), null, true, 100); //aluminum
basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 0), new FluidStack(moltenCobaltFluid, TConstruct.blockLiquidValue), null, true, 100); //cobalt
basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 1), new FluidStack(moltenArditeFluid, TConstruct.blockLiquidValue), null, true, 100); //ardite
basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 4), new FluidStack(moltenBronzeFluid, TConstruct.blockLiquidValue), null, true, 100); //bronze
basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 7), new FluidStack(moltenAlubrassFluid, TConstruct.blockLiquidValue), null, true, 100); //albrass
basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 2), new FluidStack(moltenManyullynFluid, TConstruct.blockLiquidValue), null, true, 100); //manyullyn
basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 8), new FluidStack(moltenAlumiteFluid, TConstruct.blockLiquidValue), null, true, 100); //alumite
basinCasting.addCastingRecipe(new ItemStack(Block.obsidian), new FluidStack(moltenObsidianFluid, TConstruct.oreLiquidValue), null, true, 100);// obsidian
basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 9), new FluidStack(moltenSteelFluid, TConstruct.blockLiquidValue), null, true, 100); //steel
basinCasting.addCastingRecipe(new ItemStack(clearGlass, 1, 0), new FluidStack(moltenGlassFluid, FluidContainerRegistry.BUCKET_VOLUME), null, true, 100); //glass
basinCasting.addCastingRecipe(new ItemStack(smeltery, 1, 4), new FluidStack(moltenStoneFluid, TConstruct.ingotLiquidValue), null, true, 100); //seared stone
basinCasting.addCastingRecipe(new ItemStack(smeltery, 1, 5), new FluidStack(moltenStoneFluid, TConstruct.chunkLiquidValue), new ItemStack(Block.cobblestone), true, 100);
basinCasting.addCastingRecipe(new ItemStack(speedBlock, 1, 0), new FluidStack(moltenTinFluid, TConstruct.nuggetLiquidValue), new ItemStack(Block.gravel), true, 100); //brownstone
basinCasting.addCastingRecipe(new ItemStack(Block.whiteStone), new FluidStack(moltenEnderFluid, TConstruct.chunkLiquidValue), new ItemStack(Block.obsidian), true, 100); //endstone
basinCasting.addCastingRecipe(new ItemStack(metalBlock.blockID, 1, 10), new FluidStack(moltenEnderFluid, TConstruct.blockLiquidValue), null, true, 100); //ender
// basinCasting.addCastingRecipe(new ItemStack(slimeGel, 1, 0), new FluidStack(blueSlimeFluid, FluidContainerRegistry.BUCKET_VOLUME), null, true, 100);
//Armor casts
FluidRenderProperties frp = new FluidRenderProperties(Applications.BASIN.minHeight, 0.65F, Applications.BASIN);
FluidStack aluFlu = new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue * 10);
FluidStack gloFlu = new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 10);
ItemStack[] armor = { new ItemStack(helmetWood), new ItemStack(chestplateWood), new ItemStack(leggingsWood), new ItemStack(bootsWood) };
for (int sc = 0; sc < armor.length; sc++)
{
basinCasting.addCastingRecipe(new ItemStack(armorPattern, 1, sc), aluFlu, armor[sc], 50, frp);
basinCasting.addCastingRecipe(new ItemStack(armorPattern, 1, sc), gloFlu, armor[sc], 50, frp);
}
}
private void addRecipesForSmeltery ()
{
//Alloys Smelting
if (PHConstruct.harderBronze)
Smeltery.addAlloyMixing(new FluidStack(moltenBronzeFluid, 16), new FluidStack(moltenCopperFluid, 24), new FluidStack(moltenTinFluid, 8)); //Bronze
else
Smeltery.addAlloyMixing(new FluidStack(moltenBronzeFluid, 24), new FluidStack(moltenCopperFluid, 24), new FluidStack(moltenTinFluid, 8)); //Bronze
Smeltery.addAlloyMixing(new FluidStack(moltenAlubrassFluid, 32), new FluidStack(moltenAluminumFluid, 24), new FluidStack(moltenCopperFluid, 8)); //Aluminum Brass
Smeltery.addAlloyMixing(new FluidStack(moltenManyullynFluid, 16), new FluidStack(moltenCobaltFluid, 32), new FluidStack(moltenArditeFluid, 32)); //Manyullyn
Smeltery.addAlloyMixing(new FluidStack(moltenAlumiteFluid, 48), new FluidStack(moltenAluminumFluid, 80), new FluidStack(moltenIronFluid, 32), new FluidStack(moltenObsidianFluid, 32)); //Alumite
// Stone parts
for (int sc = 0; sc < patternOutputs.length; sc++)
{
if (patternOutputs[sc] != null)
{
Smeltery.addMelting(FluidType.Stone, new ItemStack(patternOutputs[sc], 1, 1), 1, (8 * ((IPattern) woodPattern).getPatternCost(new ItemStack(woodPattern, 1, sc + 1))) / 2);
}
}
// Chunks
Smeltery.addMelting(FluidType.Stone, new ItemStack(toolShard, 1, 1), 0, 4);
Smeltery.addMelting(FluidType.Iron, new ItemStack(toolShard, 1, 2), 0, TConstruct.chunkLiquidValue);
Smeltery.addMelting(FluidType.Obsidian, new ItemStack(toolShard, 1, 6), 0, TConstruct.chunkLiquidValue);
Smeltery.addMelting(FluidType.Cobalt, new ItemStack(toolShard, 1, 10), 0, TConstruct.chunkLiquidValue);
Smeltery.addMelting(FluidType.Ardite, new ItemStack(toolShard, 1, 11), 0, TConstruct.chunkLiquidValue);
Smeltery.addMelting(FluidType.Manyullyn, new ItemStack(toolShard, 1, 12), 0, TConstruct.chunkLiquidValue);
Smeltery.addMelting(FluidType.Copper, new ItemStack(toolShard, 1, 13), 0, TConstruct.chunkLiquidValue);
Smeltery.addMelting(FluidType.Bronze, new ItemStack(toolShard, 1, 14), 0, TConstruct.chunkLiquidValue);
Smeltery.addMelting(FluidType.Alumite, new ItemStack(toolShard, 1, 15), 0, TConstruct.chunkLiquidValue);
Smeltery.addMelting(FluidType.Steel, new ItemStack(toolShard, 1, 16), 0, TConstruct.chunkLiquidValue);
// Items
Smeltery.addMelting(FluidType.AluminumBrass, new ItemStack(blankPattern, 4, 1), -50, TConstruct.ingotLiquidValue);
Smeltery.addMelting(FluidType.Gold, new ItemStack(blankPattern, 4, 2), -50, TConstruct.ingotLiquidValue);
Smeltery.addMelting(FluidType.Ender, new ItemStack(Item.enderPearl, 4), 0, 250);
Smeltery.addMelting(metalBlock, 10, 50, new FluidStack(moltenEnderFluid, 1000));
Smeltery.addMelting(FluidType.Water, new ItemStack(Item.snowball, 1, 0), 0, 125);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.flintAndSteel, 1, 0), 0, TConstruct.ingotLiquidValue);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.compass, 1, 0), 0, TConstruct.ingotLiquidValue * 4);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.bucketEmpty), 0, TConstruct.ingotLiquidValue * 3);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.minecartEmpty), 0, TConstruct.ingotLiquidValue * 5);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.minecartCrate), 0, TConstruct.ingotLiquidValue * 5);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.minecartPowered), 0, TConstruct.ingotLiquidValue * 5);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.minecartHopper), 50, TConstruct.ingotLiquidValue * 10);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.doorIron), 0, TConstruct.ingotLiquidValue * 6);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.cauldron), 0, TConstruct.ingotLiquidValue * 7);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.shears), 0, TConstruct.oreLiquidValue);
// Smeltery.addMelting(FluidType.Slime, new ItemStack(slimeGel, 1, 0), 0, TConstruct.ingotLiquidValue * 4);
// Smeltery.addMelting(FluidType.Slime, new ItemStack(strangeFood, 1, 0), 0, TConstruct.ingotLiquidValue);
// Smeltery.addMelting(FluidType.Slime, new ItemStack(multiBrick, 1, 11), 0, TConstruct.ingotLiquidValue);
// Smeltery.addMelting(FluidType.Slime, new ItemStack(multiBrickFancy, 1, 11), 0, TConstruct.ingotLiquidValue);
//Blocks melt at themselves!
//Ore
Smeltery.addMelting(Block.oreIron, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 2));
Smeltery.addMelting(Block.oreGold, 0, 400, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2));
Smeltery.addMelting(oreGravel, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 2));
Smeltery.addMelting(oreGravel, 1, 400, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2));
//Blocks
Smeltery.addMelting(Block.blockIron, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 9));
Smeltery.addMelting(Block.blockGold, 0, 400, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 9));
Smeltery.addMelting(Block.obsidian, 0, 800, new FluidStack(moltenObsidianFluid, TConstruct.ingotLiquidValue * 2));
Smeltery.addMelting(Block.ice, 0, 75, new FluidStack(FluidRegistry.getFluid("water"), 1000));
Smeltery.addMelting(Block.blockSnow, 0, 75, new FluidStack(FluidRegistry.getFluid("water"), 500));
Smeltery.addMelting(Block.snow, 0, 75, new FluidStack(FluidRegistry.getFluid("water"), 250));
Smeltery.addMelting(Block.sand, 0, 625, new FluidStack(moltenGlassFluid, FluidContainerRegistry.BUCKET_VOLUME));
Smeltery.addMelting(Block.glass, 0, 625, new FluidStack(moltenGlassFluid, FluidContainerRegistry.BUCKET_VOLUME));
Smeltery.addMelting(Block.thinGlass, 0, 625, new FluidStack(moltenGlassFluid, 250));
Smeltery.addMelting(Block.stone, 0, 800, new FluidStack(moltenStoneFluid, TConstruct.ingotLiquidValue / 18));
Smeltery.addMelting(Block.cobblestone, 0, 800, new FluidStack(moltenStoneFluid, TConstruct.ingotLiquidValue / 18));
Smeltery.addMelting(clearGlass, 0, 500, new FluidStack(moltenGlassFluid, 1000));
Smeltery.addMelting(glassPane, 0, 350, new FluidStack(moltenGlassFluid, 250));
for (int i = 0; i < 16; i++)
{
Smeltery.addMelting(stainedGlassClear, i, 500, new FluidStack(moltenGlassFluid, 1000));
Smeltery.addMelting(stainedGlassClearPane, i, 350, new FluidStack(moltenGlassFluid, 250));
}
//Bricks
Smeltery.addMelting(multiBrick, 4, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue));
Smeltery.addMelting(multiBrickFancy, 4, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue));
Smeltery.addMelting(multiBrick, 5, 400, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue));
Smeltery.addMelting(multiBrickFancy, 5, 400, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue));
Smeltery.addMelting(multiBrick, 0, 800, new FluidStack(moltenObsidianFluid, TConstruct.ingotLiquidValue * 2));
Smeltery.addMelting(multiBrickFancy, 0, 800, new FluidStack(moltenObsidianFluid, TConstruct.ingotLiquidValue * 2));
//Vanilla blocks
Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.fenceIron), 0, TConstruct.ingotLiquidValue * 6 / 16);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.pressurePlateIron), 0, TConstruct.oreLiquidValue);
Smeltery.addMelting(FluidType.Gold, new ItemStack(Block.pressurePlateGold, 4), 0, TConstruct.oreLiquidValue);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.rail), 0, TConstruct.ingotLiquidValue * 6 / 16);
Smeltery.addMelting(FluidType.Gold, new ItemStack(Block.railPowered), 0, TConstruct.ingotLiquidValue);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.railDetector), 0, TConstruct.ingotLiquidValue);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.railActivator), 0, TConstruct.ingotLiquidValue);
Smeltery.addMelting(FluidType.Obsidian, new ItemStack(Block.enchantmentTable), 0, TConstruct.ingotLiquidValue * 4);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.cauldron), 0, TConstruct.ingotLiquidValue * 7);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.anvil, 1, 0), 200, TConstruct.ingotLiquidValue * 31);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.anvil, 1, 1), 200, TConstruct.ingotLiquidValue * 31);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.anvil, 1, 2), 200, TConstruct.ingotLiquidValue * 31);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.hopperBlock), 0, TConstruct.ingotLiquidValue * 5);
//Vanilla Armor
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.helmetIron, 1, 0), 50, TConstruct.ingotLiquidValue * 5);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.plateIron, 1, 0), 50, TConstruct.ingotLiquidValue * 8);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.legsIron, 1, 0), 50, TConstruct.ingotLiquidValue * 7);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.bootsIron, 1, 0), 50, TConstruct.ingotLiquidValue * 4);
Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.helmetGold, 1, 0), 50, TConstruct.ingotLiquidValue * 5);
Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.plateGold, 1, 0), 50, TConstruct.ingotLiquidValue * 8);
Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.legsGold, 1, 0), 50, TConstruct.ingotLiquidValue * 7);
Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.bootsGold, 1, 0), 50, TConstruct.ingotLiquidValue * 4);
Smeltery.addMelting(FluidType.Steel, new ItemStack(Item.helmetChain, 1, 0), 25, TConstruct.ingotLiquidValue);
Smeltery.addMelting(FluidType.Steel, new ItemStack(Item.plateChain, 1, 0), 50, TConstruct.oreLiquidValue);
Smeltery.addMelting(FluidType.Steel, new ItemStack(Item.legsChain, 1, 0), 50, TConstruct.oreLiquidValue);
Smeltery.addMelting(FluidType.Steel, new ItemStack(Item.bootsChain, 1, 0), 25, TConstruct.ingotLiquidValue);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.horseArmorIron, 1), 100, TConstruct.ingotLiquidValue * 8);
Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.horseArmorGold, 1), 100, TConstruct.ingotLiquidValue * 8);
//Vanilla tools
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.hoeIron, 1, 0), 0, TConstruct.oreLiquidValue);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.swordIron, 1, 0), 0, TConstruct.oreLiquidValue);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.shovelIron, 1, 0), 0, TConstruct.ingotLiquidValue);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.pickaxeIron, 1, 0), 0, TConstruct.ingotLiquidValue * 3);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.axeIron, 1, 0), 0, TConstruct.ingotLiquidValue * 3);
Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.hoeGold, 1, 0), 0, TConstruct.oreLiquidValue);
Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.swordGold, 1, 0), 0, TConstruct.oreLiquidValue);
Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.shovelGold, 1, 0), 0, TConstruct.ingotLiquidValue);
Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.pickaxeGold, 1, 0), 0, TConstruct.ingotLiquidValue * 3);
Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.axeGold, 1, 0), 0, TConstruct.ingotLiquidValue * 3);
}
private void addRecipesForDryingRack ()
{
//Drying rack
DryingRackRecipes.addDryingRecipe(Item.beefRaw, 20 * 60 * 5, new ItemStack(jerky, 1, 0));
DryingRackRecipes.addDryingRecipe(Item.chickenRaw, 20 * 60 * 5, new ItemStack(jerky, 1, 1));
DryingRackRecipes.addDryingRecipe(Item.porkRaw, 20 * 60 * 5, new ItemStack(jerky, 1, 2));
//DryingRackRecipes.addDryingRecipe(Item.muttonRaw, 20 * 60 * 5, new ItemStack(jerky, 1, 3));
DryingRackRecipes.addDryingRecipe(Item.fishRaw, 20 * 60 * 5, new ItemStack(jerky, 1, 4));
DryingRackRecipes.addDryingRecipe(Item.rottenFlesh, 20 * 60 * 5, new ItemStack(jerky, 1, 5));
//DryingRackRecipes.addDryingRecipe(new ItemStack(jerky, 1, 5), 20 * 60 * 10, Item.leather);
}
private void addRecipesForChisel ()
{
/* Detailing */
Detailing chiseling = TConstructRegistry.getChiselDetailing();
chiseling.addDetailing(Block.stone, 0, Block.stoneBrick, 0, chisel);
chiseling.addDetailing(speedBlock, 0, speedBlock, 1, chisel);
chiseling.addDetailing(speedBlock, 2, speedBlock, 3, chisel);
chiseling.addDetailing(speedBlock, 3, speedBlock, 4, chisel);
chiseling.addDetailing(speedBlock, 4, speedBlock, 5, chisel);
chiseling.addDetailing(speedBlock, 5, speedBlock, 6, chisel);
chiseling.addDetailing(Block.obsidian, 0, multiBrick, 0, chisel);
chiseling.addDetailing(Block.sandStone, 0, Block.sandStone, 2, chisel);
chiseling.addDetailing(Block.sandStone, 2, Block.sandStone, 1, chisel);
chiseling.addDetailing(Block.sandStone, 1, multiBrick, 1, chisel);
//chiseling.addDetailing(Block.netherrack, 0, multiBrick, 2, chisel);
//chiseling.addDetailing(Block.stone_refined, 0, multiBrick, 3, chisel);
chiseling.addDetailing(Item.ingotIron, 0, multiBrick, 4, chisel);
chiseling.addDetailing(Item.ingotGold, 0, multiBrick, 5, chisel);
chiseling.addDetailing(Item.dyePowder, 4, multiBrick, 6, chisel);
chiseling.addDetailing(Item.diamond, 0, multiBrick, 7, chisel);
chiseling.addDetailing(Item.redstone, 0, multiBrick, 8, chisel);
chiseling.addDetailing(Item.bone, 0, multiBrick, 9, chisel);
chiseling.addDetailing(Item.slimeBall, 0, multiBrick, 10, chisel);
chiseling.addDetailing(strangeFood, 0, multiBrick, 11, chisel);
chiseling.addDetailing(Block.whiteStone, 0, multiBrick, 12, chisel);
chiseling.addDetailing(materials, 18, multiBrick, 13, chisel);
// adding multiBrick / multiBrickFanxy meta 0-13 to list
for (int sc = 0; sc < 14; sc++)
{
chiseling.addDetailing(multiBrick, sc, multiBrickFancy, sc, chisel);
}
chiseling.addDetailing(Block.stoneBrick, 0, multiBrickFancy, 15, chisel);
chiseling.addDetailing(multiBrickFancy, 15, multiBrickFancy, 14, chisel);
chiseling.addDetailing(multiBrickFancy, 14, Block.stoneBrick, 3, chisel);
/*chiseling.addDetailing(multiBrick, 14, multiBrickFancy, 14, chisel);
chiseling.addDetailing(multiBrick, 15, multiBrickFancy, 15, chisel);*/
chiseling.addDetailing(smeltery, 4, smeltery, 6, chisel);
chiseling.addDetailing(smeltery, 6, smeltery, 11, chisel);
chiseling.addDetailing(smeltery, 11, smeltery, 2, chisel);
chiseling.addDetailing(smeltery, 2, smeltery, 8, chisel);
chiseling.addDetailing(smeltery, 8, smeltery, 9, chisel);
chiseling.addDetailing(smeltery, 9, smeltery, 10, chisel);
}
void setupToolTabs ()
{
TConstructRegistry.materialTab.init(new ItemStack(titleIcon, 1, 255));
TConstructRegistry.blockTab.init(new ItemStack(toolStationWood));
ItemStack tool = new ItemStack(longsword, 1, 0);
NBTTagCompound compound = new NBTTagCompound();
compound.setCompoundTag("InfiTool", new NBTTagCompound());
compound.getCompoundTag("InfiTool").setInteger("RenderHead", 2);
compound.getCompoundTag("InfiTool").setInteger("RenderHandle", 0);
compound.getCompoundTag("InfiTool").setInteger("RenderAccessory", 10);
tool.setTagCompound(compound);
//TConstruct.
TConstructRegistry.toolTab.init(tool);
}
public void addLoot ()
{
//Item, min, max, weight
ChestGenHooks.getInfo(ChestGenHooks.DUNGEON_CHEST).addItem(new WeightedRandomChestContent(new ItemStack(heartCanister, 1, 1), 1, 1, 5));
ChestGenHooks.getInfo(ChestGenHooks.PYRAMID_DESERT_CHEST).addItem(new WeightedRandomChestContent(new ItemStack(heartCanister, 1, 1), 1, 1, 10));
ChestGenHooks.getInfo(ChestGenHooks.PYRAMID_JUNGLE_CHEST).addItem(new WeightedRandomChestContent(new ItemStack(heartCanister, 1, 1), 1, 1, 10));
tinkerHouseChest = new ChestGenHooks("TinkerHouse", new WeightedRandomChestContent[0], 3, 27);
tinkerHouseChest.addItem(new WeightedRandomChestContent(new ItemStack(heartCanister, 1, 1), 1, 1, 1));
int[] validTypes = { 0, 1, 2, 3, 4, 5, 6, 8, 9, 13, 14, 17 };
Item[] partTypes = { pickaxeHead, shovelHead, hatchetHead, binding, swordBlade, wideGuard, handGuard, crossbar, knifeBlade, frypanHead, signHead, chiselHead };
for (int partIter = 0; partIter < partTypes.length; partIter++)
{
for (int typeIter = 0; typeIter < validTypes.length; typeIter++)
{
tinkerHouseChest.addItem(new WeightedRandomChestContent(new ItemStack(partTypes[partIter], 1, validTypes[typeIter]), 1, 1, 15));
}
}
tinkerHousePatterns = new ChestGenHooks("TinkerPatterns", new WeightedRandomChestContent[0], 5, 30);
for (int i = 0; i < 13; i++)
{
tinkerHousePatterns.addItem(new WeightedRandomChestContent(new ItemStack(woodPattern, 1, i + 1), 1, 3, 20));
}
tinkerHousePatterns.addItem(new WeightedRandomChestContent(new ItemStack(woodPattern, 1, 22), 1, 3, 40));
}
public static String[] liquidNames;
public void oreRegistry ()
{
OreDictionary.registerOre("oreCobalt", new ItemStack(oreSlag, 1, 1));
OreDictionary.registerOre("oreArdite", new ItemStack(oreSlag, 1, 2));
OreDictionary.registerOre("oreCopper", new ItemStack(oreSlag, 1, 3));
OreDictionary.registerOre("oreTin", new ItemStack(oreSlag, 1, 4));
OreDictionary.registerOre("oreNaturalAluminum", new ItemStack(oreSlag, 1, 5));
OreDictionary.registerOre("oreIron", new ItemStack(oreGravel, 1, 0));
OreDictionary.registerOre("oreGold", new ItemStack(oreGravel, 1, 1));
OreDictionary.registerOre("oreCobalt", new ItemStack(oreGravel, 1, 5));
OreDictionary.registerOre("oreCopper", new ItemStack(oreGravel, 1, 2));
OreDictionary.registerOre("oreTin", new ItemStack(oreGravel, 1, 3));
OreDictionary.registerOre("oreNaturalAluminum", new ItemStack(oreGravel, 1, 4));
OreDictionary.registerOre("ingotCobalt", new ItemStack(materials, 1, 3));
OreDictionary.registerOre("ingotArdite", new ItemStack(materials, 1, 4));
OreDictionary.registerOre("ingotManyullyn", new ItemStack(materials, 1, 5));
OreDictionary.registerOre("ingotCopper", new ItemStack(materials, 1, 9));
OreDictionary.registerOre("ingotTin", new ItemStack(materials, 1, 10));
OreDictionary.registerOre("ingotNaturalAluminum", new ItemStack(materials, 1, 11));
OreDictionary.registerOre("naturalAluminum", new ItemStack(materials, 1, 12));
OreDictionary.registerOre("ingotBronze", new ItemStack(materials, 1, 13));
OreDictionary.registerOre("ingotAluminumBrass", new ItemStack(materials, 1, 14));
OreDictionary.registerOre("ingotAlumite", new ItemStack(materials, 1, 15));
OreDictionary.registerOre("ingotSteel", new ItemStack(materials, 1, 16));
ensureOreIsRegistered("ingotIron", new ItemStack(Item.ingotIron));
ensureOreIsRegistered("ingotGold", new ItemStack(Item.ingotGold));
OreDictionary.registerOre("ingotObsidian", new ItemStack(materials, 1, 18));
OreDictionary.registerOre("blockCobalt", new ItemStack(metalBlock, 1, 0));
OreDictionary.registerOre("blockArdite", new ItemStack(metalBlock, 1, 1));
OreDictionary.registerOre("blockManyullyn", new ItemStack(metalBlock, 1, 2));
OreDictionary.registerOre("blockCopper", new ItemStack(metalBlock, 1, 3));
OreDictionary.registerOre("blockBronze", new ItemStack(metalBlock, 1, 4));
OreDictionary.registerOre("blockTin", new ItemStack(metalBlock, 1, 5));
OreDictionary.registerOre("blockNaturalAluminum", new ItemStack(metalBlock, 1, 6));
OreDictionary.registerOre("blockAluminumBrass", new ItemStack(metalBlock, 1, 7));
OreDictionary.registerOre("blockAlumite", new ItemStack(metalBlock, 1, 8));
OreDictionary.registerOre("blockSteel", new ItemStack(metalBlock, 1, 9));
ensureOreIsRegistered("blockIron", new ItemStack(Block.blockIron));
ensureOreIsRegistered("blockGold", new ItemStack(Block.blockGold));
OreDictionary.registerOre("nuggetIron", new ItemStack(materials, 1, 19));
OreDictionary.registerOre("nuggetIron", new ItemStack(oreBerries, 1, 0));
OreDictionary.registerOre("nuggetCopper", new ItemStack(materials, 1, 20));
OreDictionary.registerOre("nuggetCopper", new ItemStack(oreBerries, 1, 2));
OreDictionary.registerOre("nuggetTin", new ItemStack(materials, 1, 21));
OreDictionary.registerOre("nuggetTin", new ItemStack(oreBerries, 1, 3));
OreDictionary.registerOre("nuggetNaturalAluminum", new ItemStack(materials, 1, 22));
OreDictionary.registerOre("nuggetNaturalAluminum", new ItemStack(oreBerries, 1, 4));
OreDictionary.registerOre("nuggetAluminumBrass", new ItemStack(materials, 1, 24));
OreDictionary.registerOre("nuggetObsidian", new ItemStack(materials, 1, 27));
OreDictionary.registerOre("nuggetCobalt", new ItemStack(materials, 1, 28));
OreDictionary.registerOre("nuggetArdite", new ItemStack(materials, 1, 29));
OreDictionary.registerOre("nuggetManyullyn", new ItemStack(materials, 1, 30));
OreDictionary.registerOre("nuggetBronze", new ItemStack(materials, 1, 31));
OreDictionary.registerOre("nuggetAlumite", new ItemStack(materials, 1, 32));
OreDictionary.registerOre("nuggetSteel", new ItemStack(materials, 1, 33));
OreDictionary.registerOre("nuggetGold", new ItemStack(oreBerries, 1, 1));
ensureOreIsRegistered("nuggetGold", new ItemStack(Item.goldNugget));
OreDictionary.registerOre("slabCloth", new ItemStack(woolSlab1, 1, Short.MAX_VALUE));
OreDictionary.registerOre("slabCloth", new ItemStack(woolSlab2, 1, Short.MAX_VALUE));
ensureOreIsRegistered("stoneMossy", new ItemStack(Block.stoneBrick, 1, 1));
ensureOreIsRegistered("stoneMossy", new ItemStack(Block.cobblestoneMossy));
ensureOreIsRegistered("crafterWood", new ItemStack(Block.workbench, 1));
String[] matNames = { "wood", "stone", "iron", "flint", "cactus", "bone", "obsidian", "netherrack", "slime", "paper", "cobalt", "ardite", "manyullyn", "copper", "bronze", "alumite", "steel",
"blueslime" };
for (int i = 0; i < matNames.length; i++)
OreDictionary.registerOre(matNames[i] + "Rod", new ItemStack(toolRod, 1, i));
OreDictionary.registerOre("thaumiumRod", new ItemStack(toolRod, 1, 31));
String[] glassTypes = { "glassBlack", "glassRed", "glassGreen", "glassBrown", "glassBlue", "glassPurple", "glassCyan", "glassLightGray", "glassGray", "glassPink", "glassLime", "glassYellow",
"glassLightBlue", "glassMagenta", "glassOrange", "glassWhite" };
for (int i = 0; i < 16; i++)
{
OreDictionary.registerOre(glassTypes[15 - i], new ItemStack(stainedGlassClear, 1, i));
}
BlockDispenser.dispenseBehaviorRegistry.putObject(titleIcon, new TDispenserBehaviorSpawnEgg());
BlockDispenser.dispenseBehaviorRegistry.putObject(arrow, new TDispenserBehaviorArrow());
//Vanilla stuff
OreDictionary.registerOre("slimeball", new ItemStack(Item.slimeBall));
OreDictionary.registerOre("slimeball", new ItemStack(strangeFood, 1, 0));
OreDictionary.registerOre("glass", new ItemStack(clearGlass));
OreDictionary.registerOre("glass", new ItemStack(Block.glass));
RecipeRemover.removeShapedRecipe(new ItemStack(Block.pistonStickyBase));
RecipeRemover.removeShapedRecipe(new ItemStack(Item.magmaCream));
RecipeRemover.removeShapedRecipe(new ItemStack(Item.leash));
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(Block.pistonStickyBase), "slimeball", Block.pistonBase));
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(Item.magmaCream), "slimeball", Item.blazePowder));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(Item.leash, 2), "ss ", "sS ", " s", 's', Item.silk, 'S', "slimeball"));
}
private void ensureOreIsRegistered (String oreName, ItemStack is)
{
int oreId = OreDictionary.getOreID(is);
if (oreId == -1)
{
OreDictionary.registerOre(oreName, is);
}
}
public static boolean thaumcraftAvailable;
public void intermodCommunication ()
{
if (Loader.isModLoaded("Thaumcraft"))
{
FMLInterModComms.sendMessage("Thaumcraft", "harvestClickableCrop", new ItemStack(oreBerry, 1, 12));
FMLInterModComms.sendMessage("Thaumcraft", "harvestClickableCrop", new ItemStack(oreBerry, 1, 13));
FMLInterModComms.sendMessage("Thaumcraft", "harvestClickableCrop", new ItemStack(oreBerry, 1, 14));
FMLInterModComms.sendMessage("Thaumcraft", "harvestClickableCrop", new ItemStack(oreBerry, 1, 15));
FMLInterModComms.sendMessage("Thaumcraft", "harvestClickableCrop", new ItemStack(oreBerrySecond, 1, 12));
FMLInterModComms.sendMessage("Thaumcraft", "harvestClickableCrop", new ItemStack(oreBerrySecond, 1, 13));
}
if (Loader.isModLoaded("Mystcraft"))
{
MystImcHandler.blacklistFluids();
}
if (Loader.isModLoaded("BuildCraft|Transport"))
{
BCImcHandler.registerFacades();
}
/* FORESTRY
* Edit these strings to change what items are added to the backpacks
* Format info: "[backpack ID]@[item ID].[metadata or *]:[next item]" and so on
* Avaliable backpack IDs: forester, miner, digger, hunter, adventurer, builder
* May add more backpack items later - Spyboticsguy
*/
if (Loader.isModLoaded("Forestry"))
{
String builderItems = "builder@" + String.valueOf(stoneTorch.blockID) + ":*";
FMLInterModComms.sendMessage("Forestry", "add-backpack-items", builderItems);
}
if (!Loader.isModLoaded("AppliedEnergistics"))
{
AEImcHandler.registerForSpatialIO();
}
}
private static boolean initRecipes;
public static void modRecipes ()
{
if (!initRecipes)
{
initRecipes = true;
if (PHConstruct.removeVanillaToolRecipes)
{
RecipeRemover.removeAnyRecipe(new ItemStack(Item.pickaxeWood));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.axeWood));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.shovelWood));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.hoeWood));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.swordWood));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.pickaxeStone));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.axeStone));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.shovelStone));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.hoeStone));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.swordStone));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.pickaxeIron));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.axeIron));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.shovelIron));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.hoeIron));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.swordIron));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.pickaxeDiamond));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.axeDiamond));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.shovelDiamond));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.hoeDiamond));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.swordDiamond));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.pickaxeGold));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.axeGold));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.shovelGold));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.hoeGold));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.swordGold));
}
}
}
public static void addShapedRecipeFirst (List recipeList, ItemStack itemstack, Object... objArray)
{
String var3 = "";
int var4 = 0;
int var5 = 0;
int var6 = 0;
if (objArray[var4] instanceof String[])
{
String[] var7 = ((String[]) objArray[var4++]);
for (int var8 = 0; var8 < var7.length; ++var8)
{
String var9 = var7[var8];
++var6;
var5 = var9.length();
var3 = var3 + var9;
}
}
else
{
while (objArray[var4] instanceof String)
{
String var11 = (String) objArray[var4++];
++var6;
var5 = var11.length();
var3 = var3 + var11;
}
}
HashMap var12;
for (var12 = new HashMap(); var4 < objArray.length; var4 += 2)
{
Character var13 = (Character) objArray[var4];
ItemStack var14 = null;
if (objArray[var4 + 1] instanceof Item)
{
var14 = new ItemStack((Item) objArray[var4 + 1]);
}
else if (objArray[var4 + 1] instanceof Block)
{
var14 = new ItemStack((Block) objArray[var4 + 1], 1, Short.MAX_VALUE);
}
else if (objArray[var4 + 1] instanceof ItemStack)
{
var14 = (ItemStack) objArray[var4 + 1];
}
var12.put(var13, var14);
}
ItemStack[] var15 = new ItemStack[var5 * var6];
for (int var16 = 0; var16 < var5 * var6; ++var16)
{
char var10 = var3.charAt(var16);
if (var12.containsKey(Character.valueOf(var10)))
{
var15[var16] = ((ItemStack) var12.get(Character.valueOf(var10))).copy();
}
else
{
var15[var16] = null;
}
}
ShapedRecipes var17 = new ShapedRecipes(var5, var6, var15, itemstack);
recipeList.add(0, var17);
}
public void modIntegration ()
{
ItemStack ironpick = ToolBuilder.instance.buildTool(new ItemStack(TContent.pickaxeHead, 1, 6), new ItemStack(TContent.toolRod, 1, 2), new ItemStack(TContent.binding, 1, 6), "");
/* IC2 */
//ItemStack reBattery = ic2.api.item.Items.getItem("reBattery");
Object reBattery = getStaticItem("reBattery", "ic2.core.Ic2Items");
if (reBattery != null)
{
modE.batteries.add((ItemStack) reBattery);
}
//ItemStack chargedReBattery = ic2.api.item.Items.getItem("chargedReBattery");
Object chargedReBattery = getStaticItem("chargedReBattery", "ic2.core.Ic2Items");
if (chargedReBattery != null)
{
modE.batteries.add((ItemStack) chargedReBattery);
}
//ItemStack electronicCircuit = ic2.api.item.Items.getItem("electronicCircuit");
Object electronicCircuit = getStaticItem("electronicCircuit", "ic2.core.Ic2Items");
if (electronicCircuit != null)
modE.circuits.add((ItemStack) electronicCircuit);
if (chargedReBattery != null && electronicCircuit != null)
TConstructClientRegistry.registerManualModifier("electricmod", ironpick.copy(), (ItemStack) chargedReBattery, (ItemStack) electronicCircuit);
/* Thaumcraft */
Object obj = getStaticItem("itemResource", "thaumcraft.common.config.ConfigItems");
if (obj != null)
{
TConstruct.logger.info("Thaumcraft detected. Adding thaumium tools.");
thaumcraftAvailable = true;
TConstructClientRegistry.addMaterialRenderMapping(31, "tinker", "thaumium", true);
TConstructRegistry.addToolMaterial(31, "Thaumium", 3, 400, 700, 2, 1.3F, 0, 0f, "\u00A75", "Thaumic");
PatternBuilder.instance.registerFullMaterial(new ItemStack((Item) obj, 1, 2), 2, "Thaumium", new ItemStack(toolShard, 1, 31), new ItemStack(toolRod, 1, 31), 31);
for (int meta = 0; meta < patternOutputs.length; meta++)
{
if (patternOutputs[meta] != null)
TConstructRegistry.addPartMapping(woodPattern.itemID, meta + 1, 31, new ItemStack(patternOutputs[meta], 1, 31));
}
TConstructRegistry.addBowstringMaterial(1, 2, new ItemStack((Item) obj, 1, 7), new ItemStack(bowstring, 1, 1), 1F, 1F, 0.9f);
TConstructRegistry.addBowMaterial(31, 576, 40, 1.2f);
TConstructRegistry.addArrowMaterial(31, 1.8F, 0.5F, 100F);
}
else
{
TConstruct.logger.warning("Thaumcraft not detected.");
}
if (Loader.isModLoaded("Natura"))
{
try
{
Object plantItem = getStaticItem("plantItem", "mods.natura.common.NContent");
TConstructRegistry.addBowstringMaterial(2, 2, new ItemStack((Item) plantItem, 1, 7), new ItemStack(bowstring, 1, 2), 1.2F, 0.8F, 1.3f);
}
catch (Exception e)
{
} //No need to handle
}
ItemStack ingotcast = new ItemStack(metalPattern, 1, 0);
LiquidCasting tableCasting = TConstructRegistry.instance.getTableCasting();
LiquidCasting basinCasting = TConstructRegistry.instance.getBasinCasting();
/* Thermal Expansion */
ArrayList<ItemStack> ores = OreDictionary.getOres("ingotNickel");
if (ores.size() > 0)
{
tableCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenNickelFluid, TConstruct.ingotLiquidValue), ingotcast, 80);
}
ores = OreDictionary.getOres("ingotLead");
if (ores.size() > 0)
{
tableCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenLeadFluid, TConstruct.ingotLiquidValue), ingotcast, 80);
}
ores = OreDictionary.getOres("ingotSilver");
if (ores.size() > 0)
{
tableCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenSilverFluid, TConstruct.ingotLiquidValue), ingotcast, 80);
}
ores = OreDictionary.getOres("ingotPlatinum");
if (ores.size() > 0)
{
tableCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenShinyFluid, TConstruct.ingotLiquidValue), ingotcast, 80);
}
ores = OreDictionary.getOres("ingotInvar");
if (ores.size() > 0)
{
tableCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenInvarFluid, TConstruct.ingotLiquidValue), ingotcast, 80);
Smeltery.addAlloyMixing(new FluidStack(moltenInvarFluid, 24), new FluidStack(moltenIronFluid, 16), new FluidStack(moltenNickelFluid, 8)); //Invar
}
ores = OreDictionary.getOres("ingotElectrum");
if (ores.size() > 0)
{
tableCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenElectrumFluid, TConstruct.ingotLiquidValue), ingotcast, 80);
Smeltery.addAlloyMixing(new FluidStack(moltenElectrumFluid, 16), new FluidStack(moltenGoldFluid, 8), new FluidStack(moltenSilverFluid, 8)); //Electrum
}
ores = OreDictionary.getOres("blockNickel");
if (ores.size() > 0)
{
basinCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenNickelFluid, TConstruct.blockLiquidValue), null, 100);
}
ores = OreDictionary.getOres("blockLead");
if (ores.size() > 0)
{
basinCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenLeadFluid, TConstruct.blockLiquidValue), null, 100);
}
ores = OreDictionary.getOres("blockSilver");
if (ores.size() > 0)
{
basinCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenSilverFluid, TConstruct.blockLiquidValue), null, 100);
}
ores = OreDictionary.getOres("blockPlatinum");
if (ores.size() > 0)
{
basinCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenShinyFluid, TConstruct.blockLiquidValue), null, 100);
}
ores = OreDictionary.getOres("blockInvar");
if (ores.size() > 0)
{
basinCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenInvarFluid, TConstruct.blockLiquidValue), null, 100);
}
ores = OreDictionary.getOres("blockElectrum");
if (ores.size() > 0)
{
basinCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenElectrumFluid, TConstruct.blockLiquidValue), null, 100);
}
}
public static Object getStaticItem (String name, String classPackage)
{
try
{
Class clazz = Class.forName(classPackage);
Field field = clazz.getDeclaredField(name);
Object ret = field.get(null);
if (ret != null && (ret instanceof ItemStack || ret instanceof Item))
return ret;
return null;
}
catch (Exception e)
{
TConstruct.logger.warning("Could not find " + name);
return null;
}
}
@Override
public int getBurnTime (ItemStack fuel)
{
if (fuel.itemID == materials.itemID && fuel.getItemDamage() == 7)
return 26400;
if (fuel.itemID == woodPattern.itemID)
return 800;
return 0;
}
public void addOreDictionarySmelteryRecipes ()
{
List<FluidType> exceptions = Arrays.asList(new FluidType[] { FluidType.Water, FluidType.Stone, FluidType.Ender, FluidType.Glass, FluidType.Slime });
for (FluidType ft : FluidType.values())
{
if (exceptions.contains(ft))
continue;
// Nuggets
Smeltery.addDictionaryMelting("nugget" + ft.toString(), ft, -100, TConstruct.nuggetLiquidValue);
// Ingots, Dust
registerIngotCasting(ft);
Smeltery.addDictionaryMelting("ingot" + ft.toString(), ft, -50, TConstruct.ingotLiquidValue);
Smeltery.addDictionaryMelting("dust" + ft.toString(), ft, -75, TConstruct.ingotLiquidValue);
// Factorization support
Smeltery.addDictionaryMelting("crystalline" + ft.toString(), ft, -50, TConstruct.ingotLiquidValue);
// Ores
Smeltery.addDictionaryMelting("ore" + ft.toString(), ft, 0, TConstruct.oreLiquidValue);
// NetherOres support
Smeltery.addDictionaryMelting("oreNether" + ft.toString(), ft, 75, TConstruct.oreLiquidValue * 2);
// Blocks
Smeltery.addDictionaryMelting("block" + ft.toString(), ft, 100, TConstruct.blockLiquidValue);
if (ft.isToolpart)
{
registerPatternMaterial("ingot" + ft.toString(), 2, ft.toString());
registerPatternMaterial("block" + ft.toString(), 18, ft.toString());
}
}
registerPatternMaterial("plankWood", 2, "Wood");
registerPatternMaterial("stickWood", 1, "Wood");
registerPatternMaterial("slabWood", 1, "Wood");
}
private void registerPatternMaterial (String oreName, int value, String materialName)
{
for (ItemStack ore : OreDictionary.getOres(oreName))
{
PatternBuilder.instance.registerMaterial(ore, value, materialName);
}
}
private void registerIngotCasting (FluidType ft)
{
ItemStack pattern = new ItemStack(TContent.metalPattern, 1, 0);
LiquidCasting tableCasting = TConstructRegistry.instance.getTableCasting();
for (ItemStack ore : OreDictionary.getOres("ingot" + ft.toString()))
{
tableCasting.addCastingRecipe(pattern, new FluidStack(TContent.moltenAlubrassFluid, TConstruct.ingotLiquidValue), new ItemStack(ore.itemID, 1, ore.getItemDamage()), false, 50);
tableCasting.addCastingRecipe(pattern, new FluidStack(TContent.moltenGoldFluid, TConstruct.oreLiquidValue), new ItemStack(ore.itemID, 1, ore.getItemDamage()), false, 50);
tableCasting.addCastingRecipe(new ItemStack(ore.itemID, 1, ore.getItemDamage()), new FluidStack(ft.fluid, TConstruct.ingotLiquidValue), pattern, 80);
}
}
}
| false | true | void registerBlocks ()
{
//Tool Station
toolStationWood = new ToolStationBlock(PHConstruct.woodStation, Material.wood).setUnlocalizedName("ToolStation");
GameRegistry.registerBlock(toolStationWood, ToolStationItemBlock.class, "ToolStationBlock");
GameRegistry.registerTileEntity(ToolStationLogic.class, "ToolStation");
GameRegistry.registerTileEntity(PartBuilderLogic.class, "PartCrafter");
GameRegistry.registerTileEntity(PatternChestLogic.class, "PatternHolder");
GameRegistry.registerTileEntity(StencilTableLogic.class, "PatternShaper");
toolForge = new ToolForgeBlock(PHConstruct.toolForge, Material.iron).setUnlocalizedName("ToolForge");
GameRegistry.registerBlock(toolForge, MetadataItemBlock.class, "ToolForgeBlock");
GameRegistry.registerTileEntity(ToolForgeLogic.class, "ToolForge");
craftingStationWood = new CraftingStationBlock(PHConstruct.woodCrafter, Material.wood).setUnlocalizedName("CraftingStation");
GameRegistry.registerBlock(craftingStationWood, "CraftingStation");
GameRegistry.registerTileEntity(CraftingStationLogic.class, "CraftingStation");
craftingSlabWood = new CraftingSlab(PHConstruct.woodCrafterSlab, Material.wood).setUnlocalizedName("CraftingSlab");
GameRegistry.registerBlock(craftingSlabWood, CraftingSlabItemBlock.class, "CraftingSlab");
heldItemBlock = new EquipBlock(PHConstruct.heldItemBlock, Material.wood).setUnlocalizedName("Frypan");
GameRegistry.registerBlock(heldItemBlock, "HeldItemBlock");
GameRegistry.registerTileEntity(FrypanLogic.class, "FrypanLogic");
craftedSoil = new SoilBlock(PHConstruct.craftedSoil).setLightOpacity(0).setUnlocalizedName("TConstruct.Soil");
craftedSoil.stepSound = Block.soundGravelFootstep;
GameRegistry.registerBlock(craftedSoil, CraftedSoilItemBlock.class, "CraftedSoil");
searedSlab = new SearedSlab(PHConstruct.searedSlab).setUnlocalizedName("SearedSlab");
searedSlab.stepSound = Block.soundStoneFootstep;
GameRegistry.registerBlock(searedSlab, SearedSlabItem.class, "SearedSlab");
speedSlab = new SpeedSlab(PHConstruct.speedSlab).setUnlocalizedName("SpeedSlab");
speedSlab.stepSound = Block.soundStoneFootstep;
GameRegistry.registerBlock(speedSlab, SpeedSlabItem.class, "SpeedSlab");
metalBlock = new TMetalBlock(PHConstruct.metalBlock, Material.iron, 10.0F).setUnlocalizedName("tconstruct.metalblock");
metalBlock.stepSound = Block.soundMetalFootstep;
GameRegistry.registerBlock(metalBlock, MetalItemBlock.class, "MetalBlock");
meatBlock = new MeatBlock(PHConstruct.meatBlock).setUnlocalizedName("tconstruct.meatblock");
GameRegistry.registerBlock(meatBlock, "MeatBlock");
OreDictionary.registerOre("hambone", new ItemStack(meatBlock));
LanguageRegistry.addName(meatBlock, "Hambone");
GameRegistry.addRecipe(new ItemStack(meatBlock), "mmm", "mbm", "mmm", 'b', new ItemStack(Item.bone), 'm', new ItemStack(Item.porkRaw));
woolSlab1 = new SlabBase(PHConstruct.woolSlab1, Material.cloth, Block.cloth, 0, 8).setUnlocalizedName("cloth");
woolSlab1.setStepSound(Block.soundClothFootstep).setCreativeTab(CreativeTabs.tabDecorations);
GameRegistry.registerBlock(woolSlab1, WoolSlab1Item.class, "WoolSlab1");
woolSlab2 = new SlabBase(PHConstruct.woolSlab2, Material.cloth, Block.cloth, 8, 8).setUnlocalizedName("cloth");
woolSlab2.setStepSound(Block.soundClothFootstep).setCreativeTab(CreativeTabs.tabDecorations);
GameRegistry.registerBlock(woolSlab2, WoolSlab2Item.class, "WoolSlab2");
//Smeltery
smeltery = new SmelteryBlock(PHConstruct.smeltery).setUnlocalizedName("Smeltery");
GameRegistry.registerBlock(smeltery, SmelteryItemBlock.class, "Smeltery");
if (PHConstruct.newSmeltery)
{
GameRegistry.registerTileEntity(AdaptiveSmelteryLogic.class, "TConstruct.Smeltery");
GameRegistry.registerTileEntity(AdaptiveDrainLogic.class, "TConstruct.SmelteryDrain");
}
else
{
GameRegistry.registerTileEntity(SmelteryLogic.class, "TConstruct.Smeltery");
GameRegistry.registerTileEntity(SmelteryDrainLogic.class, "TConstruct.SmelteryDrain");
}
GameRegistry.registerTileEntity(MultiServantLogic.class, "TConstruct.Servants");
lavaTank = new LavaTankBlock(PHConstruct.lavaTank).setUnlocalizedName("LavaTank");
lavaTank.setStepSound(Block.soundGlassFootstep);
GameRegistry.registerBlock(lavaTank, LavaTankItemBlock.class, "LavaTank");
GameRegistry.registerTileEntity(LavaTankLogic.class, "TConstruct.LavaTank");
searedBlock = new SearedBlock(PHConstruct.searedTable).setUnlocalizedName("SearedBlock");
GameRegistry.registerBlock(searedBlock, SearedTableItemBlock.class, "SearedBlock");
GameRegistry.registerTileEntity(CastingTableLogic.class, "CastingTable");
GameRegistry.registerTileEntity(FaucetLogic.class, "Faucet");
GameRegistry.registerTileEntity(CastingBasinLogic.class, "CastingBasin");
castingChannel = (new CastingChannelBlock(PHConstruct.castingChannel)).setUnlocalizedName("CastingChannel");
GameRegistry.registerBlock(castingChannel, CastingChannelItem.class, "CastingChannel");
GameRegistry.registerTileEntity(CastingChannelLogic.class, "CastingChannel");
tankAir = new TankAirBlock(PHConstruct.airTank, Material.leaves).setBlockUnbreakable().setUnlocalizedName("tconstruct.tank.air");
GameRegistry.registerBlock(tankAir, "TankAir");
GameRegistry.registerTileEntity(TankAirLogic.class, "tconstruct.tank.air");
//Redstone machines
redstoneMachine = new RedstoneMachine(PHConstruct.redstoneMachine).setUnlocalizedName("Redstone.Machine");
GameRegistry.registerBlock(redstoneMachine, RedstoneMachineItem.class, "Redstone.Machine");
GameRegistry.registerTileEntity(DrawbridgeLogic.class, "Drawbridge");
GameRegistry.registerTileEntity(FirestarterLogic.class, "Firestarter");
GameRegistry.registerTileEntity(AdvancedDrawbridgeLogic.class, "AdvDrawbridge");
//Traps
landmine = new BlockLandmine(PHConstruct.landmine).setHardness(0.5F).setResistance(0F).setStepSound(Block.soundMetalFootstep).setCreativeTab(CreativeTabs.tabRedstone)
.setUnlocalizedName("landmine");
GameRegistry.registerBlock(landmine, ItemBlockLandmine.class, "Redstone.Landmine");
GameRegistry.registerTileEntity(TileEntityLandmine.class, "Landmine");
punji = new Punji(PHConstruct.punji).setUnlocalizedName("trap.punji");
GameRegistry.registerBlock(punji, "trap.punji");
barricadeOak = new BarricadeBlock(PHConstruct.barricadeOak, Block.wood, 0).setUnlocalizedName("trap.barricade.oak");
GameRegistry.registerBlock(barricadeOak, BarricadeItem.class, "trap.barricade.oak");
barricadeSpruce = new BarricadeBlock(PHConstruct.barricadeSpruce, Block.wood, 1).setUnlocalizedName("trap.barricade.spruce");
GameRegistry.registerBlock(barricadeSpruce, BarricadeItem.class, "trap.barricade.spruce");
barricadeBirch = new BarricadeBlock(PHConstruct.barricadeBirch, Block.wood, 2).setUnlocalizedName("trap.barricade.birch");
GameRegistry.registerBlock(barricadeBirch, BarricadeItem.class, "trap.barricade.birch");
barricadeJungle = new BarricadeBlock(PHConstruct.barricadeJungle, Block.wood, 3).setUnlocalizedName("trap.barricade.jungle");
GameRegistry.registerBlock(barricadeJungle, BarricadeItem.class, "trap.barricade.jungle");
slimeExplosive = new SlimeExplosive(PHConstruct.slimeExplosive).setHardness(0.0F).setStepSound(Block.soundGrassFootstep).setUnlocalizedName("explosive.slime");
GameRegistry.registerBlock(slimeExplosive, MetadataItemBlock.class, "explosive.slime");
dryingRack = new DryingRack(PHConstruct.dryingRack).setUnlocalizedName("Armor.DryingRack");
GameRegistry.registerBlock(dryingRack, "Armor.DryingRack");
GameRegistry.registerTileEntity(DryingRackLogic.class, "Armor.DryingRack");
//Liquids
liquidMetal = new MaterialLiquid(MapColor.tntColor);
moltenIronFluid = new Fluid("iron.molten");
if (!FluidRegistry.registerFluid(moltenIronFluid))
moltenIronFluid = FluidRegistry.getFluid("iron.molten");
moltenIron = new TConstructFluid(PHConstruct.moltenIron, moltenIronFluid, Material.lava, "liquid_iron").setUnlocalizedName("metal.molten.iron");
GameRegistry.registerBlock(moltenIron, "metal.molten.iron");
fluids[0] = moltenIronFluid;
fluidBlocks[0] = moltenIron;
moltenIronFluid.setBlockID(moltenIron).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenIronFluid, 1000), new ItemStack(buckets, 1, 0), new ItemStack(Item.bucketEmpty)));
moltenGoldFluid = new Fluid("gold.molten");
if (!FluidRegistry.registerFluid(moltenGoldFluid))
moltenGoldFluid = FluidRegistry.getFluid("gold.molten");
moltenGold = new TConstructFluid(PHConstruct.moltenGold, moltenGoldFluid, Material.lava, "liquid_gold").setUnlocalizedName("metal.molten.gold");
GameRegistry.registerBlock(moltenGold, "metal.molten.gold");
fluids[1] = moltenGoldFluid;
fluidBlocks[1] = moltenGold;
moltenGoldFluid.setBlockID(moltenGold).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenGoldFluid, 1000), new ItemStack(buckets, 1, 1), new ItemStack(Item.bucketEmpty)));
moltenCopperFluid = new Fluid("copper.molten");
if (!FluidRegistry.registerFluid(moltenCopperFluid))
moltenCopperFluid = FluidRegistry.getFluid("copper.molten");
moltenCopper = new TConstructFluid(PHConstruct.moltenCopper, moltenCopperFluid, Material.lava, "liquid_copper").setUnlocalizedName("metal.molten.copper");
GameRegistry.registerBlock(moltenCopper, "metal.molten.copper");
fluids[2] = moltenCopperFluid;
fluidBlocks[2] = moltenCopper;
moltenCopperFluid.setBlockID(moltenCopper).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenCopperFluid, 1000), new ItemStack(buckets, 1, 2), new ItemStack(Item.bucketEmpty)));
moltenTinFluid = new Fluid("tin.molten");
if (!FluidRegistry.registerFluid(moltenTinFluid))
moltenTinFluid = FluidRegistry.getFluid("tin.molten");
moltenTin = new TConstructFluid(PHConstruct.moltenTin, moltenTinFluid, Material.lava, "liquid_tin").setUnlocalizedName("metal.molten.tin");
GameRegistry.registerBlock(moltenTin, "metal.molten.tin");
fluids[3] = moltenTinFluid;
fluidBlocks[3] = moltenTin;
moltenTinFluid.setBlockID(moltenTin).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenTinFluid, 1000), new ItemStack(buckets, 1, 3), new ItemStack(Item.bucketEmpty)));
moltenAluminumFluid = new Fluid("aluminum.molten");
if (!FluidRegistry.registerFluid(moltenAluminumFluid))
moltenAluminumFluid = FluidRegistry.getFluid("aluminum.molten");
moltenAluminum = new TConstructFluid(PHConstruct.moltenAluminum, moltenAluminumFluid, Material.lava, "liquid_aluminum").setUnlocalizedName("metal.molten.aluminum");
GameRegistry.registerBlock(moltenAluminum, "metal.molten.aluminum");
fluids[4] = moltenAluminumFluid;
fluidBlocks[4] = moltenAluminum;
moltenAluminumFluid.setBlockID(moltenAluminum).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenAluminumFluid, 1000), new ItemStack(buckets, 1, 4), new ItemStack(Item.bucketEmpty)));
moltenCobaltFluid = new Fluid("cobalt.molten");
if (!FluidRegistry.registerFluid(moltenCobaltFluid))
moltenCobaltFluid = FluidRegistry.getFluid("cobalt.molten");
moltenCobalt = new TConstructFluid(PHConstruct.moltenCobalt, moltenCobaltFluid, Material.lava, "liquid_cobalt").setUnlocalizedName("metal.molten.cobalt");
GameRegistry.registerBlock(moltenCobalt, "metal.molten.cobalt");
fluids[5] = moltenCobaltFluid;
fluidBlocks[5] = moltenCobalt;
moltenCobaltFluid.setBlockID(moltenCobalt).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenCobaltFluid, 1000), new ItemStack(buckets, 1, 5), new ItemStack(Item.bucketEmpty)));
moltenArditeFluid = new Fluid("ardite.molten");
if (!FluidRegistry.registerFluid(moltenArditeFluid))
moltenArditeFluid = FluidRegistry.getFluid("ardite.molten");
moltenArdite = new TConstructFluid(PHConstruct.moltenArdite, moltenArditeFluid, Material.lava, "liquid_ardite").setUnlocalizedName("metal.molten.ardite");
GameRegistry.registerBlock(moltenArdite, "metal.molten.ardite");
fluids[6] = moltenArditeFluid;
fluidBlocks[6] = moltenArdite;
moltenArditeFluid.setBlockID(moltenArdite).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenArditeFluid, 1000), new ItemStack(buckets, 1, 6), new ItemStack(Item.bucketEmpty)));
moltenBronzeFluid = new Fluid("bronze.molten");
if (!FluidRegistry.registerFluid(moltenBronzeFluid))
moltenBronzeFluid = FluidRegistry.getFluid("bronze.molten");
moltenBronze = new TConstructFluid(PHConstruct.moltenBronze, moltenBronzeFluid, Material.lava, "liquid_bronze").setUnlocalizedName("metal.molten.bronze");
GameRegistry.registerBlock(moltenBronze, "metal.molten.bronze");
fluids[7] = moltenBronzeFluid;
fluidBlocks[7] = moltenBronze;
moltenBronzeFluid.setBlockID(moltenBronze).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenBronzeFluid, 1000), new ItemStack(buckets, 1, 7), new ItemStack(Item.bucketEmpty)));
moltenAlubrassFluid = new Fluid("aluminumbrass.molten");
if (!FluidRegistry.registerFluid(moltenAlubrassFluid))
moltenAlubrassFluid = FluidRegistry.getFluid("aluminumbrass.molten");
moltenAlubrass = new TConstructFluid(PHConstruct.moltenAlubrass, moltenAlubrassFluid, Material.lava, "liquid_alubrass").setUnlocalizedName("metal.molten.alubrass");
GameRegistry.registerBlock(moltenAlubrass, "metal.molten.alubrass");
fluids[8] = moltenAlubrassFluid;
fluidBlocks[8] = moltenAlubrass;
moltenAlubrassFluid.setBlockID(moltenAlubrass).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenAlubrassFluid, 1000), new ItemStack(buckets, 1, 8), new ItemStack(Item.bucketEmpty)));
moltenManyullynFluid = new Fluid("manyullyn.molten");
if (!FluidRegistry.registerFluid(moltenManyullynFluid))
moltenManyullynFluid = FluidRegistry.getFluid("manyullyn.molten");
moltenManyullyn = new TConstructFluid(PHConstruct.moltenManyullyn, moltenManyullynFluid, Material.lava, "liquid_manyullyn").setUnlocalizedName("metal.molten.manyullyn");
GameRegistry.registerBlock(moltenManyullyn, "metal.molten.manyullyn");
fluids[9] = moltenManyullynFluid;
fluidBlocks[9] = moltenManyullyn;
moltenManyullynFluid.setBlockID(moltenManyullyn).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenManyullynFluid, 1000), new ItemStack(buckets, 1, 9), new ItemStack(Item.bucketEmpty)));
moltenAlumiteFluid = new Fluid("alumite.molten");
if (!FluidRegistry.registerFluid(moltenAlumiteFluid))
moltenAlumiteFluid = FluidRegistry.getFluid("alumite.molten");
moltenAlumite = new TConstructFluid(PHConstruct.moltenAlumite, moltenAlumiteFluid, Material.lava, "liquid_alumite").setUnlocalizedName("metal.molten.alumite");
GameRegistry.registerBlock(moltenAlumite, "metal.molten.alumite");
fluids[10] = moltenAlumiteFluid;
fluidBlocks[10] = moltenAlumite;
moltenAlumiteFluid.setBlockID(moltenAlumite).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenAlumiteFluid, 1000), new ItemStack(buckets, 1, 10), new ItemStack(Item.bucketEmpty)));
moltenObsidianFluid = new Fluid("obsidian.molten");
if (!FluidRegistry.registerFluid(moltenObsidianFluid))
moltenObsidianFluid = FluidRegistry.getFluid("obsidian.molten");
moltenObsidian = new TConstructFluid(PHConstruct.moltenObsidian, moltenObsidianFluid, Material.lava, "liquid_obsidian").setUnlocalizedName("metal.molten.obsidian");
GameRegistry.registerBlock(moltenObsidian, "metal.molten.obsidian");
fluids[11] = moltenObsidianFluid;
fluidBlocks[11] = moltenObsidian;
moltenObsidianFluid.setBlockID(moltenObsidian).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenObsidianFluid, 1000), new ItemStack(buckets, 1, 11), new ItemStack(Item.bucketEmpty)));
moltenSteelFluid = new Fluid("steel.molten");
if (!FluidRegistry.registerFluid(moltenSteelFluid))
moltenSteelFluid = FluidRegistry.getFluid("steel.molten");
moltenSteel = new TConstructFluid(PHConstruct.moltenSteel, moltenSteelFluid, Material.lava, "liquid_steel").setUnlocalizedName("metal.molten.steel");
GameRegistry.registerBlock(moltenSteel, "metal.molten.steel");
fluids[12] = moltenSteelFluid;
fluidBlocks[12] = moltenSteel;
moltenSteelFluid.setBlockID(moltenSteel).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenSteelFluid, 1000), new ItemStack(buckets, 1, 12), new ItemStack(Item.bucketEmpty)));
moltenGlassFluid = new Fluid("glass.molten");
if (!FluidRegistry.registerFluid(moltenGlassFluid))
moltenGlassFluid = FluidRegistry.getFluid("glass.molten");
moltenGlass = new TConstructFluid(PHConstruct.moltenGlass, moltenGlassFluid, Material.lava, "liquid_glass", true).setUnlocalizedName("metal.molten.glass");
GameRegistry.registerBlock(moltenGlass, "metal.molten.glass");
fluids[13] = moltenGlassFluid;
fluidBlocks[13] = moltenGlass;
moltenGlassFluid.setBlockID(moltenGlass).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenGlassFluid, 1000), new ItemStack(buckets, 1, 13), new ItemStack(Item.bucketEmpty)));
moltenStoneFluid = new Fluid("stone.seared");
if (!FluidRegistry.registerFluid(moltenStoneFluid))
moltenStoneFluid = FluidRegistry.getFluid("stone.seared");
moltenStone = new TConstructFluid(PHConstruct.moltenStone, moltenStoneFluid, Material.lava, "liquid_stone").setUnlocalizedName("molten.stone");
GameRegistry.registerBlock(moltenStone, "molten.stone");
fluids[14] = moltenStoneFluid;
fluidBlocks[14] = moltenStone;
moltenStoneFluid.setBlockID(moltenStone).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenStoneFluid, 1000), new ItemStack(buckets, 1, 14), new ItemStack(Item.bucketEmpty)));
moltenEmeraldFluid = new Fluid("emerald.liquid");
if (!FluidRegistry.registerFluid(moltenEmeraldFluid))
moltenEmeraldFluid = FluidRegistry.getFluid("emerald.liquid");
moltenEmerald = new TConstructFluid(PHConstruct.moltenEmerald, moltenEmeraldFluid, Material.water, "liquid_villager").setUnlocalizedName("molten.emerald");
GameRegistry.registerBlock(moltenEmerald, "molten.emerald");
fluids[15] = moltenEmeraldFluid;
fluidBlocks[15] = moltenEmerald;
moltenEmeraldFluid.setBlockID(moltenEmerald).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenEmeraldFluid, 1000), new ItemStack(buckets, 1, 15), new ItemStack(Item.bucketEmpty)));
bloodFluid = new Fluid("blood");
if (!FluidRegistry.registerFluid(bloodFluid))
bloodFluid = FluidRegistry.getFluid("blood");
blood = new TConstructFluid(PHConstruct.blood, bloodFluid, Material.water, "liquid_cow").setUnlocalizedName("liquid.blood");
GameRegistry.registerBlock(blood, "liquid.blood");
fluids[16] = bloodFluid;
fluidBlocks[16] = blood;
bloodFluid.setBlockID(blood).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(bloodFluid, 1000), new ItemStack(buckets, 1, 16), new ItemStack(Item.bucketEmpty)));
moltenNickelFluid = new Fluid("nickel.molten");
if (!FluidRegistry.registerFluid(moltenNickelFluid))
moltenNickelFluid = FluidRegistry.getFluid("nickel.molten");
moltenNickel = new TConstructFluid(PHConstruct.moltenNickel, moltenNickelFluid, Material.lava, "liquid_ferrous").setUnlocalizedName("metal.molten.nickel");
GameRegistry.registerBlock(moltenNickel, "metal.molten.nickel");
fluids[17] = moltenNickelFluid;
fluidBlocks[17] = moltenNickel;
moltenNickelFluid.setBlockID(moltenNickel).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenNickelFluid, 1000), new ItemStack(buckets, 1, 17), new ItemStack(Item.bucketEmpty)));
moltenLeadFluid = new Fluid("lead.molten");
if (!FluidRegistry.registerFluid(moltenLeadFluid))
moltenLeadFluid = FluidRegistry.getFluid("lead.molten");
moltenLead = new TConstructFluid(PHConstruct.moltenLead, moltenLeadFluid, Material.lava, "liquid_lead").setUnlocalizedName("metal.molten.lead");
GameRegistry.registerBlock(moltenLead, "metal.molten.lead");
fluids[18] = moltenLeadFluid;
fluidBlocks[18] = moltenLead;
moltenLeadFluid.setBlockID(moltenLead).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenLeadFluid, 1000), new ItemStack(buckets, 1, 18), new ItemStack(Item.bucketEmpty)));
moltenSilverFluid = new Fluid("silver.molten");
if (!FluidRegistry.registerFluid(moltenSilverFluid))
moltenSilverFluid = FluidRegistry.getFluid("silver.molten");
moltenSilver = new TConstructFluid(PHConstruct.moltenSilver, moltenSilverFluid, Material.lava, "liquid_silver").setUnlocalizedName("metal.molten.silver");
GameRegistry.registerBlock(moltenSilver, "metal.molten.silver");
fluids[19] = moltenSilverFluid;
fluidBlocks[19] = moltenSilver;
moltenSilverFluid.setBlockID(moltenSilver).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenSilverFluid, 1000), new ItemStack(buckets, 1, 19), new ItemStack(Item.bucketEmpty)));
moltenShinyFluid = new Fluid("platinum.molten");
if (!FluidRegistry.registerFluid(moltenShinyFluid))
moltenShinyFluid = FluidRegistry.getFluid("platinum.molten");
moltenShiny = new TConstructFluid(PHConstruct.moltenShiny, moltenShinyFluid, Material.lava, "liquid_shiny").setUnlocalizedName("metal.molten.shiny");
GameRegistry.registerBlock(moltenShiny, "metal.molten.shiny");
fluids[20] = moltenLeadFluid;
fluidBlocks[20] = moltenShiny;
moltenShinyFluid.setBlockID(moltenShiny).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenShinyFluid, 1000), new ItemStack(buckets, 1, 20), new ItemStack(Item.bucketEmpty)));
moltenInvarFluid = new Fluid("invar.molten");
if (!FluidRegistry.registerFluid(moltenInvarFluid))
moltenInvarFluid = FluidRegistry.getFluid("invar.molten");
moltenInvar = new TConstructFluid(PHConstruct.moltenInvar, moltenInvarFluid, Material.lava, "liquid_invar").setUnlocalizedName("metal.molten.invar");
GameRegistry.registerBlock(moltenInvar, "metal.molten.invar");
fluids[21] = moltenInvarFluid;
fluidBlocks[21] = moltenInvar;
moltenInvarFluid.setBlockID(moltenInvar).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenInvarFluid, 1000), new ItemStack(buckets, 1, 21), new ItemStack(Item.bucketEmpty)));
moltenElectrumFluid = new Fluid("electrum.molten");
if (!FluidRegistry.registerFluid(moltenElectrumFluid))
moltenElectrumFluid = FluidRegistry.getFluid("electrum.molten");
moltenElectrum = new TConstructFluid(PHConstruct.moltenElectrum, moltenElectrumFluid, Material.lava, "liquid_electrum").setUnlocalizedName("metal.molten.electrum");
GameRegistry.registerBlock(moltenElectrum, "metal.molten.electrum");
fluids[22] = moltenElectrumFluid;
fluidBlocks[22] = moltenElectrum;
moltenElectrumFluid.setBlockID(moltenElectrum).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenElectrumFluid, 1000), new ItemStack(buckets, 1, 22), new ItemStack(Item.bucketEmpty)));
moltenEnderFluid = new Fluid("ender");
if (GameRegistry.findBlock("ThermalExpansion", "fluid.ender") == null)
{
if (FluidRegistry.registerFluid(moltenEnderFluid))
{
moltenEnder = new TConstructFluid(PHConstruct.moltenEnder, moltenEnderFluid, Material.water, "liquid_ender").setUnlocalizedName("fluid.ender");
//TConstruct.logger.info("Registering Molten Ender Stuff.");
GameRegistry.registerBlock(moltenEnder, "fluid.ender");
moltenEnderFluid.setBlockID(moltenEnder).setDensity(3000).setViscosity(6000);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenEnderFluid, 1000), new ItemStack(buckets, 1, 23), new ItemStack(Item.bucketEmpty)));
}
}
else
{
moltenEnderFluid = FluidRegistry.getFluid("ender");
moltenEnder = GameRegistry.findBlock("ThermalExpansion", "fluid.ender");
}
fluids[23] = moltenEnderFluid;
fluidBlocks[23] = moltenEnder;
//Slime
slimeStep = new StepSoundSlime("mob.slime", 1.0f, 1.0f);
blueSlimeFluid = new Fluid("slime.blue");
if (!FluidRegistry.registerFluid(blueSlimeFluid))
blueSlimeFluid = FluidRegistry.getFluid("slime.blue");
slimePool = new SlimeFluid(PHConstruct.slimePoolBlue, blueSlimeFluid, Material.water).setCreativeTab(TConstructRegistry.blockTab).setStepSound(slimeStep).setUnlocalizedName("liquid.slime");
GameRegistry.registerBlock(slimePool, "liquid.slime");
fluids[24] = blueSlimeFluid;
fluidBlocks[24] = slimePool;
blueSlimeFluid.setBlockID(slimePool);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(blueSlimeFluid, 1000), new ItemStack(buckets, 1, 24), new ItemStack(Item.bucketEmpty)));
slimeGel = new SlimeGel(PHConstruct.slimeGel).setStepSound(slimeStep).setLightOpacity(0).setUnlocalizedName("slime.gel");
GameRegistry.registerBlock(slimeGel, SlimeGelItemBlock.class, "slime.gel");
slimeGrass = new SlimeGrass(PHConstruct.slimeGrass).setStepSound(Block.soundGrassFootstep).setLightOpacity(0).setUnlocalizedName("slime.grass");
GameRegistry.registerBlock(slimeGrass, SlimeGrassItemBlock.class, "slime.grass");
slimeTallGrass = new SlimeTallGrass(PHConstruct.slimeTallGrass).setStepSound(Block.soundGrassFootstep).setUnlocalizedName("slime.grass.tall");
GameRegistry.registerBlock(slimeTallGrass, SlimeTallGrassItem.class, "slime.grass.tall");
slimeLeaves = (SlimeLeaves) new SlimeLeaves(PHConstruct.slimeLeaves).setStepSound(slimeStep).setLightOpacity(0).setUnlocalizedName("slime.leaves");
GameRegistry.registerBlock(slimeLeaves, SlimeLeavesItemBlock.class, "slime.leaves");
slimeSapling = (SlimeSapling) new SlimeSapling(PHConstruct.slimeSapling).setStepSound(slimeStep).setUnlocalizedName("slime.sapling");
GameRegistry.registerBlock(slimeSapling, SlimeSaplingItemBlock.class, "slime.sapling");
slimeChannel = new ConveyorBase(PHConstruct.slimeChannel, Material.water).setStepSound(slimeStep).setUnlocalizedName("slime.channel");
GameRegistry.registerBlock(slimeChannel, "slime.channel");
TConstructRegistry.drawbridgeState[slimeChannel.blockID] = 1;
slimePad = new SlimePad(PHConstruct.slimePad, Material.cloth).setStepSound(slimeStep).setUnlocalizedName("slime.pad");
GameRegistry.registerBlock(slimePad, "slime.pad");
TConstructRegistry.drawbridgeState[slimePad.blockID] = 1;
//Decoration
stoneTorch = new StoneTorch(PHConstruct.stoneTorch).setUnlocalizedName("decoration.stonetorch");
GameRegistry.registerBlock(stoneTorch, "decoration.stonetorch");
stoneLadder = new StoneLadder(PHConstruct.stoneLadder).setUnlocalizedName("decoration.stoneladder");
GameRegistry.registerBlock(stoneLadder, "decoration.stoneladder");
multiBrick = new MultiBrick(PHConstruct.multiBrick).setUnlocalizedName("Decoration.Brick");
GameRegistry.registerBlock(multiBrick, MultiBrickItem.class, "decoration.multibrick");
multiBrickFancy = new MultiBrickFancy(PHConstruct.multiBrickFancy).setUnlocalizedName("Decoration.BrickFancy");
GameRegistry.registerBlock(multiBrickFancy, MultiBrickFancyItem.class, "decoration.multibrickfancy");
//Ores
String[] berryOres = new String[] { "berry_iron", "berry_gold", "berry_copper", "berry_tin", "berry_iron_ripe", "berry_gold_ripe", "berry_copper_ripe", "berry_tin_ripe" };
oreBerry = (OreberryBush) new OreberryBush(PHConstruct.oreBerry, berryOres, 0, 4, new String[] { "oreIron", "oreGold", "oreCopper", "oreTin" }).setUnlocalizedName("ore.berries.one");
GameRegistry.registerBlock(oreBerry, OreberryBushItem.class, "ore.berries.one");
String[] berryOresTwo = new String[] { "berry_aluminum", "berry_essence", "", "", "berry_aluminum_ripe", "berry_essence_ripe", "", "" };
oreBerrySecond = (OreberryBush) new OreberryBushEssence(PHConstruct.oreBerrySecond, berryOresTwo, 4, 2, new String[] { "oreAluminum", "oreSilver" }).setUnlocalizedName("ore.berries.two");
GameRegistry.registerBlock(oreBerrySecond, OreberryBushSecondItem.class, "ore.berries.two");
String[] oreTypes = new String[] { "nether_slag", "nether_cobalt", "nether_ardite", "ore_copper", "ore_tin", "ore_aluminum", "ore_slag" };
oreSlag = new MetalOre(PHConstruct.oreSlag, Material.iron, 10.0F, oreTypes).setUnlocalizedName("tconstruct.stoneore");
GameRegistry.registerBlock(oreSlag, MetalOreItemBlock.class, "SearedBrick");
MinecraftForge.setBlockHarvestLevel(oreSlag, 1, "pickaxe", 4);
MinecraftForge.setBlockHarvestLevel(oreSlag, 2, "pickaxe", 4);
MinecraftForge.setBlockHarvestLevel(oreSlag, 3, "pickaxe", 1);
MinecraftForge.setBlockHarvestLevel(oreSlag, 4, "pickaxe", 1);
MinecraftForge.setBlockHarvestLevel(oreSlag, 5, "pickaxe", 1);
oreGravel = new GravelOre(PHConstruct.oreGravel).setUnlocalizedName("GravelOre").setUnlocalizedName("tconstruct.gravelore");
GameRegistry.registerBlock(oreGravel, GravelOreItem.class, "GravelOre");
MinecraftForge.setBlockHarvestLevel(oreGravel, 0, "shovel", 1);
MinecraftForge.setBlockHarvestLevel(oreGravel, 1, "shovel", 2);
MinecraftForge.setBlockHarvestLevel(oreGravel, 2, "shovel", 1);
MinecraftForge.setBlockHarvestLevel(oreGravel, 3, "shovel", 1);
MinecraftForge.setBlockHarvestLevel(oreGravel, 4, "shovel", 1);
MinecraftForge.setBlockHarvestLevel(oreGravel, 5, "shovel", 4);
speedBlock = new SpeedBlock(PHConstruct.speedBlock).setUnlocalizedName("SpeedBlock");
GameRegistry.registerBlock(speedBlock, SpeedBlockItem.class, "SpeedBlock");
//Glass
clearGlass = new GlassBlockConnected(PHConstruct.glass, "clear", false).setUnlocalizedName("GlassBlock");
clearGlass.stepSound = Block.soundGlassFootstep;
GameRegistry.registerBlock(clearGlass, GlassBlockItem.class, "GlassBlock");
glassPane = new GlassPaneConnected(PHConstruct.glassPane, "clear", false);
GameRegistry.registerBlock(glassPane, GlassPaneItem.class, "GlassPane");
stainedGlassClear = new GlassBlockConnectedMeta(PHConstruct.stainedGlassClear, "stained", true, "white", "orange", "magenta", "light_blue", "yellow", "lime", "pink", "gray", "light_gray",
"cyan", "purple", "blue", "brown", "green", "red", "black").setUnlocalizedName("GlassBlock.StainedClear");
stainedGlassClear.stepSound = Block.soundGlassFootstep;
GameRegistry.registerBlock(stainedGlassClear, StainedGlassClearItem.class, "GlassBlock.StainedClear");
stainedGlassClearPane = new GlassPaneStained(PHConstruct.stainedGlassClearPane);
GameRegistry.registerBlock(stainedGlassClearPane, StainedGlassClearPaneItem.class, "GlassPaneClearStained");
//Crystalline
essenceExtractor = new EssenceExtractor(PHConstruct.essenceExtractor).setHardness(12f).setUnlocalizedName("extractor.essence");
GameRegistry.registerBlock(essenceExtractor, "extractor.essence");
GameRegistry.registerTileEntity(EssenceExtractorLogic.class, "extractor.essence");
//Rail
woodenRail = new WoodRail(PHConstruct.woodenRail).setStepSound(Block.soundWoodFootstep).setCreativeTab(TConstructRegistry.blockTab).setUnlocalizedName("rail.wood");
GameRegistry.registerBlock(woodenRail, "rail.wood");
//Signal & Logic
signalBus = (new SignalBus(PHConstruct.signalBus)).setUnlocalizedName("tconstruct.signalbus");
GameRegistry.registerBlock(signalBus, SignalBusItem.class, "SignalBus");
GameRegistry.registerTileEntity(SignalBusLogic.class, "SignalBus");
signalTerminal = (new SignalTerminal(PHConstruct.signalTerminal)).setUnlocalizedName("tconstruct.signalterminal");
GameRegistry.registerBlock(signalTerminal, SignalTerminalItem.class, "SignalTerminal");
GameRegistry.registerTileEntity(SignalTerminalLogic.class, "SignalTerminal");
}
void registerItems ()
{
titleIcon = new TitleIcon(PHConstruct.uselessItem).setUnlocalizedName("tconstruct.titleicon");
String[] blanks = new String[] { "blank_pattern", "blank_cast", "blank_cast" };
blankPattern = new CraftingItem(PHConstruct.blankPattern, blanks, blanks, "materials/").setUnlocalizedName("tconstruct.Pattern");
materials = new MaterialItem(PHConstruct.materials).setUnlocalizedName("tconstruct.Materials");
toolRod = new ToolPart(PHConstruct.toolRod, "_rod", "ToolRod").setUnlocalizedName("tconstruct.ToolRod");
toolShard = new ToolShard(PHConstruct.toolShard, "_chunk").setUnlocalizedName("tconstruct.ToolShard");
woodPattern = new Pattern(PHConstruct.woodPattern, "WoodPattern", "pattern_", "materials/").setUnlocalizedName("tconstruct.Pattern");
metalPattern = new MetalPattern(PHConstruct.metalPattern, "MetalPattern", "cast_", "materials/").setUnlocalizedName("tconstruct.MetalPattern");
armorPattern = new ArmorPattern(PHConstruct.armorPattern, "ArmorPattern", "armorcast_", "materials/").setUnlocalizedName("tconstruct.ArmorPattern");
TConstructRegistry.addItemToDirectory("blankPattern", blankPattern);
TConstructRegistry.addItemToDirectory("woodPattern", woodPattern);
TConstructRegistry.addItemToDirectory("metalPattern", metalPattern);
TConstructRegistry.addItemToDirectory("armorPattern", armorPattern);
String[] patternTypes = { "ingot", "toolRod", "pickaxeHead", "shovelHead", "hatchetHead", "swordBlade", "wideGuard", "handGuard", "crossbar", "binding", "frypanHead", "signHead",
"knifeBlade", "chiselHead", "toughRod", "toughBinding", "largePlate", "broadAxeHead", "scytheHead", "excavatorHead", "largeBlade", "hammerHead", "fullGuard" };
for (int i = 1; i < patternTypes.length; i++)
{
TConstructRegistry.addItemStackToDirectory(patternTypes[i] + "Pattern", new ItemStack(woodPattern, 1, i));
}
for (int i = 0; i < patternTypes.length; i++)
{
TConstructRegistry.addItemStackToDirectory(patternTypes[i] + "Cast", new ItemStack(metalPattern, 1, i));
}
String[] armorPartTypes = { "helmet", "chestplate", "leggings", "boots" };
for (int i = 1; i < armorPartTypes.length; i++)
{
TConstructRegistry.addItemStackToDirectory(armorPartTypes[i] + "Cast", new ItemStack(armorPattern, 1, i));
}
manualBook = new Manual(PHConstruct.manual);
buckets = new FilledBucket(PHConstruct.buckets);
pickaxe = new Pickaxe(PHConstruct.pickaxe);
shovel = new Shovel(PHConstruct.shovel);
hatchet = new Hatchet(PHConstruct.axe);
broadsword = new Broadsword(PHConstruct.broadsword);
longsword = new Longsword(PHConstruct.longsword);
rapier = new Rapier(PHConstruct.rapier);
dagger = new Dagger(PHConstruct.dagger);
cutlass = new Cutlass(PHConstruct.cutlass);
frypan = new FryingPan(PHConstruct.frypan);
battlesign = new BattleSign(PHConstruct.battlesign);
mattock = new Mattock(PHConstruct.mattock);
chisel = new Chisel(PHConstruct.chisel);
lumberaxe = new LumberAxe(PHConstruct.lumberaxe);
cleaver = new Cleaver(PHConstruct.cleaver);
scythe = new Scythe(PHConstruct.scythe);
excavator = new Excavator(PHConstruct.excavator);
hammer = new Hammer(PHConstruct.hammer);
battleaxe = new Battleaxe(PHConstruct.battleaxe);
shortbow = new Shortbow(PHConstruct.shortbow);
arrow = new Arrow(PHConstruct.arrow);
Item[] tools = { pickaxe, shovel, hatchet, broadsword, longsword, rapier, cutlass, frypan, battlesign, mattock, chisel, lumberaxe, cleaver, scythe, excavator, hammer, battleaxe };
String[] toolStrings = { "pickaxe", "shovel", "hatchet", "broadsword", "longsword", "rapier", "cutlass", "frypan", "battlesign", "mattock", "chisel", "lumberaxe", "cleaver", "scythe",
"excavator", "hammer", "battleaxe" };
for (int i = 0; i < tools.length; i++)
{
TConstructRegistry.addItemToDirectory(toolStrings[i], tools[i]);
}
potionLauncher = new PotionLauncher(PHConstruct.potionLauncher).setUnlocalizedName("tconstruct.PotionLauncher");
pickaxeHead = new ToolPart(PHConstruct.pickaxeHead, "_pickaxe_head", "PickHead").setUnlocalizedName("tconstruct.PickaxeHead");
shovelHead = new ToolPart(PHConstruct.shovelHead, "_shovel_head", "ShovelHead").setUnlocalizedName("tconstruct.ShovelHead");
hatchetHead = new ToolPart(PHConstruct.axeHead, "_axe_head", "AxeHead").setUnlocalizedName("tconstruct.AxeHead");
binding = new ToolPart(PHConstruct.binding, "_binding", "Binding").setUnlocalizedName("tconstruct.Binding");
toughBinding = new ToolPart(PHConstruct.toughBinding, "_toughbind", "ToughBind").setUnlocalizedName("tconstruct.ThickBinding");
toughRod = new ToolPart(PHConstruct.toughRod, "_toughrod", "ToughRod").setUnlocalizedName("tconstruct.ThickRod");
largePlate = new ToolPart(PHConstruct.largePlate, "_largeplate", "LargePlate").setUnlocalizedName("tconstruct.LargePlate");
swordBlade = new ToolPart(PHConstruct.swordBlade, "_sword_blade", "SwordBlade").setUnlocalizedName("tconstruct.SwordBlade");
wideGuard = new ToolPart(PHConstruct.largeGuard, "_large_guard", "LargeGuard").setUnlocalizedName("tconstruct.LargeGuard");
handGuard = new ToolPart(PHConstruct.medGuard, "_medium_guard", "MediumGuard").setUnlocalizedName("tconstruct.MediumGuard");
crossbar = new ToolPart(PHConstruct.crossbar, "_crossbar", "Crossbar").setUnlocalizedName("tconstruct.Crossbar");
knifeBlade = new ToolPart(PHConstruct.knifeBlade, "_knife_blade", "KnifeBlade").setUnlocalizedName("tconstruct.KnifeBlade");
fullGuard = new ToolPartHidden(PHConstruct.fullGuard, "_full_guard", "FullGuard").setUnlocalizedName("tconstruct.FullGuard");
frypanHead = new ToolPart(PHConstruct.frypanHead, "_frypan_head", "FrypanHead").setUnlocalizedName("tconstruct.FrypanHead");
signHead = new ToolPart(PHConstruct.signHead, "_battlesign_head", "SignHead").setUnlocalizedName("tconstruct.SignHead");
chiselHead = new ToolPart(PHConstruct.chiselHead, "_chisel_head", "ChiselHead").setUnlocalizedName("tconstruct.ChiselHead");
scytheBlade = new ToolPart(PHConstruct.scytheBlade, "_scythe_head", "ScytheHead").setUnlocalizedName("tconstruct.ScytheBlade");
broadAxeHead = new ToolPart(PHConstruct.lumberHead, "_lumberaxe_head", "LumberHead").setUnlocalizedName("tconstruct.LumberHead");
excavatorHead = new ToolPart(PHConstruct.excavatorHead, "_excavator_head", "ExcavatorHead").setUnlocalizedName("tconstruct.ExcavatorHead");
largeSwordBlade = new ToolPart(PHConstruct.largeSwordBlade, "_large_sword_blade", "LargeSwordBlade").setUnlocalizedName("tconstruct.LargeSwordBlade");
hammerHead = new ToolPart(PHConstruct.hammerHead, "_hammer_head", "HammerHead").setUnlocalizedName("tconstruct.HammerHead");
bowstring = new Bowstring(PHConstruct.bowstring).setUnlocalizedName("tconstruct.Bowstring");
arrowhead = new ToolPart(PHConstruct.arrowhead, "_arrowhead", "ArrowHead").setUnlocalizedName("tconstruct.Arrowhead");
fletching = new Fletching(PHConstruct.fletching).setUnlocalizedName("tconstruct.Fletching");
Item[] toolParts = { toolRod, toolShard, pickaxeHead, shovelHead, hatchetHead, binding, toughBinding, toughRod, largePlate, swordBlade, wideGuard, handGuard, crossbar, knifeBlade, fullGuard,
frypanHead, signHead, chiselHead, scytheBlade, broadAxeHead, excavatorHead, largeSwordBlade, hammerHead, bowstring, fletching, arrowhead };
String[] toolPartStrings = { "toolRod", "toolShard", "pickaxeHead", "shovelHead", "hatchetHead", "binding", "toughBinding", "toughRod", "heavyPlate", "swordBlade", "wideGuard", "handGuard",
"crossbar", "knifeBlade", "fullGuard", "frypanHead", "signHead", "chiselHead", "scytheBlade", "broadAxeHead", "excavatorHead", "largeSwordBlade", "hammerHead", "bowstring",
"fletching", "arrowhead" };
for (int i = 0; i < toolParts.length; i++)
{
TConstructRegistry.addItemToDirectory(toolPartStrings[i], toolParts[i]);
}
diamondApple = new DiamondApple(PHConstruct.diamondApple).setUnlocalizedName("tconstruct.apple.diamond");
strangeFood = new StrangeFood(PHConstruct.slimefood).setUnlocalizedName("tconstruct.strangefood");
oreBerries = new OreBerries(PHConstruct.oreChunks).setUnlocalizedName("oreberry");
jerky = new Jerky(PHConstruct.jerky, Loader.isModLoaded("HungerOverhaul")).setUnlocalizedName("tconstruct.jerky");
//Wearables
//heavyHelmet = new TArmorBase(PHConstruct.heavyHelmet, 0).setUnlocalizedName("tconstruct.HeavyHelmet");
heartCanister = new HeartCanister(PHConstruct.heartCanister).setUnlocalizedName("tconstruct.canister");
//heavyBoots = new TArmorBase(PHConstruct.heavyBoots, 3).setUnlocalizedName("tconstruct.HeavyBoots");
//glove = new Glove(PHConstruct.glove).setUnlocalizedName("tconstruct.Glove");
knapsack = new Knapsack(PHConstruct.knapsack).setUnlocalizedName("tconstruct.storage");
//Crystalline
essenceCrystal = new EssenceCrystal(PHConstruct.essenceCrystal).setUnlocalizedName("tconstruct.crystal.essence");
goldHead = new GoldenHead(PHConstruct.goldHead, 4, 1.2F, false).setAlwaysEdible().setPotionEffect(Potion.regeneration.id, 10, 0, 1.0F).setUnlocalizedName("goldenhead");
LiquidCasting basinCasting = TConstruct.getBasinCasting();
materialWood = EnumHelper.addArmorMaterial("WOOD", 2, new int[] { 1, 2, 2, 1 }, 3);
helmetWood = new ArmorBasic(PHConstruct.woodHelmet, materialWood, 0, "wood").setUnlocalizedName("tconstruct.helmetWood");
chestplateWood = new ArmorBasic(PHConstruct.woodChestplate, materialWood, 1, "wood").setUnlocalizedName("tconstruct.chestplateWood");
leggingsWood = new ArmorBasic(PHConstruct.woodPants, materialWood, 2, "wood").setUnlocalizedName("tconstruct.leggingsWood");
bootsWood = new ArmorBasic(PHConstruct.woodBoots, materialWood, 3, "wood").setUnlocalizedName("tconstruct.bootsWood");
spoolWire = new SpoolOfWire(PHConstruct.spoolWire).setUnlocalizedName("spoolwire");
lengthWire = new LengthWire(PHConstruct.lengthWire).setUnlocalizedName("lengthwire");
// essenceCrystal = new EssenceCrystal(PHConstruct.essenceCrystal).setUnlocalizedName("tconstruct.crystal.essence");
String[] materialStrings = { "paperStack", "greenSlimeCrystal", "searedBrick", "ingotCobalt", "ingotArdite", "ingotManyullyn", "mossBall", "lavaCrystal", "necroticBone", "ingotCopper",
"ingotTin", "ingotAluminum", "rawAluminum", "ingotBronze", "ingotAluminumBrass", "ingotAlumite", "ingotSteel", "blueSlimeCrystal", "ingotObsidian", "nuggetIron", "nuggetCopper",
"nuggetTin", "nuggetAluminum", "nuggetSilver", "nuggetAluminumBrass", "silkyCloth", "silkyJewel", "nuggetObsidian", "nuggetCobalt", "nuggetArdite", "nuggetManyullyn", "nuggetBronze",
"nuggetAlumite", "nuggetSteel" };
for (int i = 0; i < materialStrings.length; i++)
{
TConstructRegistry.addItemStackToDirectory(materialStrings[i], new ItemStack(materials, 1, i));
}
String[] oreberries = { "Iron", "Gold", "Copper", "Tin", "Aluminum", "Essence" };
for (int i = 0; i < oreberries.length; i++)
{
TConstructRegistry.addItemStackToDirectory("oreberry" + oreberries[i], new ItemStack(oreBerries, 1, i));
}
TConstructRegistry.addItemStackToDirectory("diamondApple", new ItemStack(diamondApple, 1, 0));
TConstructRegistry.addItemStackToDirectory("blueSlimeFood", new ItemStack(strangeFood, 1, 0));
TConstructRegistry.addItemStackToDirectory("canisterEmpty", new ItemStack(heartCanister, 1, 0));
TConstructRegistry.addItemStackToDirectory("miniRedHeart", new ItemStack(heartCanister, 1, 1));
TConstructRegistry.addItemStackToDirectory("canisterRedHeart", new ItemStack(heartCanister, 1, 2));
TConstructRegistry.addItemStackToDirectory("spoolWire", new ItemStack(spoolWire, 1, 0));
TConstructRegistry.addItemStackToDirectory("lengthWire", new ItemStack(lengthWire, 1, 0));
//Vanilla stack sizes
Item.doorWood.setMaxStackSize(16);
Item.doorIron.setMaxStackSize(16);
Item.snowball.setMaxStackSize(64);
Item.boat.setMaxStackSize(16);
Item.minecartEmpty.setMaxStackSize(3);
Item.minecartCrate.setMaxStackSize(3);
Item.minecartPowered.setMaxStackSize(3);
Item.itemsList[Block.cake.blockID].setMaxStackSize(16);
//Block.torchWood.setTickRandomly(false);
}
void registerMaterials ()
{
TConstructRegistry.addToolMaterial(0, "Wood", "Wooden ", 0, 59, 200, 0, 1.0F, 0, 0f, "\u00A7e", "");
TConstructRegistry.addToolMaterial(1, "Stone", 1, 131, 400, 1, 0.5F, 0, 1f, "", "Stonebound");
TConstructRegistry.addToolMaterial(2, "Iron", 2, 250, 600, 2, 1.3F, 1, 0f, "\u00A7f", "");
TConstructRegistry.addToolMaterial(3, "Flint", 1, 171, 525, 2, 0.7F, 0, 0f, "\u00A78", "");
TConstructRegistry.addToolMaterial(4, "Cactus", 1, 150, 500, 2, 1.0F, 0, -1f, "\u00A72", "Jagged");
TConstructRegistry.addToolMaterial(5, "Bone", 1, 200, 400, 1, 1.0F, 0, 0f, "\u00A7e", "");
TConstructRegistry.addToolMaterial(6, "Obsidian", 3, 89, 700, 2, 0.8F, 3, 0f, "\u00A7d", "");
TConstructRegistry.addToolMaterial(7, "Netherrack", 2, 131, 400, 1, 1.2F, 0, 1f, "\u00A74", "Stonebound");
TConstructRegistry.addToolMaterial(8, "Slime", 0, 500, 150, 0, 1.5F, 0, 0f, "\u00A7a", "");
TConstructRegistry.addToolMaterial(9, "Paper", 0, 30, 200, 0, 0.3F, 0, 0f, "\u00A7f", "Writable");
TConstructRegistry.addToolMaterial(10, "Cobalt", 4, 800, 1100, 3, 1.75F, 2, 0f, "\u00A73", "");
TConstructRegistry.addToolMaterial(11, "Ardite", 4, 600, 800, 3, 2.0F, 0, 2f, "\u00A74", "Stonebound");
TConstructRegistry.addToolMaterial(12, "Manyullyn", 5, 1200, 900, 4, 2.5F, 0, 0f, "\u00A75", "");
TConstructRegistry.addToolMaterial(13, "Copper", 1, 180, 500, 2, 1.15F, 0, 0f, "\u00A7c", "");
TConstructRegistry.addToolMaterial(14, "Bronze", 2, 350, 700, 2, 1.3F, 1, 0f, "\u00A76", "");
TConstructRegistry.addToolMaterial(15, "Alumite", 4, 550, 800, 3, 1.3F, 2, 0f, "\u00A7d", "");
TConstructRegistry.addToolMaterial(16, "Steel", 4, 750, 800, 3, 1.3F, 2, 0f, "", "");
TConstructRegistry.addToolMaterial(17, "BlueSlime", "Slime ", 0, 1200, 150, 0, 2.0F, 0, 0f, "\u00A7b", "");
TConstructRegistry.addBowMaterial(0, 384, 20, 1.0f); //Wood
TConstructRegistry.addBowMaterial(1, 10, 80, 0.2f); //Stone
TConstructRegistry.addBowMaterial(2, 576, 40, 1.2f); //Iron
TConstructRegistry.addBowMaterial(3, 10, 80, 0.2f); //Flint
TConstructRegistry.addBowMaterial(4, 384, 20, 1.0f); //Cactus
TConstructRegistry.addBowMaterial(5, 192, 30, 1.0f); //Bone
TConstructRegistry.addBowMaterial(6, 10, 80, 0.2f); //Obsidian
TConstructRegistry.addBowMaterial(7, 10, 80, 0.2f); //Netherrack
TConstructRegistry.addBowMaterial(8, 1536, 20, 1.2f); //Slime
TConstructRegistry.addBowMaterial(9, 48, 25, 0.5f); //Paper
TConstructRegistry.addBowMaterial(10, 1152, 40, 1.2f); //Cobalt
TConstructRegistry.addBowMaterial(11, 960, 40, 1.2f); //Ardite
TConstructRegistry.addBowMaterial(12, 1536, 40, 1.2f); //Manyullyn
TConstructRegistry.addBowMaterial(13, 384, 40, 1.2f); //Copper
TConstructRegistry.addBowMaterial(14, 576, 40, 1.2f); //Bronze
TConstructRegistry.addBowMaterial(15, 768, 40, 1.2f); //Alumite
TConstructRegistry.addBowMaterial(16, 768, 40, 1.2f); //Steel
TConstructRegistry.addBowMaterial(17, 576, 20, 1.2f); //Blue Slime
//Material ID, mass, fragility
TConstructRegistry.addArrowMaterial(0, 0.69F, 1.0F, 100F); //Wood
TConstructRegistry.addArrowMaterial(1, 2.5F, 5.0F, 100F); //Stone
TConstructRegistry.addArrowMaterial(2, 7.2F, 0.5F, 100F); //Iron
TConstructRegistry.addArrowMaterial(3, 2.65F, 1.0F, 100F); //Flint
TConstructRegistry.addArrowMaterial(4, 0.76F, 1.0F, 100F); //Cactus
TConstructRegistry.addArrowMaterial(5, 0.69F, 1.0F, 100); //Bone
TConstructRegistry.addArrowMaterial(6, 2.4F, 1.0F, 100F); //Obsidian
TConstructRegistry.addArrowMaterial(7, 3.5F, 1.0F, 100F); //Netherrack
TConstructRegistry.addArrowMaterial(8, 0.42F, 0.0F, 100F); //Slime
TConstructRegistry.addArrowMaterial(9, 1.1F, 3.0F, 90F); //Paper
TConstructRegistry.addArrowMaterial(10, 8.9F, 0.25F, 100F); //Cobalt
TConstructRegistry.addArrowMaterial(11, 7.2F, 0.25F, 100F); //Ardite
TConstructRegistry.addArrowMaterial(12, 10.6F, 0.1F, 100F); //Manyullyn
TConstructRegistry.addArrowMaterial(13, 8.96F, 0.5F, 100F); //Copper
TConstructRegistry.addArrowMaterial(14, 7.9F, 0.25F, 100F); //Bronze
TConstructRegistry.addArrowMaterial(15, 4.7F, 0.25F, 100F); //Alumite
TConstructRegistry.addArrowMaterial(16, 7.6F, 0.25F, 100F); //Steel
TConstructRegistry.addArrowMaterial(17, 0.42F, 0.0F, 100F); //Blue Slime
TConstructRegistry.addBowstringMaterial(0, 2, new ItemStack(Item.silk), new ItemStack(bowstring, 1, 0), 1F, 1F, 1f); //String
TConstructRegistry.addFletchingMaterial(0, 2, new ItemStack(Item.feather), new ItemStack(fletching, 1, 0), 100F, 0F, 0.05F); //Feather
for (int i = 0; i < 4; i++)
TConstructRegistry.addFletchingMaterial(1, 2, new ItemStack(Block.leaves, 1, i), new ItemStack(fletching, 1, 1), 75F, 0F, 0.2F); //All four vanialla Leaves
TConstructRegistry.addFletchingMaterial(2, 2, new ItemStack(materials, 1, 1), new ItemStack(fletching, 1, 2), 100F, 0F, 0.12F); //Slime
TConstructRegistry.addFletchingMaterial(3, 2, new ItemStack(materials, 1, 17), new ItemStack(fletching, 1, 3), 100F, 0F, 0.12F); //BlueSlime
PatternBuilder pb = PatternBuilder.instance;
if (PHConstruct.enableTWood)
pb.registerFullMaterial(Block.planks, 2, "Wood", new ItemStack(Item.stick), new ItemStack(Item.stick), 0);
else
pb.registerMaterialSet("Wood", new ItemStack(Item.stick, 2), new ItemStack(Item.stick), 0);
if (PHConstruct.enableTStone)
{
pb.registerFullMaterial(Block.stone, 2, "Stone", new ItemStack(TContent.toolShard, 1, 1), new ItemStack(TContent.toolRod, 1, 1), 1);
pb.registerMaterial(Block.cobblestone, 2, "Stone");
}
else
pb.registerMaterialSet("Stone", new ItemStack(TContent.toolShard, 1, 1), new ItemStack(TContent.toolRod, 1, 1), 0);
pb.registerFullMaterial(Item.ingotIron, 2, "Iron", new ItemStack(TContent.toolShard, 1, 2), new ItemStack(TContent.toolRod, 1, 2), 2);
if (PHConstruct.enableTFlint)
pb.registerFullMaterial(Item.flint, 2, "Flint", new ItemStack(TContent.toolShard, 1, 3), new ItemStack(TContent.toolRod, 1, 3), 3);
else
pb.registerMaterialSet("Flint", new ItemStack(TContent.toolShard, 1, 3), new ItemStack(TContent.toolRod, 1, 3), 3);
if (PHConstruct.enableTCactus)
pb.registerFullMaterial(Block.cactus, 2, "Cactus", new ItemStack(TContent.toolShard, 1, 4), new ItemStack(TContent.toolRod, 1, 4), 4);
else
pb.registerMaterialSet("Cactus", new ItemStack(TContent.toolShard, 1, 4), new ItemStack(TContent.toolRod, 1, 4), 4);
if (PHConstruct.enableTBone)
pb.registerFullMaterial(Item.bone, 2, "Bone", new ItemStack(Item.dyePowder, 1, 15), new ItemStack(Item.bone), 5);
else
pb.registerMaterialSet("Bone", new ItemStack(Item.dyePowder, 1, 15), new ItemStack(Item.bone), 5);
pb.registerFullMaterial(Block.obsidian, 2, "Obsidian", new ItemStack(TContent.toolShard, 1, 6), new ItemStack(TContent.toolRod, 1, 6), 6);
pb.registerMaterial(new ItemStack(materials, 1, 18), 2, "Obsidian");
if (PHConstruct.enableTNetherrack)
pb.registerFullMaterial(Block.netherrack, 2, "Netherrack", new ItemStack(TContent.toolShard, 1, 7), new ItemStack(TContent.toolRod, 1, 7), 7);
else
pb.registerMaterialSet("Netherrack", new ItemStack(TContent.toolShard, 1, 7), new ItemStack(TContent.toolRod, 1, 7), 7);
if (PHConstruct.enableTSlime)
pb.registerFullMaterial(new ItemStack(materials, 1, 1), 2, "Slime", new ItemStack(toolShard, 1, 8), new ItemStack(toolRod, 1, 8), 8);
else
pb.registerMaterialSet("Slime", new ItemStack(TContent.toolShard, 1, 8), new ItemStack(TContent.toolRod, 1, 17), 8);
if (PHConstruct.enableTPaper)
pb.registerFullMaterial(new ItemStack(materials, 1, 0), 2, "Paper", new ItemStack(Item.paper, 2), new ItemStack(toolRod, 1, 9), 9);
else
pb.registerMaterialSet("BlueSlime", new ItemStack(Item.paper, 2), new ItemStack(TContent.toolRod, 1, 9), 9);
pb.registerMaterialSet("Cobalt", new ItemStack(toolShard, 1, 10), new ItemStack(toolRod, 1, 10), 10);
pb.registerMaterialSet("Ardite", new ItemStack(toolShard, 1, 11), new ItemStack(toolRod, 1, 11), 11);
pb.registerMaterialSet("Manyullyn", new ItemStack(toolShard, 1, 12), new ItemStack(toolRod, 1, 12), 12);
pb.registerMaterialSet("Copper", new ItemStack(toolShard, 1, 13), new ItemStack(toolRod, 1, 13), 13);
pb.registerMaterialSet("Bronze", new ItemStack(toolShard, 1, 14), new ItemStack(toolRod, 1, 14), 14);
pb.registerMaterialSet("Alumite", new ItemStack(toolShard, 1, 15), new ItemStack(toolRod, 1, 15), 15);
pb.registerMaterialSet("Steel", new ItemStack(toolShard, 1, 16), new ItemStack(toolRod, 1, 16), 16);
if (PHConstruct.enableTBlueSlime)
pb.registerFullMaterial(new ItemStack(materials, 1, 17), 2, "BlueSlime", new ItemStack(toolShard, 1, 17), new ItemStack(toolRod, 1, 17), 17);
else
pb.registerMaterialSet("BlueSlime", new ItemStack(TContent.toolShard, 1, 17), new ItemStack(TContent.toolRod, 1, 17), 17);
pb.addToolPattern((IPattern) woodPattern);
}
public static Item[] patternOutputs;
public static FluidStack[] liquids;
void addCraftingRecipes ()
{
addPartMapping();
addRecipesForToolBuilder();
addRecipesForTableCasting();
addRecipesForBasinCasting();
addRecipesForSmeltery();
addRecipesForChisel();
addRecipesForFurnace();
addRecipesForCraftingTable();
addRecipesForDryingRack();
}
private void addRecipesForCraftingTable ()
{
String[] patBlock = { "###", "###", "###" };
String[] patSurround = { "###", "#m#", "###" };
Object[] toolForgeBlocks = { "blockIron", "blockGold", Block.blockDiamond, Block.blockEmerald, "blockCobalt", "blockArdite", "blockManyullyn", "blockCopper", "blockBronze", "blockTin",
"blockNaturalAluminum", "blockAluminumBrass", "blockAlumite", "blockSteel" };
// ToolForge Recipes (Metal Version)
for (int sc = 0; sc < toolForgeBlocks.length; sc++)
{
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolForge, 1, sc), "bbb", "msm", "m m", 'b', new ItemStack(smeltery, 1, 2), 's', new ItemStack(toolStationWood, 1, 0), 'm',
toolForgeBlocks[sc]));
// adding slab version recipe
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(craftingSlabWood, 1, 5), "bbb", "msm", "m m", 'b', new ItemStack(smeltery, 1, 2), 's', new ItemStack(craftingSlabWood, 1, 1), 'm',
toolForgeBlocks[sc]));
}
// Drawbridge Recipes
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(redstoneMachine, 1, 0), "aca", "#d#", "#r#", '#', "ingotBronze", 'a', "ingotAluminumBrass", 'c', new ItemStack(blankPattern, 1, 1),
'r', new ItemStack(Item.redstone), 'd', new ItemStack(Block.dispenser)));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(redstoneMachine, 1, 0), "aca", "#d#", "#r#", '#', "ingotBronze", 'a', "ingotAluminumBrass", 'c', new ItemStack(blankPattern, 1, 2),
'r', new ItemStack(Item.redstone), 'd', new ItemStack(Block.dispenser)));
// Igniter Recipes
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(redstoneMachine, 1, 1), "aca", "#d#", "#r#", '#', "ingotBronze", 'a', "ingotAluminumBrass", 'c', new ItemStack(largePlate, 1, 7), 'r',
new ItemStack(Item.redstone), 'd', new ItemStack(Item.flintAndSteel)));
// Advanced Drawbridge Recipes
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(redstoneMachine, 1, 2), " c ", "rdr", " a ", 'a', "ingotAluminumBrass", 'c', new ItemStack(blankPattern, 1, 1), 'r', new ItemStack(
Item.redstone), 'd', new ItemStack(redstoneMachine, 1, 0)));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(redstoneMachine, 1, 2), " c ", "rdr", " a ", 'a', "ingotAluminumBrass", 'c', new ItemStack(blankPattern, 1, 2), 'r', new ItemStack(
Item.redstone), 'd', new ItemStack(redstoneMachine, 1, 0)));
// ToolStation Recipes (Wooden Version)
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolStationWood, 1, 0), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', "crafterWood"));
GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 0), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(craftingStationWood, 1, 0));
GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 0), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(craftingSlabWood, 1, 0));
GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 2), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.wood, 1, 1));
GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 3), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.wood, 1, 2));
GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 4), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.wood, 1, 3));
GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 5), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', Block.chest);
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolStationWood, 1, 1), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', "logWood"));
if (PHConstruct.stencilTableCrafting)
{
GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 10), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.planks, 1, 0));
GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 11), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.planks, 1, 1));
GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 12), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.planks, 1, 2));
GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 13), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.planks, 1, 3));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolStationWood, 1, 10), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', "plankWood"));
}
// Blank Pattern Recipe
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(blankPattern, 1, 0), "ps", "sp", 'p', "plankWood", 's', "stickWood"));
// Manual Book Recipes
GameRegistry.addRecipe(new ItemStack(manualBook), "wp", 'w', new ItemStack(blankPattern, 1, 0), 'p', Item.paper);
GameRegistry.addShapelessRecipe(new ItemStack(manualBook, 2, 0), new ItemStack(manualBook, 1, 0), Item.book);
GameRegistry.addShapelessRecipe(new ItemStack(manualBook, 1, 1), new ItemStack(manualBook, 1, 0));
GameRegistry.addShapelessRecipe(new ItemStack(manualBook, 2, 1), new ItemStack(manualBook, 1, 1), Item.book);
GameRegistry.addShapelessRecipe(new ItemStack(manualBook, 1, 2), new ItemStack(manualBook, 1, 1));
GameRegistry.addShapelessRecipe(new ItemStack(manualBook, 2, 2), new ItemStack(manualBook, 1, 2), Item.book);
// alternativ Vanilla Book Recipe
GameRegistry.addShapelessRecipe(new ItemStack(Item.book), Item.paper, Item.paper, Item.paper, Item.silk, blankPattern, blankPattern);
// Paperstack Recipe
GameRegistry.addRecipe(new ItemStack(materials, 1, 0), "pp", "pp", 'p', Item.paper);
// Mossball Recipe
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(materials, 1, 6), patBlock, '#', "stoneMossy"));
// LavaCrystal Recipes -Auto-smelt
GameRegistry.addRecipe(new ItemStack(materials, 1, 7), "xcx", "cbc", "xcx", 'b', Item.bucketLava, 'c', Item.fireballCharge, 'x', Item.blazeRod);
GameRegistry.addRecipe(new ItemStack(materials, 1, 7), "xcx", "cbc", "xcx", 'b', Item.bucketLava, 'x', Item.fireballCharge, 'c', Item.blazeRod);
// Slimy sand Recipes
GameRegistry.addShapelessRecipe(new ItemStack(craftedSoil, 1, 0), Item.slimeBall, Item.slimeBall, Item.slimeBall, Item.slimeBall, Block.sand, Block.dirt);
GameRegistry.addShapelessRecipe(new ItemStack(craftedSoil, 1, 2), strangeFood, strangeFood, strangeFood, strangeFood, Block.sand, Block.dirt);
// Grout Recipes
GameRegistry.addShapelessRecipe(new ItemStack(craftedSoil, 2, 1), Item.clay, Block.sand, Block.gravel);
GameRegistry.addRecipe(new ItemStack(craftedSoil, 8, 1), "sgs", "gcg", "sgs", 'c', new ItemStack(Block.stainedClay, 1, Short.MAX_VALUE), 's', Block.sand, 'g', Block.gravel);
GameRegistry.addRecipe(new ItemStack(craftedSoil, 8, 1), "sgs", "gcg", "sgs", 'c', new ItemStack(Block.blockClay, 1, Short.MAX_VALUE), 's', Block.sand, 'g', Block.gravel);
// Graveyard Soil Recipes
GameRegistry.addShapelessRecipe(new ItemStack(craftedSoil, 1, 3), Block.dirt, Item.rottenFlesh, new ItemStack(Item.dyePowder, 1, 15));
// Silky Cloth Recipes
GameRegistry.addRecipe(new ItemStack(materials, 1, 25), patSurround, 'm', new ItemStack(materials, 1, 24), '#', new ItemStack(Item.silk));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(materials, 1, 25), patSurround, 'm', "nuggetGold", '#', new ItemStack(Item.silk)));
// Silky Jewel Recipes
GameRegistry.addRecipe(new ItemStack(materials, 1, 26), " c ", "cec", " c ", 'c', new ItemStack(materials, 1, 25), 'e', new ItemStack(Item.emerald));
// Ender Stuff
GameRegistry.addRecipe(new ItemStack(Item.enderPearl, 9), "m", 'm', new ItemStack(metalBlock.blockID, 1, 10));
// Wooden Armor Recipes
GameRegistry.addRecipe(new ShapedOreRecipe(helmetWood, new Object[] { "www", "w w", 'w', "logWood" }));
GameRegistry.addRecipe(new ShapedOreRecipe(chestplateWood, new Object[] { "w w", "www", "www", 'w', "logWood" }));
GameRegistry.addRecipe(new ShapedOreRecipe(leggingsWood, new Object[] { "www", "w w", "w w", 'w', "logWood" }));
GameRegistry.addRecipe(new ShapedOreRecipe(bootsWood, new Object[] { "w w", "w w", 'w', "logWood" }));
// Metal conversion Recipes
GameRegistry.addRecipe(new ItemStack(materials, 9, 9), "m", 'm', new ItemStack(metalBlock, 1, 3)); //Copper
GameRegistry.addRecipe(new ItemStack(materials, 9, 10), "m", 'm', new ItemStack(metalBlock, 1, 5)); //Tin
GameRegistry.addRecipe(new ItemStack(materials, 9, 12), "m", 'm', new ItemStack(metalBlock, 1, 6)); //Aluminum
GameRegistry.addRecipe(new ItemStack(materials, 9, 13), "m", 'm', new ItemStack(metalBlock, 1, 4)); //Bronze
GameRegistry.addRecipe(new ItemStack(materials, 9, 14), "m", 'm', new ItemStack(metalBlock, 1, 7)); //AluBrass
GameRegistry.addRecipe(new ItemStack(materials, 9, 3), "m", 'm', new ItemStack(metalBlock, 1, 0)); //Cobalt
GameRegistry.addRecipe(new ItemStack(materials, 9, 4), "m", 'm', new ItemStack(metalBlock, 1, 1)); //Ardite
GameRegistry.addRecipe(new ItemStack(materials, 9, 5), "m", 'm', new ItemStack(metalBlock, 1, 2)); //Manyullyn
GameRegistry.addRecipe(new ItemStack(materials, 9, 15), "m", 'm', new ItemStack(metalBlock, 1, 8)); //Alumite
GameRegistry.addRecipe(new ItemStack(materials, 9, 16), "m", 'm', new ItemStack(metalBlock, 1, 9)); //Steel
GameRegistry.addRecipe(new ItemStack(Item.ingotIron), patBlock, '#', new ItemStack(materials, 1, 19)); //Iron
GameRegistry.addRecipe(new ItemStack(materials, 1, 9), patBlock, '#', new ItemStack(materials, 1, 20)); //Copper
GameRegistry.addRecipe(new ItemStack(materials, 1, 10), patBlock, '#', new ItemStack(materials, 1, 21)); //Tin
GameRegistry.addRecipe(new ItemStack(materials, 1, 12), patBlock, '#', new ItemStack(materials, 1, 22)); //Aluminum
GameRegistry.addRecipe(new ItemStack(materials, 1, 14), patBlock, '#', new ItemStack(materials, 1, 24)); //Aluminum Brass
GameRegistry.addRecipe(new ItemStack(materials, 1, 18), patBlock, '#', new ItemStack(materials, 1, 27)); //Obsidian
GameRegistry.addRecipe(new ItemStack(materials, 1, 3), patBlock, '#', new ItemStack(materials, 1, 28)); //Cobalt
GameRegistry.addRecipe(new ItemStack(materials, 1, 4), patBlock, '#', new ItemStack(materials, 1, 29)); //Ardite
GameRegistry.addRecipe(new ItemStack(materials, 1, 5), patBlock, '#', new ItemStack(materials, 1, 30)); //Manyullyn
GameRegistry.addRecipe(new ItemStack(materials, 1, 13), patBlock, '#', new ItemStack(materials, 1, 31)); //Bronze
GameRegistry.addRecipe(new ItemStack(materials, 1, 15), patBlock, '#', new ItemStack(materials, 1, 32)); //Alumite
GameRegistry.addRecipe(new ItemStack(materials, 1, 16), patBlock, '#', new ItemStack(materials, 1, 33)); //Steel
GameRegistry.addRecipe(new ItemStack(materials, 9, 19), "m", 'm', new ItemStack(Item.ingotIron)); //Iron
GameRegistry.addRecipe(new ItemStack(materials, 9, 20), "m", 'm', new ItemStack(materials, 1, 9)); //Copper
GameRegistry.addRecipe(new ItemStack(materials, 9, 21), "m", 'm', new ItemStack(materials, 1, 10)); //Tin
GameRegistry.addRecipe(new ItemStack(materials, 9, 22), "m", 'm', new ItemStack(materials, 1, 12)); //Aluminum
GameRegistry.addRecipe(new ItemStack(materials, 9, 24), "m", 'm', new ItemStack(materials, 1, 14)); //Aluminum Brass
GameRegistry.addRecipe(new ItemStack(materials, 9, 27), "m", 'm', new ItemStack(materials, 1, 18)); //Obsidian
GameRegistry.addRecipe(new ItemStack(materials, 9, 28), "m", 'm', new ItemStack(materials, 1, 3)); //Cobalt
GameRegistry.addRecipe(new ItemStack(materials, 9, 29), "m", 'm', new ItemStack(materials, 1, 4)); //Ardite
GameRegistry.addRecipe(new ItemStack(materials, 9, 30), "m", 'm', new ItemStack(materials, 1, 5)); //Manyullyn
GameRegistry.addRecipe(new ItemStack(materials, 9, 31), "m", 'm', new ItemStack(materials, 1, 13)); //Bronze
GameRegistry.addRecipe(new ItemStack(materials, 9, 32), "m", 'm', new ItemStack(materials, 1, 15)); //Alumite
GameRegistry.addRecipe(new ItemStack(materials, 9, 33), "m", 'm', new ItemStack(materials, 1, 16)); //Steel
// stained Glass Recipes
String[] dyeTypes = { "dyeBlack", "dyeRed", "dyeGreen", "dyeBrown", "dyeBlue", "dyePurple", "dyeCyan", "dyeLightGray", "dyeGray", "dyePink", "dyeLime", "dyeYellow", "dyeLightBlue",
"dyeMagenta", "dyeOrange", "dyeWhite" };
String color = "";
for (int i = 0; i < 16; i++)
{
color = dyeTypes[15 - i];
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(Block.cloth, 8, i), patSurround, 'm', color, '#', new ItemStack(Block.cloth, 1, Short.MAX_VALUE)));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(stainedGlassClear, 8, i), patSurround, 'm', color, '#', clearGlass));
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(stainedGlassClear, 1, i), color, clearGlass));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(stainedGlassClear, 8, i), patSurround, 'm', color, '#', new ItemStack(stainedGlassClear, 1, Short.MAX_VALUE)));
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(stainedGlassClear, 1, i), color, new ItemStack(stainedGlassClear, 1, Short.MAX_VALUE)));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(stainedGlassClearPane, 8, i), patSurround, 'm', color, '#', glassPane));
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(stainedGlassClearPane, 1, i), color, glassPane));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(stainedGlassClearPane, 8, i), patSurround, 'm', color, '#', new ItemStack(stainedGlassClearPane, 1, Short.MAX_VALUE)));
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(stainedGlassClearPane, 1, i), color, new ItemStack(stainedGlassClearPane, 1, Short.MAX_VALUE)));
}
// Glass Recipes
GameRegistry.addRecipe(new ItemStack(Item.glassBottle, 3), new Object[] { "# #", " # ", '#', clearGlass });
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(Block.daylightSensor), new Object[] { "GGG", "QQQ", "WWW", 'G', "glass", 'Q', Item.netherQuartz, 'W', "slabWood" }));
GameRegistry.addRecipe(new ItemStack(Block.beacon, 1), new Object[] { "GGG", "GSG", "OOO", 'G', clearGlass, 'S', Item.netherStar, 'O', Block.obsidian });
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(glassPane, 16, 0), "GGG", "GGG", 'G', clearGlass));
// Smeltery Components Recipes
ItemStack searedBrick = new ItemStack(materials, 1, 2);
GameRegistry.addRecipe(new ItemStack(smeltery, 1, 0), "bbb", "b b", "bbb", 'b', searedBrick); //Controller
GameRegistry.addRecipe(new ItemStack(smeltery, 1, 1), "b b", "b b", "b b", 'b', searedBrick); //Drain
GameRegistry.addRecipe(new ItemStack(smeltery, 1, 2), "bb", "bb", 'b', searedBrick); //Bricks
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(lavaTank, 1, 0), patSurround, '#', searedBrick, 'm', "glass")); //Tank
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(lavaTank, 1, 1), "bgb", "ggg", "bgb", 'b', searedBrick, 'g', "glass")); //Glass
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(lavaTank, 1, 2), "bgb", "bgb", "bgb", 'b', searedBrick, 'g', "glass")); //Window
GameRegistry.addRecipe(new ItemStack(searedBlock, 1, 0), "bbb", "b b", "b b", 'b', searedBrick); //Table
GameRegistry.addRecipe(new ItemStack(searedBlock, 1, 1), "b b", " b ", 'b', searedBrick); //Faucet
GameRegistry.addRecipe(new ItemStack(searedBlock, 1, 2), "b b", "b b", "bbb", 'b', searedBrick); //Basin
GameRegistry.addRecipe(new ItemStack(castingChannel, 4, 0), "b b", "bbb", 'b', searedBrick); //Channel
// Jack o'Latern Recipe - Stone Torch
GameRegistry.addRecipe(new ItemStack(Block.pumpkinLantern, 1, 0), "p", "s", 'p', new ItemStack(Block.pumpkin), 's', new ItemStack(stoneTorch));
// Stone Torch Recipe
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(stoneTorch, 4), "p", "w", 'p', new ItemStack(Item.coal, 1, Short.MAX_VALUE), 'w', "stoneRod"));
// Stone Ladder Recipe
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(stoneLadder, 3), "w w", "www", "w w", 'w', "stoneRod"));
// Wooden Rail Recipe
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(woodenRail, 4, 0), "b b", "bxb", "b b", 'b', "plankWood", 'x', "stickWood"));
// Stonesticks Recipes
GameRegistry.addRecipe(new ItemStack(toolRod, 4, 1), "c", "c", 'c', new ItemStack(Block.stone));
GameRegistry.addRecipe(new ItemStack(toolRod, 2, 1), "c", "c", 'c', new ItemStack(Block.cobblestone));
//
ItemStack aluBrass = new ItemStack(materials, 1, 14);
// Clock Recipe - Vanilla alternativ
GameRegistry.addRecipe(new ItemStack(Item.pocketSundial), " i ", "iri", " i ", 'i', aluBrass, 'r', new ItemStack(Item.redstone));
// Gold Pressure Plate - Vanilla alternativ
GameRegistry.addRecipe(new ItemStack(Block.pressurePlateGold), "ii", 'i', aluBrass);
//Accessories
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(heartCanister, 1, 0), "##", "##", '#', "ingotNaturalAluminum"));
GameRegistry.addRecipe(new ItemStack(diamondApple), " d ", "d#d", " d ", 'd', new ItemStack(Item.diamond), '#', new ItemStack(Item.appleRed));
GameRegistry.addShapelessRecipe(new ItemStack(heartCanister, 1, 2), new ItemStack(diamondApple), new ItemStack(materials, 1, 8), new ItemStack(heartCanister, 1, 0), new ItemStack(
heartCanister, 1, 1));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(knapsack, 1, 0), "###", "rmr", "###", '#', new ItemStack(Item.leather), 'r', new ItemStack(toughRod, 1, 2), 'm', "ingotGold"));
GameRegistry.addRecipe(new ItemStack(knapsack, 1, 0), "###", "rmr", "###", '#', new ItemStack(Item.leather), 'r', new ItemStack(toughRod, 1, 2), 'm', aluBrass);
// Drying Rack Recipes
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(dryingRack, 1, 0), "bbb", 'b', "slabWood"));
//Landmine Recipes
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(landmine, 1, 0), "mcm", "rpr", 'm', "plankWood", 'c', new ItemStack(blankPattern, 1, 1), 'r', Item.redstone, 'p',
Block.pressurePlateStone));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(landmine, 1, 1), "mcm", "rpr", 'm', Block.stone, 'c', new ItemStack(blankPattern, 1, 1), 'r', Item.redstone, 'p',
Block.pressurePlateStone));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(landmine, 1, 2), "mcm", "rpr", 'm', Block.obsidian, 'c', new ItemStack(blankPattern, 1, 1), 'r', Item.redstone, 'p',
Block.pressurePlateStone));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(landmine, 1, 3), "mcm", "rpr", 'm', Item.redstoneRepeater, 'c', new ItemStack(blankPattern, 1, 1), 'r', Item.redstone, 'p',
Block.pressurePlateStone));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(signalBus.blockID, 1, 0), "www", "sss", 'w', lengthWire, 's', new ItemStack(Block.stoneSingleSlab, 1, OreDictionary.WILDCARD_VALUE)));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(signalTerminal.blockID, 1, 0), "b", "g", "b", 'b', new ItemStack(signalBus.blockID, 1, 0), 'g', new ItemStack(Block.glass, 1,
OreDictionary.WILDCARD_VALUE)));
GameRegistry.addRecipe(new ItemStack(lengthWire, 8), "a", "a", 'a', aluBrass);
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(spoolWire, 1, 256 - 8), "www", "wrw", "www", 'w', lengthWire, 'r', "stoneRod"));
GameRegistry.addRecipe(new SpoolRepairRecipe(new ItemStack(spoolWire, 1, 256), new ItemStack(lengthWire, 1)));
//Ultra hardcore recipes
GameRegistry.addRecipe(new ItemStack(goldHead), patSurround, '#', new ItemStack(Item.ingotGold), 'm', new ItemStack(Item.skull, 1, 3));
// Slab Smeltery Components Recipes
for (int i = 0; i < 7; i++)
{
GameRegistry.addRecipe(new ItemStack(speedSlab, 6, i), "bbb", 'b', new ItemStack(speedBlock, 1, i));
}
GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 0), "bbb", 'b', new ItemStack(smeltery, 1, 2));
GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 1), "bbb", 'b', new ItemStack(smeltery, 1, 4));
GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 2), "bbb", 'b', new ItemStack(smeltery, 1, 5));
GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 3), "bbb", 'b', new ItemStack(smeltery, 1, 6));
GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 4), "bbb", 'b', new ItemStack(smeltery, 1, 8));
GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 5), "bbb", 'b', new ItemStack(smeltery, 1, 9));
GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 6), "bbb", 'b', new ItemStack(smeltery, 1, 10));
GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 7), "bbb", 'b', new ItemStack(smeltery, 1, 11));
// Wool Slab Recipes
for (int sc = 0; sc <= 7; sc++)
{
GameRegistry.addRecipe(new ItemStack(woolSlab1, 6, sc), "www", 'w', new ItemStack(Block.cloth, 1, sc));
GameRegistry.addRecipe(new ItemStack(woolSlab2, 6, sc), "www", 'w', new ItemStack(Block.cloth, 1, sc + 8));
GameRegistry.addShapelessRecipe(new ItemStack(Block.cloth, 1, sc), new ItemStack(woolSlab1, 1, sc), new ItemStack(woolSlab1, 1, sc));
GameRegistry.addShapelessRecipe(new ItemStack(Block.cloth, 1, sc + 8), new ItemStack(woolSlab2, 1, sc), new ItemStack(woolSlab2, 1, sc));
}
GameRegistry.addRecipe(new ItemStack(woolSlab1, 6, 0), "www", 'w', new ItemStack(Block.cloth, 1, Short.MAX_VALUE));
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(Block.cloth, 1, 0), "slabCloth", "slabCloth"));
//Trap Recipes
GameRegistry.addRecipe(new ItemStack(punji, 5, 0), "b b", " b ", "b b", 'b', new ItemStack(Item.reed));
GameRegistry.addRecipe(new ItemStack(barricadeSpruce, 1, 0), "b", "b", 'b', new ItemStack(Block.wood, 1, 1));
GameRegistry.addRecipe(new ItemStack(barricadeBirch, 1, 0), "b", "b", 'b', new ItemStack(Block.wood, 1, 2));
GameRegistry.addRecipe(new ItemStack(barricadeJungle, 1, 0), "b", "b", 'b', new ItemStack(Block.wood, 1, 3));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(barricadeOak, 1, 0), "b", "b", 'b', "logWood"));
// Advanced WorkBench Recipes
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(craftingStationWood, 1, 0), "b", 'b', "crafterWood"));
//Slab crafters
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(craftingSlabWood, 6, 0), "bbb", 'b', "crafterWood"));
GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 0), "b", 'b', new ItemStack(craftingStationWood, 1, 0));
GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 1), "b", 'b', new ItemStack(toolStationWood, 1, 0));
GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 2), "b", 'b', new ItemStack(toolStationWood, 1, 1));
GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 2), "b", 'b', new ItemStack(toolStationWood, 1, 2));
GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 2), "b", 'b', new ItemStack(toolStationWood, 1, 3));
GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 2), "b", 'b', new ItemStack(toolStationWood, 1, 4));
GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 4), "b", 'b', new ItemStack(toolStationWood, 1, 5));
GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 3), "b", 'b', new ItemStack(toolStationWood, 1, 10));
GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 3), "b", 'b', new ItemStack(toolStationWood, 1, 11));
GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 3), "b", 'b', new ItemStack(toolStationWood, 1, 12));
GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 3), "b", 'b', new ItemStack(toolStationWood, 1, 13));
GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 5), "b", 'b', new ItemStack(toolForge, 1, Short.MAX_VALUE));
// EssenceExtractor Recipe
GameRegistry.addRecipe(new ItemStack(essenceExtractor, 1, 0), " b ", "eme", "mmm", 'b', Item.book, 'e', Item.emerald, 'm', Block.whiteStone);
//Slime Recipes
GameRegistry.addRecipe(new ItemStack(slimeGel, 1, 0), "##", "##", '#', strangeFood);
GameRegistry.addRecipe(new ItemStack(strangeFood, 4, 0), "#", '#', new ItemStack(slimeGel, 1, 0));
GameRegistry.addRecipe(new ItemStack(slimeGel, 1, 1), "##", "##", '#', Item.slimeBall);
GameRegistry.addRecipe(new ItemStack(Item.slimeBall, 4, 0), "#", '#', new ItemStack(slimeGel, 1, 1));
//slimeExplosive
GameRegistry.addShapelessRecipe(new ItemStack(slimeExplosive, 1, 0), Item.slimeBall, Block.tnt);
GameRegistry.addShapelessRecipe(new ItemStack(slimeExplosive, 1, 2), strangeFood, Block.tnt);
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(slimeExplosive, 1, 0), "slimeball", Block.tnt));
GameRegistry.addShapelessRecipe(new ItemStack(slimeChannel, 1, 0), new ItemStack(slimeGel, 1, Short.MAX_VALUE), new ItemStack(Item.redstone));
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(slimePad, 1, 0), slimeChannel, new ItemStack(slimeGel, 1, Short.MAX_VALUE), "slimeBall"));
}
private void addRecipesForFurnace ()
{
FurnaceRecipes.smelting().addSmelting(craftedSoil.blockID, 3, new ItemStack(craftedSoil, 1, 4), 0.2f); //Concecrated Soil
FurnaceRecipes.smelting().addSmelting(craftedSoil.blockID, 0, new ItemStack(materials, 1, 1), 2f); //Slime
FurnaceRecipes.smelting().addSmelting(craftedSoil.blockID, 1, new ItemStack(materials, 1, 2), 2f); //Seared brick item
FurnaceRecipes.smelting().addSmelting(craftedSoil.blockID, 2, new ItemStack(materials, 1, 17), 2f); //Blue Slime
//FurnaceRecipes.smelting().addSmelting(oreSlag.blockID, 1, new ItemStack(materials, 1, 3), 3f);
//FurnaceRecipes.smelting().addSmelting(oreSlag.blockID, 2, new ItemStack(materials, 1, 4), 3f);
FurnaceRecipes.smelting().addSmelting(oreSlag.blockID, 3, new ItemStack(materials, 1, 9), 0.5f);
FurnaceRecipes.smelting().addSmelting(oreSlag.blockID, 4, new ItemStack(materials, 1, 10), 0.5f);
FurnaceRecipes.smelting().addSmelting(oreSlag.blockID, 5, new ItemStack(materials, 1, 12), 0.5f);
FurnaceRecipes.smelting().addSmelting(oreBerries.itemID, 0, new ItemStack(materials, 1, 19), 0.2f);
FurnaceRecipes.smelting().addSmelting(oreBerries.itemID, 1, new ItemStack(Item.goldNugget), 0.2f);
FurnaceRecipes.smelting().addSmelting(oreBerries.itemID, 2, new ItemStack(materials, 1, 20), 0.2f);
FurnaceRecipes.smelting().addSmelting(oreBerries.itemID, 3, new ItemStack(materials, 1, 21), 0.2f);
FurnaceRecipes.smelting().addSmelting(oreBerries.itemID, 4, new ItemStack(materials, 1, 22), 0.2f);
//FurnaceRecipes.smelting().addSmelting(oreBerries.itemID, 5, new ItemStack(materials, 1, 23), 0.2f);
FurnaceRecipes.smelting().addSmelting(oreGravel.blockID, 0, new ItemStack(Item.ingotIron), 0.2f);
FurnaceRecipes.smelting().addSmelting(oreGravel.blockID, 1, new ItemStack(Item.ingotGold), 0.2f);
FurnaceRecipes.smelting().addSmelting(oreGravel.blockID, 2, new ItemStack(materials, 1, 9), 0.2f);
FurnaceRecipes.smelting().addSmelting(oreGravel.blockID, 3, new ItemStack(materials, 1, 10), 0.2f);
FurnaceRecipes.smelting().addSmelting(oreGravel.blockID, 4, new ItemStack(materials, 1, 12), 0.2f);
FurnaceRecipes.smelting().addSmelting(speedBlock.blockID, 0, new ItemStack(speedBlock, 1, 2), 0.2f);
}
private void addPartMapping ()
{
/* Tools */
patternOutputs = new Item[] { toolRod, pickaxeHead, shovelHead, hatchetHead, swordBlade, wideGuard, handGuard, crossbar, binding, frypanHead, signHead, knifeBlade, chiselHead, toughRod,
toughBinding, largePlate, broadAxeHead, scytheBlade, excavatorHead, largeSwordBlade, hammerHead, fullGuard, null, null, arrowhead };
int[] nonMetals = { 0, 1, 3, 4, 5, 6, 7, 8, 9 };
if (PHConstruct.craftMetalTools)
{
for (int mat = 0; mat < 18; mat++)
{
for (int meta = 0; meta < patternOutputs.length; meta++)
{
if (patternOutputs[meta] != null)
TConstructRegistry.addPartMapping(woodPattern.itemID, meta + 1, mat, new ItemStack(patternOutputs[meta], 1, mat));
}
}
}
else
{
for (int mat = 0; mat < nonMetals.length; mat++)
{
for (int meta = 0; meta < patternOutputs.length; meta++)
{
if (patternOutputs[meta] != null)
TConstructRegistry.addPartMapping(woodPattern.itemID, meta + 1, nonMetals[mat], new ItemStack(patternOutputs[meta], 1, nonMetals[mat]));
}
}
}
}
private void addRecipesForToolBuilder ()
{
ToolBuilder tb = ToolBuilder.instance;
tb.addNormalToolRecipe(pickaxe, pickaxeHead, toolRod, binding);
tb.addNormalToolRecipe(broadsword, swordBlade, toolRod, wideGuard);
tb.addNormalToolRecipe(hatchet, hatchetHead, toolRod);
tb.addNormalToolRecipe(shovel, shovelHead, toolRod);
tb.addNormalToolRecipe(longsword, swordBlade, toolRod, handGuard);
tb.addNormalToolRecipe(rapier, swordBlade, toolRod, crossbar);
tb.addNormalToolRecipe(frypan, frypanHead, toolRod);
tb.addNormalToolRecipe(battlesign, signHead, toolRod);
tb.addNormalToolRecipe(mattock, hatchetHead, toolRod, shovelHead);
tb.addNormalToolRecipe(dagger, knifeBlade, toolRod, crossbar);
tb.addNormalToolRecipe(cutlass, swordBlade, toolRod, fullGuard);
tb.addNormalToolRecipe(chisel, chiselHead, toolRod);
tb.addNormalToolRecipe(scythe, scytheBlade, toughRod, toughBinding, toughRod);
tb.addNormalToolRecipe(lumberaxe, broadAxeHead, toughRod, largePlate, toughBinding);
tb.addNormalToolRecipe(cleaver, largeSwordBlade, toughRod, largePlate, toughRod);
tb.addNormalToolRecipe(excavator, excavatorHead, toughRod, largePlate, toughBinding);
tb.addNormalToolRecipe(hammer, hammerHead, toughRod, largePlate, largePlate);
tb.addNormalToolRecipe(battleaxe, broadAxeHead, toughRod, broadAxeHead, toughBinding);
//tb.addNormalToolRecipe(shortbow, toolRod, bowstring, toolRod);
BowRecipe recipe = new BowRecipe(toolRod, bowstring, toolRod, shortbow);
tb.addCustomToolRecipe(recipe);
tb.addNormalToolRecipe(arrow, arrowhead, toolRod, fletching);
ItemStack diamond = new ItemStack(Item.diamond);
tb.registerToolMod(new ModRepair());
tb.registerToolMod(new ModDurability(new ItemStack[] { diamond }, 0, 500, 0f, 3, "Diamond", "\u00a7bDurability +500", "\u00a7b"));
tb.registerToolMod(new ModDurability(new ItemStack[] { new ItemStack(Item.emerald) }, 1, 0, 0.5f, 2, "Emerald", "\u00a72Durability +50%", "\u00a72"));
modE = new ModElectric();
tb.registerToolMod(modE);
ItemStack redstoneItem = new ItemStack(Item.redstone);
ItemStack redstoneBlock = new ItemStack(Block.blockRedstone);
tb.registerToolMod(new ModRedstone(new ItemStack[] { redstoneItem }, 2, 1));
tb.registerToolMod(new ModRedstone(new ItemStack[] { redstoneItem, redstoneItem }, 2, 2));
tb.registerToolMod(new ModRedstone(new ItemStack[] { redstoneBlock }, 2, 9));
tb.registerToolMod(new ModRedstone(new ItemStack[] { redstoneItem, redstoneBlock }, 2, 10));
tb.registerToolMod(new ModRedstone(new ItemStack[] { redstoneBlock, redstoneBlock }, 2, 18));
ItemStack lapisItem = new ItemStack(Item.dyePowder, 1, 4);
ItemStack lapisBlock = new ItemStack(Block.blockLapis);
modL = new ModLapis(new ItemStack[] { lapisItem }, 10, 1);
tb.registerToolMod(modL);
tb.registerToolMod(new ModLapis(new ItemStack[] { lapisItem, lapisItem }, 10, 2));
tb.registerToolMod(new ModLapis(new ItemStack[] { lapisBlock }, 10, 9));
tb.registerToolMod(new ModLapis(new ItemStack[] { lapisItem, lapisBlock }, 10, 10));
tb.registerToolMod(new ModLapis(new ItemStack[] { lapisBlock, lapisBlock }, 10, 18));
tb.registerToolMod(new ModInteger(new ItemStack[] { new ItemStack(materials, 1, 6) }, 4, "Moss", 3, "\u00a72", "Auto-Repair"));
ItemStack blazePowder = new ItemStack(Item.blazePowder);
tb.registerToolMod(new ModBlaze(new ItemStack[] { blazePowder }, 7, 1));
tb.registerToolMod(new ModBlaze(new ItemStack[] { blazePowder, blazePowder }, 7, 2));
tb.registerToolMod(new ModAutoSmelt(new ItemStack[] { new ItemStack(materials, 1, 7) }, 6, "Lava", "\u00a74", "Auto-Smelt"));
tb.registerToolMod(new ModInteger(new ItemStack[] { new ItemStack(materials, 1, 8) }, 8, "Necrotic", 1, "\u00a78", "Life Steal"));
ItemStack quartzItem = new ItemStack(Item.netherQuartz);
ItemStack quartzBlock = new ItemStack(Block.blockNetherQuartz, 1, Short.MAX_VALUE);
tb.registerToolMod(new ModAttack("Quartz", new ItemStack[] { quartzItem }, 11, 1));
tb.registerToolMod(new ModAttack("Quartz", new ItemStack[] { quartzItem, quartzItem }, 11, 2));
tb.registerToolMod(new ModAttack("Quartz", new ItemStack[] { quartzBlock }, 11, 4));
tb.registerToolMod(new ModAttack("Quartz", new ItemStack[] { quartzItem, quartzBlock }, 11, 5));
tb.registerToolMod(new ModAttack("Quartz", new ItemStack[] { quartzBlock, quartzBlock }, 11, 8));
tb.registerToolMod(new ModExtraModifier(new ItemStack[] { diamond, new ItemStack(Block.blockGold) }, "Tier1Free"));
tb.registerToolMod(new ModExtraModifier(new ItemStack[] { new ItemStack(Item.netherStar) }, "Tier2Free"));
ItemStack silkyJewel = new ItemStack(materials, 1, 26);
tb.registerToolMod(new ModButtertouch(new ItemStack[] { silkyJewel }, 12));
ItemStack piston = new ItemStack(Block.pistonBase);
tb.registerToolMod(new ModPiston(new ItemStack[] { piston }, 3, 1));
tb.registerToolMod(new ModPiston(new ItemStack[] { piston, piston }, 3, 2));
tb.registerToolMod(new ModInteger(new ItemStack[] { new ItemStack(Block.obsidian), new ItemStack(Item.enderPearl) }, 13, "Beheading", 1, "\u00a7d", "Beheading"));
ItemStack holySoil = new ItemStack(craftedSoil, 1, 4);
tb.registerToolMod(new ModSmite("Smite", new ItemStack[] { holySoil }, 14, 1));
tb.registerToolMod(new ModSmite("Smite", new ItemStack[] { holySoil, holySoil }, 14, 2));
ItemStack spidereyeball = new ItemStack(Item.fermentedSpiderEye);
tb.registerToolMod(new ModAntiSpider("Anti-Spider", new ItemStack[] { spidereyeball }, 15, 1));
tb.registerToolMod(new ModAntiSpider("Anti-Spider", new ItemStack[] { spidereyeball, spidereyeball }, 15, 2));
ItemStack obsidianPlate = new ItemStack(largePlate, 1, 6);
tb.registerToolMod(new ModReinforced(new ItemStack[] { obsidianPlate }, 16, 1));
TConstructRegistry.registerActiveToolMod(new TActiveOmniMod());
}
private void addRecipesForTableCasting ()
{
/* Smeltery */
ItemStack ingotcast = new ItemStack(metalPattern, 1, 0);
LiquidCasting tableCasting = TConstructRegistry.instance.getTableCasting();
//Blank
tableCasting.addCastingRecipe(new ItemStack(blankPattern, 1, 1), new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue), 80);
tableCasting.addCastingRecipe(new ItemStack(blankPattern, 1, 2), new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2), 80);
//Ingots
tableCasting.addCastingRecipe(new ItemStack(materials, 1, 2), new FluidStack(moltenStoneFluid, TConstruct.ingotLiquidValue), ingotcast, 80); //stone
//Buckets
ItemStack bucket = new ItemStack(Item.bucketEmpty);
for (int sc = 0; sc < 24; sc++)
{
tableCasting.addCastingRecipe(new ItemStack(buckets, 1, sc), new FluidStack(fluids[sc], FluidContainerRegistry.BUCKET_VOLUME), bucket, true, 10);
}
// Clear glass pane casting
tableCasting.addCastingRecipe(new ItemStack(glassPane), new FluidStack(moltenGlassFluid, 250), null, 80);
// Metal toolpart casting
liquids = new FluidStack[] { new FluidStack(moltenIronFluid, 1), new FluidStack(moltenCopperFluid, 1), new FluidStack(moltenCobaltFluid, 1), new FluidStack(moltenArditeFluid, 1),
new FluidStack(moltenManyullynFluid, 1), new FluidStack(moltenBronzeFluid, 1), new FluidStack(moltenAlumiteFluid, 1), new FluidStack(moltenObsidianFluid, 1),
new FluidStack(moltenSteelFluid, 1) };
int[] liquidDamage = new int[] { 2, 13, 10, 11, 12, 14, 15, 6, 16 };
int fluidAmount = 0;
Fluid fs = null;
for (int iter = 0; iter < patternOutputs.length; iter++)
{
if (patternOutputs[iter] != null)
{
ItemStack cast = new ItemStack(metalPattern, 1, iter + 1);
tableCasting.addCastingRecipe(cast, new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue), new ItemStack(patternOutputs[iter], 1, Short.MAX_VALUE), false, 50);
tableCasting.addCastingRecipe(cast, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2), new ItemStack(patternOutputs[iter], 1, Short.MAX_VALUE), false, 50);
for (int iterTwo = 0; iterTwo < liquids.length; iterTwo++)
{
fs = liquids[iterTwo].getFluid();
fluidAmount = ((IPattern) metalPattern).getPatternCost(cast) * TConstruct.ingotLiquidValue / 2;
ItemStack metalCast = new ItemStack(patternOutputs[iter], 1, liquidDamage[iterTwo]);
tableCasting.addCastingRecipe(metalCast, new FluidStack(fs, fluidAmount), cast, 50);
Smeltery.addMelting(FluidType.getFluidType(fs), metalCast, 0, fluidAmount);
}
}
}
ItemStack[] ingotShapes = { new ItemStack(Item.brick), new ItemStack(Item.netherrackBrick), new ItemStack(materials, 1, 2) };
for (int i = 0; i < ingotShapes.length; i++)
{
tableCasting.addCastingRecipe(ingotcast, new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue), ingotShapes[i], false, 50);
tableCasting.addCastingRecipe(ingotcast, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2), ingotShapes[i], false, 50);
}
ItemStack fullguardCast = new ItemStack(metalPattern, 1, 22);
tableCasting.addCastingRecipe(fullguardCast, new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue), new ItemStack(fullGuard, 1, Short.MAX_VALUE), false, 50);
tableCasting.addCastingRecipe(fullguardCast, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2), new ItemStack(fullGuard, 1, Short.MAX_VALUE), false, 50);
// Golden Food Stuff
FluidStack goldAmount = null;
if (PHConstruct.goldAppleRecipe)
{
goldAmount = new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 8);
}
else
{
goldAmount = new FluidStack(moltenGoldFluid, TConstruct.nuggetLiquidValue * 8);
}
tableCasting.addCastingRecipe(new ItemStack(Item.appleGold, 1), goldAmount, new ItemStack(Item.appleRed), true, 50);
tableCasting.addCastingRecipe(new ItemStack(Item.goldenCarrot, 1), goldAmount, new ItemStack(Item.carrot), true, 50);
tableCasting.addCastingRecipe(new ItemStack(Item.speckledMelon, 1), goldAmount, new ItemStack(Item.melon), true, 50);
tableCasting.addCastingRecipe(new ItemStack(goldHead), goldAmount, new ItemStack(Item.skull, 1, 3), true, 50);
}
private void addRecipesForBasinCasting ()
{
LiquidCasting basinCasting = TConstructRegistry.getBasinCasting();
// Block Casting
basinCasting.addCastingRecipe(new ItemStack(Block.blockIron), new FluidStack(moltenIronFluid, TConstruct.blockLiquidValue), null, true, 100); //Iron
basinCasting.addCastingRecipe(new ItemStack(Block.blockGold), new FluidStack(moltenGoldFluid, TConstruct.blockLiquidValue), null, true, 100); //gold
basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 3), new FluidStack(moltenCopperFluid, TConstruct.blockLiquidValue), null, true, 100); //copper
basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 5), new FluidStack(moltenTinFluid, TConstruct.blockLiquidValue), null, true, 100); //tin
basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 6), new FluidStack(moltenAluminumFluid, TConstruct.blockLiquidValue), null, true, 100); //aluminum
basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 0), new FluidStack(moltenCobaltFluid, TConstruct.blockLiquidValue), null, true, 100); //cobalt
basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 1), new FluidStack(moltenArditeFluid, TConstruct.blockLiquidValue), null, true, 100); //ardite
basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 4), new FluidStack(moltenBronzeFluid, TConstruct.blockLiquidValue), null, true, 100); //bronze
basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 7), new FluidStack(moltenAlubrassFluid, TConstruct.blockLiquidValue), null, true, 100); //albrass
basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 2), new FluidStack(moltenManyullynFluid, TConstruct.blockLiquidValue), null, true, 100); //manyullyn
basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 8), new FluidStack(moltenAlumiteFluid, TConstruct.blockLiquidValue), null, true, 100); //alumite
basinCasting.addCastingRecipe(new ItemStack(Block.obsidian), new FluidStack(moltenObsidianFluid, TConstruct.oreLiquidValue), null, true, 100);// obsidian
basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 9), new FluidStack(moltenSteelFluid, TConstruct.blockLiquidValue), null, true, 100); //steel
basinCasting.addCastingRecipe(new ItemStack(clearGlass, 1, 0), new FluidStack(moltenGlassFluid, FluidContainerRegistry.BUCKET_VOLUME), null, true, 100); //glass
basinCasting.addCastingRecipe(new ItemStack(smeltery, 1, 4), new FluidStack(moltenStoneFluid, TConstruct.ingotLiquidValue), null, true, 100); //seared stone
basinCasting.addCastingRecipe(new ItemStack(smeltery, 1, 5), new FluidStack(moltenStoneFluid, TConstruct.chunkLiquidValue), new ItemStack(Block.cobblestone), true, 100);
basinCasting.addCastingRecipe(new ItemStack(speedBlock, 1, 0), new FluidStack(moltenTinFluid, TConstruct.nuggetLiquidValue), new ItemStack(Block.gravel), true, 100); //brownstone
basinCasting.addCastingRecipe(new ItemStack(Block.whiteStone), new FluidStack(moltenEnderFluid, TConstruct.chunkLiquidValue), new ItemStack(Block.obsidian), true, 100); //endstone
basinCasting.addCastingRecipe(new ItemStack(metalBlock.blockID, 1, 10), new FluidStack(moltenEnderFluid, TConstruct.blockLiquidValue), null, true, 100); //ender
// basinCasting.addCastingRecipe(new ItemStack(slimeGel, 1, 0), new FluidStack(blueSlimeFluid, FluidContainerRegistry.BUCKET_VOLUME), null, true, 100);
//Armor casts
FluidRenderProperties frp = new FluidRenderProperties(Applications.BASIN.minHeight, 0.65F, Applications.BASIN);
FluidStack aluFlu = new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue * 10);
FluidStack gloFlu = new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 10);
ItemStack[] armor = { new ItemStack(helmetWood), new ItemStack(chestplateWood), new ItemStack(leggingsWood), new ItemStack(bootsWood) };
for (int sc = 0; sc < armor.length; sc++)
{
basinCasting.addCastingRecipe(new ItemStack(armorPattern, 1, sc), aluFlu, armor[sc], 50, frp);
basinCasting.addCastingRecipe(new ItemStack(armorPattern, 1, sc), gloFlu, armor[sc], 50, frp);
}
}
private void addRecipesForSmeltery ()
{
//Alloys Smelting
if (PHConstruct.harderBronze)
Smeltery.addAlloyMixing(new FluidStack(moltenBronzeFluid, 16), new FluidStack(moltenCopperFluid, 24), new FluidStack(moltenTinFluid, 8)); //Bronze
else
Smeltery.addAlloyMixing(new FluidStack(moltenBronzeFluid, 24), new FluidStack(moltenCopperFluid, 24), new FluidStack(moltenTinFluid, 8)); //Bronze
Smeltery.addAlloyMixing(new FluidStack(moltenAlubrassFluid, 32), new FluidStack(moltenAluminumFluid, 24), new FluidStack(moltenCopperFluid, 8)); //Aluminum Brass
Smeltery.addAlloyMixing(new FluidStack(moltenManyullynFluid, 16), new FluidStack(moltenCobaltFluid, 32), new FluidStack(moltenArditeFluid, 32)); //Manyullyn
Smeltery.addAlloyMixing(new FluidStack(moltenAlumiteFluid, 48), new FluidStack(moltenAluminumFluid, 80), new FluidStack(moltenIronFluid, 32), new FluidStack(moltenObsidianFluid, 32)); //Alumite
// Stone parts
for (int sc = 0; sc < patternOutputs.length; sc++)
{
if (patternOutputs[sc] != null)
{
Smeltery.addMelting(FluidType.Stone, new ItemStack(patternOutputs[sc], 1, 1), 1, (8 * ((IPattern) woodPattern).getPatternCost(new ItemStack(woodPattern, 1, sc + 1))) / 2);
}
}
// Chunks
Smeltery.addMelting(FluidType.Stone, new ItemStack(toolShard, 1, 1), 0, 4);
Smeltery.addMelting(FluidType.Iron, new ItemStack(toolShard, 1, 2), 0, TConstruct.chunkLiquidValue);
Smeltery.addMelting(FluidType.Obsidian, new ItemStack(toolShard, 1, 6), 0, TConstruct.chunkLiquidValue);
Smeltery.addMelting(FluidType.Cobalt, new ItemStack(toolShard, 1, 10), 0, TConstruct.chunkLiquidValue);
Smeltery.addMelting(FluidType.Ardite, new ItemStack(toolShard, 1, 11), 0, TConstruct.chunkLiquidValue);
Smeltery.addMelting(FluidType.Manyullyn, new ItemStack(toolShard, 1, 12), 0, TConstruct.chunkLiquidValue);
Smeltery.addMelting(FluidType.Copper, new ItemStack(toolShard, 1, 13), 0, TConstruct.chunkLiquidValue);
Smeltery.addMelting(FluidType.Bronze, new ItemStack(toolShard, 1, 14), 0, TConstruct.chunkLiquidValue);
Smeltery.addMelting(FluidType.Alumite, new ItemStack(toolShard, 1, 15), 0, TConstruct.chunkLiquidValue);
Smeltery.addMelting(FluidType.Steel, new ItemStack(toolShard, 1, 16), 0, TConstruct.chunkLiquidValue);
// Items
Smeltery.addMelting(FluidType.AluminumBrass, new ItemStack(blankPattern, 4, 1), -50, TConstruct.ingotLiquidValue);
Smeltery.addMelting(FluidType.Gold, new ItemStack(blankPattern, 4, 2), -50, TConstruct.ingotLiquidValue);
Smeltery.addMelting(FluidType.Ender, new ItemStack(Item.enderPearl, 4), 0, 250);
Smeltery.addMelting(metalBlock, 10, 50, new FluidStack(moltenEnderFluid, 1000));
Smeltery.addMelting(FluidType.Water, new ItemStack(Item.snowball, 1, 0), 0, 125);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.flintAndSteel, 1, 0), 0, TConstruct.ingotLiquidValue);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.compass, 1, 0), 0, TConstruct.ingotLiquidValue * 4);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.bucketEmpty), 0, TConstruct.ingotLiquidValue * 3);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.minecartEmpty), 0, TConstruct.ingotLiquidValue * 5);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.minecartCrate), 0, TConstruct.ingotLiquidValue * 5);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.minecartPowered), 0, TConstruct.ingotLiquidValue * 5);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.minecartHopper), 50, TConstruct.ingotLiquidValue * 10);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.doorIron), 0, TConstruct.ingotLiquidValue * 6);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.cauldron), 0, TConstruct.ingotLiquidValue * 7);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.shears), 0, TConstruct.oreLiquidValue);
// Smeltery.addMelting(FluidType.Slime, new ItemStack(slimeGel, 1, 0), 0, TConstruct.ingotLiquidValue * 4);
// Smeltery.addMelting(FluidType.Slime, new ItemStack(strangeFood, 1, 0), 0, TConstruct.ingotLiquidValue);
// Smeltery.addMelting(FluidType.Slime, new ItemStack(multiBrick, 1, 11), 0, TConstruct.ingotLiquidValue);
// Smeltery.addMelting(FluidType.Slime, new ItemStack(multiBrickFancy, 1, 11), 0, TConstruct.ingotLiquidValue);
//Blocks melt at themselves!
//Ore
Smeltery.addMelting(Block.oreIron, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 2));
Smeltery.addMelting(Block.oreGold, 0, 400, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2));
Smeltery.addMelting(oreGravel, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 2));
Smeltery.addMelting(oreGravel, 1, 400, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2));
//Blocks
Smeltery.addMelting(Block.blockIron, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 9));
Smeltery.addMelting(Block.blockGold, 0, 400, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 9));
Smeltery.addMelting(Block.obsidian, 0, 800, new FluidStack(moltenObsidianFluid, TConstruct.ingotLiquidValue * 2));
Smeltery.addMelting(Block.ice, 0, 75, new FluidStack(FluidRegistry.getFluid("water"), 1000));
Smeltery.addMelting(Block.blockSnow, 0, 75, new FluidStack(FluidRegistry.getFluid("water"), 500));
Smeltery.addMelting(Block.snow, 0, 75, new FluidStack(FluidRegistry.getFluid("water"), 250));
Smeltery.addMelting(Block.sand, 0, 625, new FluidStack(moltenGlassFluid, FluidContainerRegistry.BUCKET_VOLUME));
Smeltery.addMelting(Block.glass, 0, 625, new FluidStack(moltenGlassFluid, FluidContainerRegistry.BUCKET_VOLUME));
Smeltery.addMelting(Block.thinGlass, 0, 625, new FluidStack(moltenGlassFluid, 250));
Smeltery.addMelting(Block.stone, 0, 800, new FluidStack(moltenStoneFluid, TConstruct.ingotLiquidValue / 18));
Smeltery.addMelting(Block.cobblestone, 0, 800, new FluidStack(moltenStoneFluid, TConstruct.ingotLiquidValue / 18));
Smeltery.addMelting(clearGlass, 0, 500, new FluidStack(moltenGlassFluid, 1000));
Smeltery.addMelting(glassPane, 0, 350, new FluidStack(moltenGlassFluid, 250));
for (int i = 0; i < 16; i++)
{
Smeltery.addMelting(stainedGlassClear, i, 500, new FluidStack(moltenGlassFluid, 1000));
Smeltery.addMelting(stainedGlassClearPane, i, 350, new FluidStack(moltenGlassFluid, 250));
}
//Bricks
Smeltery.addMelting(multiBrick, 4, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue));
Smeltery.addMelting(multiBrickFancy, 4, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue));
Smeltery.addMelting(multiBrick, 5, 400, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue));
Smeltery.addMelting(multiBrickFancy, 5, 400, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue));
Smeltery.addMelting(multiBrick, 0, 800, new FluidStack(moltenObsidianFluid, TConstruct.ingotLiquidValue * 2));
Smeltery.addMelting(multiBrickFancy, 0, 800, new FluidStack(moltenObsidianFluid, TConstruct.ingotLiquidValue * 2));
//Vanilla blocks
Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.fenceIron), 0, TConstruct.ingotLiquidValue * 6 / 16);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.pressurePlateIron), 0, TConstruct.oreLiquidValue);
Smeltery.addMelting(FluidType.Gold, new ItemStack(Block.pressurePlateGold, 4), 0, TConstruct.oreLiquidValue);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.rail), 0, TConstruct.ingotLiquidValue * 6 / 16);
Smeltery.addMelting(FluidType.Gold, new ItemStack(Block.railPowered), 0, TConstruct.ingotLiquidValue);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.railDetector), 0, TConstruct.ingotLiquidValue);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.railActivator), 0, TConstruct.ingotLiquidValue);
Smeltery.addMelting(FluidType.Obsidian, new ItemStack(Block.enchantmentTable), 0, TConstruct.ingotLiquidValue * 4);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.cauldron), 0, TConstruct.ingotLiquidValue * 7);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.anvil, 1, 0), 200, TConstruct.ingotLiquidValue * 31);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.anvil, 1, 1), 200, TConstruct.ingotLiquidValue * 31);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.anvil, 1, 2), 200, TConstruct.ingotLiquidValue * 31);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.hopperBlock), 0, TConstruct.ingotLiquidValue * 5);
//Vanilla Armor
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.helmetIron, 1, 0), 50, TConstruct.ingotLiquidValue * 5);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.plateIron, 1, 0), 50, TConstruct.ingotLiquidValue * 8);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.legsIron, 1, 0), 50, TConstruct.ingotLiquidValue * 7);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.bootsIron, 1, 0), 50, TConstruct.ingotLiquidValue * 4);
Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.helmetGold, 1, 0), 50, TConstruct.ingotLiquidValue * 5);
Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.plateGold, 1, 0), 50, TConstruct.ingotLiquidValue * 8);
Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.legsGold, 1, 0), 50, TConstruct.ingotLiquidValue * 7);
Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.bootsGold, 1, 0), 50, TConstruct.ingotLiquidValue * 4);
Smeltery.addMelting(FluidType.Steel, new ItemStack(Item.helmetChain, 1, 0), 25, TConstruct.ingotLiquidValue);
Smeltery.addMelting(FluidType.Steel, new ItemStack(Item.plateChain, 1, 0), 50, TConstruct.oreLiquidValue);
Smeltery.addMelting(FluidType.Steel, new ItemStack(Item.legsChain, 1, 0), 50, TConstruct.oreLiquidValue);
Smeltery.addMelting(FluidType.Steel, new ItemStack(Item.bootsChain, 1, 0), 25, TConstruct.ingotLiquidValue);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.horseArmorIron, 1), 100, TConstruct.ingotLiquidValue * 8);
Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.horseArmorGold, 1), 100, TConstruct.ingotLiquidValue * 8);
//Vanilla tools
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.hoeIron, 1, 0), 0, TConstruct.oreLiquidValue);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.swordIron, 1, 0), 0, TConstruct.oreLiquidValue);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.shovelIron, 1, 0), 0, TConstruct.ingotLiquidValue);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.pickaxeIron, 1, 0), 0, TConstruct.ingotLiquidValue * 3);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.axeIron, 1, 0), 0, TConstruct.ingotLiquidValue * 3);
Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.hoeGold, 1, 0), 0, TConstruct.oreLiquidValue);
Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.swordGold, 1, 0), 0, TConstruct.oreLiquidValue);
Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.shovelGold, 1, 0), 0, TConstruct.ingotLiquidValue);
Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.pickaxeGold, 1, 0), 0, TConstruct.ingotLiquidValue * 3);
Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.axeGold, 1, 0), 0, TConstruct.ingotLiquidValue * 3);
}
private void addRecipesForDryingRack ()
{
//Drying rack
DryingRackRecipes.addDryingRecipe(Item.beefRaw, 20 * 60 * 5, new ItemStack(jerky, 1, 0));
DryingRackRecipes.addDryingRecipe(Item.chickenRaw, 20 * 60 * 5, new ItemStack(jerky, 1, 1));
DryingRackRecipes.addDryingRecipe(Item.porkRaw, 20 * 60 * 5, new ItemStack(jerky, 1, 2));
//DryingRackRecipes.addDryingRecipe(Item.muttonRaw, 20 * 60 * 5, new ItemStack(jerky, 1, 3));
DryingRackRecipes.addDryingRecipe(Item.fishRaw, 20 * 60 * 5, new ItemStack(jerky, 1, 4));
DryingRackRecipes.addDryingRecipe(Item.rottenFlesh, 20 * 60 * 5, new ItemStack(jerky, 1, 5));
//DryingRackRecipes.addDryingRecipe(new ItemStack(jerky, 1, 5), 20 * 60 * 10, Item.leather);
}
private void addRecipesForChisel ()
{
/* Detailing */
Detailing chiseling = TConstructRegistry.getChiselDetailing();
chiseling.addDetailing(Block.stone, 0, Block.stoneBrick, 0, chisel);
chiseling.addDetailing(speedBlock, 0, speedBlock, 1, chisel);
chiseling.addDetailing(speedBlock, 2, speedBlock, 3, chisel);
chiseling.addDetailing(speedBlock, 3, speedBlock, 4, chisel);
chiseling.addDetailing(speedBlock, 4, speedBlock, 5, chisel);
chiseling.addDetailing(speedBlock, 5, speedBlock, 6, chisel);
chiseling.addDetailing(Block.obsidian, 0, multiBrick, 0, chisel);
chiseling.addDetailing(Block.sandStone, 0, Block.sandStone, 2, chisel);
chiseling.addDetailing(Block.sandStone, 2, Block.sandStone, 1, chisel);
chiseling.addDetailing(Block.sandStone, 1, multiBrick, 1, chisel);
//chiseling.addDetailing(Block.netherrack, 0, multiBrick, 2, chisel);
//chiseling.addDetailing(Block.stone_refined, 0, multiBrick, 3, chisel);
chiseling.addDetailing(Item.ingotIron, 0, multiBrick, 4, chisel);
chiseling.addDetailing(Item.ingotGold, 0, multiBrick, 5, chisel);
chiseling.addDetailing(Item.dyePowder, 4, multiBrick, 6, chisel);
chiseling.addDetailing(Item.diamond, 0, multiBrick, 7, chisel);
chiseling.addDetailing(Item.redstone, 0, multiBrick, 8, chisel);
chiseling.addDetailing(Item.bone, 0, multiBrick, 9, chisel);
chiseling.addDetailing(Item.slimeBall, 0, multiBrick, 10, chisel);
chiseling.addDetailing(strangeFood, 0, multiBrick, 11, chisel);
chiseling.addDetailing(Block.whiteStone, 0, multiBrick, 12, chisel);
chiseling.addDetailing(materials, 18, multiBrick, 13, chisel);
// adding multiBrick / multiBrickFanxy meta 0-13 to list
for (int sc = 0; sc < 14; sc++)
{
chiseling.addDetailing(multiBrick, sc, multiBrickFancy, sc, chisel);
}
chiseling.addDetailing(Block.stoneBrick, 0, multiBrickFancy, 15, chisel);
chiseling.addDetailing(multiBrickFancy, 15, multiBrickFancy, 14, chisel);
chiseling.addDetailing(multiBrickFancy, 14, Block.stoneBrick, 3, chisel);
/*chiseling.addDetailing(multiBrick, 14, multiBrickFancy, 14, chisel);
chiseling.addDetailing(multiBrick, 15, multiBrickFancy, 15, chisel);*/
chiseling.addDetailing(smeltery, 4, smeltery, 6, chisel);
chiseling.addDetailing(smeltery, 6, smeltery, 11, chisel);
chiseling.addDetailing(smeltery, 11, smeltery, 2, chisel);
chiseling.addDetailing(smeltery, 2, smeltery, 8, chisel);
chiseling.addDetailing(smeltery, 8, smeltery, 9, chisel);
chiseling.addDetailing(smeltery, 9, smeltery, 10, chisel);
}
void setupToolTabs ()
{
TConstructRegistry.materialTab.init(new ItemStack(titleIcon, 1, 255));
TConstructRegistry.blockTab.init(new ItemStack(toolStationWood));
ItemStack tool = new ItemStack(longsword, 1, 0);
NBTTagCompound compound = new NBTTagCompound();
compound.setCompoundTag("InfiTool", new NBTTagCompound());
compound.getCompoundTag("InfiTool").setInteger("RenderHead", 2);
compound.getCompoundTag("InfiTool").setInteger("RenderHandle", 0);
compound.getCompoundTag("InfiTool").setInteger("RenderAccessory", 10);
tool.setTagCompound(compound);
//TConstruct.
TConstructRegistry.toolTab.init(tool);
}
public void addLoot ()
{
//Item, min, max, weight
ChestGenHooks.getInfo(ChestGenHooks.DUNGEON_CHEST).addItem(new WeightedRandomChestContent(new ItemStack(heartCanister, 1, 1), 1, 1, 5));
ChestGenHooks.getInfo(ChestGenHooks.PYRAMID_DESERT_CHEST).addItem(new WeightedRandomChestContent(new ItemStack(heartCanister, 1, 1), 1, 1, 10));
ChestGenHooks.getInfo(ChestGenHooks.PYRAMID_JUNGLE_CHEST).addItem(new WeightedRandomChestContent(new ItemStack(heartCanister, 1, 1), 1, 1, 10));
tinkerHouseChest = new ChestGenHooks("TinkerHouse", new WeightedRandomChestContent[0], 3, 27);
tinkerHouseChest.addItem(new WeightedRandomChestContent(new ItemStack(heartCanister, 1, 1), 1, 1, 1));
int[] validTypes = { 0, 1, 2, 3, 4, 5, 6, 8, 9, 13, 14, 17 };
Item[] partTypes = { pickaxeHead, shovelHead, hatchetHead, binding, swordBlade, wideGuard, handGuard, crossbar, knifeBlade, frypanHead, signHead, chiselHead };
for (int partIter = 0; partIter < partTypes.length; partIter++)
{
for (int typeIter = 0; typeIter < validTypes.length; typeIter++)
{
tinkerHouseChest.addItem(new WeightedRandomChestContent(new ItemStack(partTypes[partIter], 1, validTypes[typeIter]), 1, 1, 15));
}
}
tinkerHousePatterns = new ChestGenHooks("TinkerPatterns", new WeightedRandomChestContent[0], 5, 30);
for (int i = 0; i < 13; i++)
{
tinkerHousePatterns.addItem(new WeightedRandomChestContent(new ItemStack(woodPattern, 1, i + 1), 1, 3, 20));
}
tinkerHousePatterns.addItem(new WeightedRandomChestContent(new ItemStack(woodPattern, 1, 22), 1, 3, 40));
}
public static String[] liquidNames;
public void oreRegistry ()
{
OreDictionary.registerOre("oreCobalt", new ItemStack(oreSlag, 1, 1));
OreDictionary.registerOre("oreArdite", new ItemStack(oreSlag, 1, 2));
OreDictionary.registerOre("oreCopper", new ItemStack(oreSlag, 1, 3));
OreDictionary.registerOre("oreTin", new ItemStack(oreSlag, 1, 4));
OreDictionary.registerOre("oreNaturalAluminum", new ItemStack(oreSlag, 1, 5));
OreDictionary.registerOre("oreIron", new ItemStack(oreGravel, 1, 0));
OreDictionary.registerOre("oreGold", new ItemStack(oreGravel, 1, 1));
OreDictionary.registerOre("oreCobalt", new ItemStack(oreGravel, 1, 5));
OreDictionary.registerOre("oreCopper", new ItemStack(oreGravel, 1, 2));
OreDictionary.registerOre("oreTin", new ItemStack(oreGravel, 1, 3));
OreDictionary.registerOre("oreNaturalAluminum", new ItemStack(oreGravel, 1, 4));
OreDictionary.registerOre("ingotCobalt", new ItemStack(materials, 1, 3));
OreDictionary.registerOre("ingotArdite", new ItemStack(materials, 1, 4));
OreDictionary.registerOre("ingotManyullyn", new ItemStack(materials, 1, 5));
OreDictionary.registerOre("ingotCopper", new ItemStack(materials, 1, 9));
OreDictionary.registerOre("ingotTin", new ItemStack(materials, 1, 10));
OreDictionary.registerOre("ingotNaturalAluminum", new ItemStack(materials, 1, 11));
OreDictionary.registerOre("naturalAluminum", new ItemStack(materials, 1, 12));
OreDictionary.registerOre("ingotBronze", new ItemStack(materials, 1, 13));
OreDictionary.registerOre("ingotAluminumBrass", new ItemStack(materials, 1, 14));
OreDictionary.registerOre("ingotAlumite", new ItemStack(materials, 1, 15));
OreDictionary.registerOre("ingotSteel", new ItemStack(materials, 1, 16));
ensureOreIsRegistered("ingotIron", new ItemStack(Item.ingotIron));
ensureOreIsRegistered("ingotGold", new ItemStack(Item.ingotGold));
OreDictionary.registerOre("ingotObsidian", new ItemStack(materials, 1, 18));
OreDictionary.registerOre("blockCobalt", new ItemStack(metalBlock, 1, 0));
OreDictionary.registerOre("blockArdite", new ItemStack(metalBlock, 1, 1));
OreDictionary.registerOre("blockManyullyn", new ItemStack(metalBlock, 1, 2));
OreDictionary.registerOre("blockCopper", new ItemStack(metalBlock, 1, 3));
OreDictionary.registerOre("blockBronze", new ItemStack(metalBlock, 1, 4));
OreDictionary.registerOre("blockTin", new ItemStack(metalBlock, 1, 5));
OreDictionary.registerOre("blockNaturalAluminum", new ItemStack(metalBlock, 1, 6));
OreDictionary.registerOre("blockAluminumBrass", new ItemStack(metalBlock, 1, 7));
OreDictionary.registerOre("blockAlumite", new ItemStack(metalBlock, 1, 8));
OreDictionary.registerOre("blockSteel", new ItemStack(metalBlock, 1, 9));
ensureOreIsRegistered("blockIron", new ItemStack(Block.blockIron));
ensureOreIsRegistered("blockGold", new ItemStack(Block.blockGold));
OreDictionary.registerOre("nuggetIron", new ItemStack(materials, 1, 19));
OreDictionary.registerOre("nuggetIron", new ItemStack(oreBerries, 1, 0));
OreDictionary.registerOre("nuggetCopper", new ItemStack(materials, 1, 20));
OreDictionary.registerOre("nuggetCopper", new ItemStack(oreBerries, 1, 2));
OreDictionary.registerOre("nuggetTin", new ItemStack(materials, 1, 21));
OreDictionary.registerOre("nuggetTin", new ItemStack(oreBerries, 1, 3));
OreDictionary.registerOre("nuggetNaturalAluminum", new ItemStack(materials, 1, 22));
OreDictionary.registerOre("nuggetNaturalAluminum", new ItemStack(oreBerries, 1, 4));
OreDictionary.registerOre("nuggetAluminumBrass", new ItemStack(materials, 1, 24));
OreDictionary.registerOre("nuggetObsidian", new ItemStack(materials, 1, 27));
OreDictionary.registerOre("nuggetCobalt", new ItemStack(materials, 1, 28));
OreDictionary.registerOre("nuggetArdite", new ItemStack(materials, 1, 29));
OreDictionary.registerOre("nuggetManyullyn", new ItemStack(materials, 1, 30));
OreDictionary.registerOre("nuggetBronze", new ItemStack(materials, 1, 31));
OreDictionary.registerOre("nuggetAlumite", new ItemStack(materials, 1, 32));
OreDictionary.registerOre("nuggetSteel", new ItemStack(materials, 1, 33));
OreDictionary.registerOre("nuggetGold", new ItemStack(oreBerries, 1, 1));
ensureOreIsRegistered("nuggetGold", new ItemStack(Item.goldNugget));
OreDictionary.registerOre("slabCloth", new ItemStack(woolSlab1, 1, Short.MAX_VALUE));
OreDictionary.registerOre("slabCloth", new ItemStack(woolSlab2, 1, Short.MAX_VALUE));
ensureOreIsRegistered("stoneMossy", new ItemStack(Block.stoneBrick, 1, 1));
ensureOreIsRegistered("stoneMossy", new ItemStack(Block.cobblestoneMossy));
ensureOreIsRegistered("crafterWood", new ItemStack(Block.workbench, 1));
String[] matNames = { "wood", "stone", "iron", "flint", "cactus", "bone", "obsidian", "netherrack", "slime", "paper", "cobalt", "ardite", "manyullyn", "copper", "bronze", "alumite", "steel",
"blueslime" };
for (int i = 0; i < matNames.length; i++)
OreDictionary.registerOre(matNames[i] + "Rod", new ItemStack(toolRod, 1, i));
OreDictionary.registerOre("thaumiumRod", new ItemStack(toolRod, 1, 31));
String[] glassTypes = { "glassBlack", "glassRed", "glassGreen", "glassBrown", "glassBlue", "glassPurple", "glassCyan", "glassLightGray", "glassGray", "glassPink", "glassLime", "glassYellow",
"glassLightBlue", "glassMagenta", "glassOrange", "glassWhite" };
for (int i = 0; i < 16; i++)
{
OreDictionary.registerOre(glassTypes[15 - i], new ItemStack(stainedGlassClear, 1, i));
}
BlockDispenser.dispenseBehaviorRegistry.putObject(titleIcon, new TDispenserBehaviorSpawnEgg());
BlockDispenser.dispenseBehaviorRegistry.putObject(arrow, new TDispenserBehaviorArrow());
//Vanilla stuff
OreDictionary.registerOre("slimeball", new ItemStack(Item.slimeBall));
OreDictionary.registerOre("slimeball", new ItemStack(strangeFood, 1, 0));
OreDictionary.registerOre("glass", new ItemStack(clearGlass));
OreDictionary.registerOre("glass", new ItemStack(Block.glass));
RecipeRemover.removeShapedRecipe(new ItemStack(Block.pistonStickyBase));
RecipeRemover.removeShapedRecipe(new ItemStack(Item.magmaCream));
RecipeRemover.removeShapedRecipe(new ItemStack(Item.leash));
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(Block.pistonStickyBase), "slimeball", Block.pistonBase));
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(Item.magmaCream), "slimeball", Item.blazePowder));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(Item.leash, 2), "ss ", "sS ", " s", 's', Item.silk, 'S', "slimeball"));
}
private void ensureOreIsRegistered (String oreName, ItemStack is)
{
int oreId = OreDictionary.getOreID(is);
if (oreId == -1)
{
OreDictionary.registerOre(oreName, is);
}
}
public static boolean thaumcraftAvailable;
public void intermodCommunication ()
{
if (Loader.isModLoaded("Thaumcraft"))
{
FMLInterModComms.sendMessage("Thaumcraft", "harvestClickableCrop", new ItemStack(oreBerry, 1, 12));
FMLInterModComms.sendMessage("Thaumcraft", "harvestClickableCrop", new ItemStack(oreBerry, 1, 13));
FMLInterModComms.sendMessage("Thaumcraft", "harvestClickableCrop", new ItemStack(oreBerry, 1, 14));
FMLInterModComms.sendMessage("Thaumcraft", "harvestClickableCrop", new ItemStack(oreBerry, 1, 15));
FMLInterModComms.sendMessage("Thaumcraft", "harvestClickableCrop", new ItemStack(oreBerrySecond, 1, 12));
FMLInterModComms.sendMessage("Thaumcraft", "harvestClickableCrop", new ItemStack(oreBerrySecond, 1, 13));
}
if (Loader.isModLoaded("Mystcraft"))
{
MystImcHandler.blacklistFluids();
}
if (Loader.isModLoaded("BuildCraft|Transport"))
{
BCImcHandler.registerFacades();
}
/* FORESTRY
* Edit these strings to change what items are added to the backpacks
* Format info: "[backpack ID]@[item ID].[metadata or *]:[next item]" and so on
* Avaliable backpack IDs: forester, miner, digger, hunter, adventurer, builder
* May add more backpack items later - Spyboticsguy
*/
if (Loader.isModLoaded("Forestry"))
{
String builderItems = "builder@" + String.valueOf(stoneTorch.blockID) + ":*";
FMLInterModComms.sendMessage("Forestry", "add-backpack-items", builderItems);
}
if (!Loader.isModLoaded("AppliedEnergistics"))
{
AEImcHandler.registerForSpatialIO();
}
}
private static boolean initRecipes;
public static void modRecipes ()
{
if (!initRecipes)
{
initRecipes = true;
if (PHConstruct.removeVanillaToolRecipes)
{
RecipeRemover.removeAnyRecipe(new ItemStack(Item.pickaxeWood));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.axeWood));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.shovelWood));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.hoeWood));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.swordWood));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.pickaxeStone));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.axeStone));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.shovelStone));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.hoeStone));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.swordStone));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.pickaxeIron));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.axeIron));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.shovelIron));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.hoeIron));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.swordIron));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.pickaxeDiamond));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.axeDiamond));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.shovelDiamond));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.hoeDiamond));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.swordDiamond));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.pickaxeGold));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.axeGold));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.shovelGold));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.hoeGold));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.swordGold));
}
}
}
public static void addShapedRecipeFirst (List recipeList, ItemStack itemstack, Object... objArray)
{
String var3 = "";
int var4 = 0;
int var5 = 0;
int var6 = 0;
if (objArray[var4] instanceof String[])
{
String[] var7 = ((String[]) objArray[var4++]);
for (int var8 = 0; var8 < var7.length; ++var8)
{
String var9 = var7[var8];
++var6;
var5 = var9.length();
var3 = var3 + var9;
}
}
else
{
while (objArray[var4] instanceof String)
{
String var11 = (String) objArray[var4++];
++var6;
var5 = var11.length();
var3 = var3 + var11;
}
}
HashMap var12;
for (var12 = new HashMap(); var4 < objArray.length; var4 += 2)
{
Character var13 = (Character) objArray[var4];
ItemStack var14 = null;
if (objArray[var4 + 1] instanceof Item)
{
var14 = new ItemStack((Item) objArray[var4 + 1]);
}
else if (objArray[var4 + 1] instanceof Block)
{
var14 = new ItemStack((Block) objArray[var4 + 1], 1, Short.MAX_VALUE);
}
else if (objArray[var4 + 1] instanceof ItemStack)
{
var14 = (ItemStack) objArray[var4 + 1];
}
var12.put(var13, var14);
}
ItemStack[] var15 = new ItemStack[var5 * var6];
for (int var16 = 0; var16 < var5 * var6; ++var16)
{
char var10 = var3.charAt(var16);
if (var12.containsKey(Character.valueOf(var10)))
{
var15[var16] = ((ItemStack) var12.get(Character.valueOf(var10))).copy();
}
else
{
var15[var16] = null;
}
}
ShapedRecipes var17 = new ShapedRecipes(var5, var6, var15, itemstack);
recipeList.add(0, var17);
}
public void modIntegration ()
{
ItemStack ironpick = ToolBuilder.instance.buildTool(new ItemStack(TContent.pickaxeHead, 1, 6), new ItemStack(TContent.toolRod, 1, 2), new ItemStack(TContent.binding, 1, 6), "");
/* IC2 */
//ItemStack reBattery = ic2.api.item.Items.getItem("reBattery");
Object reBattery = getStaticItem("reBattery", "ic2.core.Ic2Items");
if (reBattery != null)
{
modE.batteries.add((ItemStack) reBattery);
}
//ItemStack chargedReBattery = ic2.api.item.Items.getItem("chargedReBattery");
Object chargedReBattery = getStaticItem("chargedReBattery", "ic2.core.Ic2Items");
if (chargedReBattery != null)
{
modE.batteries.add((ItemStack) chargedReBattery);
}
//ItemStack electronicCircuit = ic2.api.item.Items.getItem("electronicCircuit");
Object electronicCircuit = getStaticItem("electronicCircuit", "ic2.core.Ic2Items");
if (electronicCircuit != null)
modE.circuits.add((ItemStack) electronicCircuit);
if (chargedReBattery != null && electronicCircuit != null)
TConstructClientRegistry.registerManualModifier("electricmod", ironpick.copy(), (ItemStack) chargedReBattery, (ItemStack) electronicCircuit);
/* Thaumcraft */
Object obj = getStaticItem("itemResource", "thaumcraft.common.config.ConfigItems");
if (obj != null)
{
TConstruct.logger.info("Thaumcraft detected. Adding thaumium tools.");
thaumcraftAvailable = true;
TConstructClientRegistry.addMaterialRenderMapping(31, "tinker", "thaumium", true);
TConstructRegistry.addToolMaterial(31, "Thaumium", 3, 400, 700, 2, 1.3F, 0, 0f, "\u00A75", "Thaumic");
PatternBuilder.instance.registerFullMaterial(new ItemStack((Item) obj, 1, 2), 2, "Thaumium", new ItemStack(toolShard, 1, 31), new ItemStack(toolRod, 1, 31), 31);
for (int meta = 0; meta < patternOutputs.length; meta++)
{
if (patternOutputs[meta] != null)
TConstructRegistry.addPartMapping(woodPattern.itemID, meta + 1, 31, new ItemStack(patternOutputs[meta], 1, 31));
}
TConstructRegistry.addBowstringMaterial(1, 2, new ItemStack((Item) obj, 1, 7), new ItemStack(bowstring, 1, 1), 1F, 1F, 0.9f);
TConstructRegistry.addBowMaterial(31, 576, 40, 1.2f);
TConstructRegistry.addArrowMaterial(31, 1.8F, 0.5F, 100F);
}
else
{
TConstruct.logger.warning("Thaumcraft not detected.");
}
if (Loader.isModLoaded("Natura"))
{
try
{
Object plantItem = getStaticItem("plantItem", "mods.natura.common.NContent");
TConstructRegistry.addBowstringMaterial(2, 2, new ItemStack((Item) plantItem, 1, 7), new ItemStack(bowstring, 1, 2), 1.2F, 0.8F, 1.3f);
}
catch (Exception e)
{
} //No need to handle
}
ItemStack ingotcast = new ItemStack(metalPattern, 1, 0);
LiquidCasting tableCasting = TConstructRegistry.instance.getTableCasting();
LiquidCasting basinCasting = TConstructRegistry.instance.getBasinCasting();
/* Thermal Expansion */
ArrayList<ItemStack> ores = OreDictionary.getOres("ingotNickel");
if (ores.size() > 0)
{
tableCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenNickelFluid, TConstruct.ingotLiquidValue), ingotcast, 80);
}
ores = OreDictionary.getOres("ingotLead");
if (ores.size() > 0)
{
tableCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenLeadFluid, TConstruct.ingotLiquidValue), ingotcast, 80);
}
ores = OreDictionary.getOres("ingotSilver");
if (ores.size() > 0)
{
tableCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenSilverFluid, TConstruct.ingotLiquidValue), ingotcast, 80);
}
ores = OreDictionary.getOres("ingotPlatinum");
if (ores.size() > 0)
{
tableCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenShinyFluid, TConstruct.ingotLiquidValue), ingotcast, 80);
}
ores = OreDictionary.getOres("ingotInvar");
if (ores.size() > 0)
{
tableCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenInvarFluid, TConstruct.ingotLiquidValue), ingotcast, 80);
Smeltery.addAlloyMixing(new FluidStack(moltenInvarFluid, 24), new FluidStack(moltenIronFluid, 16), new FluidStack(moltenNickelFluid, 8)); //Invar
}
ores = OreDictionary.getOres("ingotElectrum");
if (ores.size() > 0)
{
tableCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenElectrumFluid, TConstruct.ingotLiquidValue), ingotcast, 80);
Smeltery.addAlloyMixing(new FluidStack(moltenElectrumFluid, 16), new FluidStack(moltenGoldFluid, 8), new FluidStack(moltenSilverFluid, 8)); //Electrum
}
ores = OreDictionary.getOres("blockNickel");
if (ores.size() > 0)
{
basinCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenNickelFluid, TConstruct.blockLiquidValue), null, 100);
}
ores = OreDictionary.getOres("blockLead");
if (ores.size() > 0)
{
basinCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenLeadFluid, TConstruct.blockLiquidValue), null, 100);
}
ores = OreDictionary.getOres("blockSilver");
if (ores.size() > 0)
{
basinCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenSilverFluid, TConstruct.blockLiquidValue), null, 100);
}
ores = OreDictionary.getOres("blockPlatinum");
if (ores.size() > 0)
{
basinCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenShinyFluid, TConstruct.blockLiquidValue), null, 100);
}
ores = OreDictionary.getOres("blockInvar");
if (ores.size() > 0)
{
basinCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenInvarFluid, TConstruct.blockLiquidValue), null, 100);
}
ores = OreDictionary.getOres("blockElectrum");
if (ores.size() > 0)
{
basinCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenElectrumFluid, TConstruct.blockLiquidValue), null, 100);
}
}
public static Object getStaticItem (String name, String classPackage)
{
try
{
Class clazz = Class.forName(classPackage);
Field field = clazz.getDeclaredField(name);
Object ret = field.get(null);
if (ret != null && (ret instanceof ItemStack || ret instanceof Item))
return ret;
return null;
}
catch (Exception e)
{
TConstruct.logger.warning("Could not find " + name);
return null;
}
}
@Override
public int getBurnTime (ItemStack fuel)
{
if (fuel.itemID == materials.itemID && fuel.getItemDamage() == 7)
return 26400;
if (fuel.itemID == woodPattern.itemID)
return 800;
return 0;
}
public void addOreDictionarySmelteryRecipes ()
{
List<FluidType> exceptions = Arrays.asList(new FluidType[] { FluidType.Water, FluidType.Stone, FluidType.Ender, FluidType.Glass, FluidType.Slime });
for (FluidType ft : FluidType.values())
{
if (exceptions.contains(ft))
continue;
// Nuggets
Smeltery.addDictionaryMelting("nugget" + ft.toString(), ft, -100, TConstruct.nuggetLiquidValue);
// Ingots, Dust
registerIngotCasting(ft);
Smeltery.addDictionaryMelting("ingot" + ft.toString(), ft, -50, TConstruct.ingotLiquidValue);
Smeltery.addDictionaryMelting("dust" + ft.toString(), ft, -75, TConstruct.ingotLiquidValue);
// Factorization support
Smeltery.addDictionaryMelting("crystalline" + ft.toString(), ft, -50, TConstruct.ingotLiquidValue);
// Ores
Smeltery.addDictionaryMelting("ore" + ft.toString(), ft, 0, TConstruct.oreLiquidValue);
// NetherOres support
Smeltery.addDictionaryMelting("oreNether" + ft.toString(), ft, 75, TConstruct.oreLiquidValue * 2);
// Blocks
Smeltery.addDictionaryMelting("block" + ft.toString(), ft, 100, TConstruct.blockLiquidValue);
if (ft.isToolpart)
{
registerPatternMaterial("ingot" + ft.toString(), 2, ft.toString());
registerPatternMaterial("block" + ft.toString(), 18, ft.toString());
}
}
registerPatternMaterial("plankWood", 2, "Wood");
registerPatternMaterial("stickWood", 1, "Wood");
registerPatternMaterial("slabWood", 1, "Wood");
}
private void registerPatternMaterial (String oreName, int value, String materialName)
{
for (ItemStack ore : OreDictionary.getOres(oreName))
{
PatternBuilder.instance.registerMaterial(ore, value, materialName);
}
}
private void registerIngotCasting (FluidType ft)
{
ItemStack pattern = new ItemStack(TContent.metalPattern, 1, 0);
LiquidCasting tableCasting = TConstructRegistry.instance.getTableCasting();
for (ItemStack ore : OreDictionary.getOres("ingot" + ft.toString()))
{
tableCasting.addCastingRecipe(pattern, new FluidStack(TContent.moltenAlubrassFluid, TConstruct.ingotLiquidValue), new ItemStack(ore.itemID, 1, ore.getItemDamage()), false, 50);
tableCasting.addCastingRecipe(pattern, new FluidStack(TContent.moltenGoldFluid, TConstruct.oreLiquidValue), new ItemStack(ore.itemID, 1, ore.getItemDamage()), false, 50);
tableCasting.addCastingRecipe(new ItemStack(ore.itemID, 1, ore.getItemDamage()), new FluidStack(ft.fluid, TConstruct.ingotLiquidValue), pattern, 80);
}
}
}
| void registerBlocks ()
{
//Tool Station
toolStationWood = new ToolStationBlock(PHConstruct.woodStation, Material.wood).setUnlocalizedName("ToolStation");
GameRegistry.registerBlock(toolStationWood, ToolStationItemBlock.class, "ToolStationBlock");
GameRegistry.registerTileEntity(ToolStationLogic.class, "ToolStation");
GameRegistry.registerTileEntity(PartBuilderLogic.class, "PartCrafter");
GameRegistry.registerTileEntity(PatternChestLogic.class, "PatternHolder");
GameRegistry.registerTileEntity(StencilTableLogic.class, "PatternShaper");
toolForge = new ToolForgeBlock(PHConstruct.toolForge, Material.iron).setUnlocalizedName("ToolForge");
GameRegistry.registerBlock(toolForge, MetadataItemBlock.class, "ToolForgeBlock");
GameRegistry.registerTileEntity(ToolForgeLogic.class, "ToolForge");
craftingStationWood = new CraftingStationBlock(PHConstruct.woodCrafter, Material.wood).setUnlocalizedName("CraftingStation");
GameRegistry.registerBlock(craftingStationWood, "CraftingStation");
GameRegistry.registerTileEntity(CraftingStationLogic.class, "CraftingStation");
craftingSlabWood = new CraftingSlab(PHConstruct.woodCrafterSlab, Material.wood).setUnlocalizedName("CraftingSlab");
GameRegistry.registerBlock(craftingSlabWood, CraftingSlabItemBlock.class, "CraftingSlab");
heldItemBlock = new EquipBlock(PHConstruct.heldItemBlock, Material.wood).setUnlocalizedName("Frypan");
GameRegistry.registerBlock(heldItemBlock, "HeldItemBlock");
GameRegistry.registerTileEntity(FrypanLogic.class, "FrypanLogic");
craftedSoil = new SoilBlock(PHConstruct.craftedSoil).setLightOpacity(0).setUnlocalizedName("TConstruct.Soil");
craftedSoil.stepSound = Block.soundGravelFootstep;
GameRegistry.registerBlock(craftedSoil, CraftedSoilItemBlock.class, "CraftedSoil");
searedSlab = new SearedSlab(PHConstruct.searedSlab).setUnlocalizedName("SearedSlab");
searedSlab.stepSound = Block.soundStoneFootstep;
GameRegistry.registerBlock(searedSlab, SearedSlabItem.class, "SearedSlab");
speedSlab = new SpeedSlab(PHConstruct.speedSlab).setUnlocalizedName("SpeedSlab");
speedSlab.stepSound = Block.soundStoneFootstep;
GameRegistry.registerBlock(speedSlab, SpeedSlabItem.class, "SpeedSlab");
metalBlock = new TMetalBlock(PHConstruct.metalBlock, Material.iron, 10.0F).setUnlocalizedName("tconstruct.metalblock");
metalBlock.stepSound = Block.soundMetalFootstep;
GameRegistry.registerBlock(metalBlock, MetalItemBlock.class, "MetalBlock");
meatBlock = new MeatBlock(PHConstruct.meatBlock).setUnlocalizedName("tconstruct.meatblock");
GameRegistry.registerBlock(meatBlock, "MeatBlock");
OreDictionary.registerOre("hambone", new ItemStack(meatBlock));
LanguageRegistry.addName(meatBlock, "Hambone");
GameRegistry.addRecipe(new ItemStack(meatBlock), "mmm", "mbm", "mmm", 'b', new ItemStack(Item.bone), 'm', new ItemStack(Item.porkRaw));
woolSlab1 = new SlabBase(PHConstruct.woolSlab1, Material.cloth, Block.cloth, 0, 8).setUnlocalizedName("cloth");
woolSlab1.setStepSound(Block.soundClothFootstep).setCreativeTab(CreativeTabs.tabDecorations);
GameRegistry.registerBlock(woolSlab1, WoolSlab1Item.class, "WoolSlab1");
woolSlab2 = new SlabBase(PHConstruct.woolSlab2, Material.cloth, Block.cloth, 8, 8).setUnlocalizedName("cloth");
woolSlab2.setStepSound(Block.soundClothFootstep).setCreativeTab(CreativeTabs.tabDecorations);
GameRegistry.registerBlock(woolSlab2, WoolSlab2Item.class, "WoolSlab2");
//Smeltery
smeltery = new SmelteryBlock(PHConstruct.smeltery).setUnlocalizedName("Smeltery");
GameRegistry.registerBlock(smeltery, SmelteryItemBlock.class, "Smeltery");
if (PHConstruct.newSmeltery)
{
GameRegistry.registerTileEntity(AdaptiveSmelteryLogic.class, "TConstruct.Smeltery");
GameRegistry.registerTileEntity(AdaptiveDrainLogic.class, "TConstruct.SmelteryDrain");
}
else
{
GameRegistry.registerTileEntity(SmelteryLogic.class, "TConstruct.Smeltery");
GameRegistry.registerTileEntity(SmelteryDrainLogic.class, "TConstruct.SmelteryDrain");
}
GameRegistry.registerTileEntity(MultiServantLogic.class, "TConstruct.Servants");
lavaTank = new LavaTankBlock(PHConstruct.lavaTank).setUnlocalizedName("LavaTank");
lavaTank.setStepSound(Block.soundGlassFootstep);
GameRegistry.registerBlock(lavaTank, LavaTankItemBlock.class, "LavaTank");
GameRegistry.registerTileEntity(LavaTankLogic.class, "TConstruct.LavaTank");
searedBlock = new SearedBlock(PHConstruct.searedTable).setUnlocalizedName("SearedBlock");
GameRegistry.registerBlock(searedBlock, SearedTableItemBlock.class, "SearedBlock");
GameRegistry.registerTileEntity(CastingTableLogic.class, "CastingTable");
GameRegistry.registerTileEntity(FaucetLogic.class, "Faucet");
GameRegistry.registerTileEntity(CastingBasinLogic.class, "CastingBasin");
castingChannel = (new CastingChannelBlock(PHConstruct.castingChannel)).setUnlocalizedName("CastingChannel");
GameRegistry.registerBlock(castingChannel, CastingChannelItem.class, "CastingChannel");
GameRegistry.registerTileEntity(CastingChannelLogic.class, "CastingChannel");
tankAir = new TankAirBlock(PHConstruct.airTank, Material.leaves).setBlockUnbreakable().setUnlocalizedName("tconstruct.tank.air");
GameRegistry.registerBlock(tankAir, "TankAir");
GameRegistry.registerTileEntity(TankAirLogic.class, "tconstruct.tank.air");
//Redstone machines
redstoneMachine = new RedstoneMachine(PHConstruct.redstoneMachine).setUnlocalizedName("Redstone.Machine");
GameRegistry.registerBlock(redstoneMachine, RedstoneMachineItem.class, "Redstone.Machine");
GameRegistry.registerTileEntity(DrawbridgeLogic.class, "Drawbridge");
GameRegistry.registerTileEntity(FirestarterLogic.class, "Firestarter");
GameRegistry.registerTileEntity(AdvancedDrawbridgeLogic.class, "AdvDrawbridge");
//Traps
landmine = new BlockLandmine(PHConstruct.landmine).setHardness(0.5F).setResistance(0F).setStepSound(Block.soundMetalFootstep).setCreativeTab(CreativeTabs.tabRedstone)
.setUnlocalizedName("landmine");
GameRegistry.registerBlock(landmine, ItemBlockLandmine.class, "Redstone.Landmine");
GameRegistry.registerTileEntity(TileEntityLandmine.class, "Landmine");
punji = new Punji(PHConstruct.punji).setUnlocalizedName("trap.punji");
GameRegistry.registerBlock(punji, "trap.punji");
barricadeOak = new BarricadeBlock(PHConstruct.barricadeOak, Block.wood, 0).setUnlocalizedName("trap.barricade.oak");
GameRegistry.registerBlock(barricadeOak, BarricadeItem.class, "trap.barricade.oak");
barricadeSpruce = new BarricadeBlock(PHConstruct.barricadeSpruce, Block.wood, 1).setUnlocalizedName("trap.barricade.spruce");
GameRegistry.registerBlock(barricadeSpruce, BarricadeItem.class, "trap.barricade.spruce");
barricadeBirch = new BarricadeBlock(PHConstruct.barricadeBirch, Block.wood, 2).setUnlocalizedName("trap.barricade.birch");
GameRegistry.registerBlock(barricadeBirch, BarricadeItem.class, "trap.barricade.birch");
barricadeJungle = new BarricadeBlock(PHConstruct.barricadeJungle, Block.wood, 3).setUnlocalizedName("trap.barricade.jungle");
GameRegistry.registerBlock(barricadeJungle, BarricadeItem.class, "trap.barricade.jungle");
slimeExplosive = new SlimeExplosive(PHConstruct.slimeExplosive).setHardness(0.0F).setStepSound(Block.soundGrassFootstep).setUnlocalizedName("explosive.slime");
GameRegistry.registerBlock(slimeExplosive, MetadataItemBlock.class, "explosive.slime");
dryingRack = new DryingRack(PHConstruct.dryingRack).setUnlocalizedName("Armor.DryingRack");
GameRegistry.registerBlock(dryingRack, "Armor.DryingRack");
GameRegistry.registerTileEntity(DryingRackLogic.class, "Armor.DryingRack");
//Liquids
liquidMetal = new MaterialLiquid(MapColor.tntColor);
moltenIronFluid = new Fluid("iron.molten");
if (!FluidRegistry.registerFluid(moltenIronFluid))
moltenIronFluid = FluidRegistry.getFluid("iron.molten");
moltenIron = new TConstructFluid(PHConstruct.moltenIron, moltenIronFluid, Material.lava, "liquid_iron").setUnlocalizedName("metal.molten.iron");
GameRegistry.registerBlock(moltenIron, "metal.molten.iron");
fluids[0] = moltenIronFluid;
fluidBlocks[0] = moltenIron;
moltenIronFluid.setBlockID(moltenIron).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenIronFluid, 1000), new ItemStack(buckets, 1, 0), new ItemStack(Item.bucketEmpty)));
moltenGoldFluid = new Fluid("gold.molten");
if (!FluidRegistry.registerFluid(moltenGoldFluid))
moltenGoldFluid = FluidRegistry.getFluid("gold.molten");
moltenGold = new TConstructFluid(PHConstruct.moltenGold, moltenGoldFluid, Material.lava, "liquid_gold").setUnlocalizedName("metal.molten.gold");
GameRegistry.registerBlock(moltenGold, "metal.molten.gold");
fluids[1] = moltenGoldFluid;
fluidBlocks[1] = moltenGold;
moltenGoldFluid.setBlockID(moltenGold).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenGoldFluid, 1000), new ItemStack(buckets, 1, 1), new ItemStack(Item.bucketEmpty)));
moltenCopperFluid = new Fluid("copper.molten");
if (!FluidRegistry.registerFluid(moltenCopperFluid))
moltenCopperFluid = FluidRegistry.getFluid("copper.molten");
moltenCopper = new TConstructFluid(PHConstruct.moltenCopper, moltenCopperFluid, Material.lava, "liquid_copper").setUnlocalizedName("metal.molten.copper");
GameRegistry.registerBlock(moltenCopper, "metal.molten.copper");
fluids[2] = moltenCopperFluid;
fluidBlocks[2] = moltenCopper;
moltenCopperFluid.setBlockID(moltenCopper).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenCopperFluid, 1000), new ItemStack(buckets, 1, 2), new ItemStack(Item.bucketEmpty)));
moltenTinFluid = new Fluid("tin.molten");
if (!FluidRegistry.registerFluid(moltenTinFluid))
moltenTinFluid = FluidRegistry.getFluid("tin.molten");
moltenTin = new TConstructFluid(PHConstruct.moltenTin, moltenTinFluid, Material.lava, "liquid_tin").setUnlocalizedName("metal.molten.tin");
GameRegistry.registerBlock(moltenTin, "metal.molten.tin");
fluids[3] = moltenTinFluid;
fluidBlocks[3] = moltenTin;
moltenTinFluid.setBlockID(moltenTin).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenTinFluid, 1000), new ItemStack(buckets, 1, 3), new ItemStack(Item.bucketEmpty)));
moltenAluminumFluid = new Fluid("aluminum.molten");
if (!FluidRegistry.registerFluid(moltenAluminumFluid))
moltenAluminumFluid = FluidRegistry.getFluid("aluminum.molten");
moltenAluminum = new TConstructFluid(PHConstruct.moltenAluminum, moltenAluminumFluid, Material.lava, "liquid_aluminum").setUnlocalizedName("metal.molten.aluminum");
GameRegistry.registerBlock(moltenAluminum, "metal.molten.aluminum");
fluids[4] = moltenAluminumFluid;
fluidBlocks[4] = moltenAluminum;
moltenAluminumFluid.setBlockID(moltenAluminum).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenAluminumFluid, 1000), new ItemStack(buckets, 1, 4), new ItemStack(Item.bucketEmpty)));
moltenCobaltFluid = new Fluid("cobalt.molten");
if (!FluidRegistry.registerFluid(moltenCobaltFluid))
moltenCobaltFluid = FluidRegistry.getFluid("cobalt.molten");
moltenCobalt = new TConstructFluid(PHConstruct.moltenCobalt, moltenCobaltFluid, Material.lava, "liquid_cobalt").setUnlocalizedName("metal.molten.cobalt");
GameRegistry.registerBlock(moltenCobalt, "metal.molten.cobalt");
fluids[5] = moltenCobaltFluid;
fluidBlocks[5] = moltenCobalt;
moltenCobaltFluid.setBlockID(moltenCobalt).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenCobaltFluid, 1000), new ItemStack(buckets, 1, 5), new ItemStack(Item.bucketEmpty)));
moltenArditeFluid = new Fluid("ardite.molten");
if (!FluidRegistry.registerFluid(moltenArditeFluid))
moltenArditeFluid = FluidRegistry.getFluid("ardite.molten");
moltenArdite = new TConstructFluid(PHConstruct.moltenArdite, moltenArditeFluid, Material.lava, "liquid_ardite").setUnlocalizedName("metal.molten.ardite");
GameRegistry.registerBlock(moltenArdite, "metal.molten.ardite");
fluids[6] = moltenArditeFluid;
fluidBlocks[6] = moltenArdite;
moltenArditeFluid.setBlockID(moltenArdite).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenArditeFluid, 1000), new ItemStack(buckets, 1, 6), new ItemStack(Item.bucketEmpty)));
moltenBronzeFluid = new Fluid("bronze.molten");
if (!FluidRegistry.registerFluid(moltenBronzeFluid))
moltenBronzeFluid = FluidRegistry.getFluid("bronze.molten");
moltenBronze = new TConstructFluid(PHConstruct.moltenBronze, moltenBronzeFluid, Material.lava, "liquid_bronze").setUnlocalizedName("metal.molten.bronze");
GameRegistry.registerBlock(moltenBronze, "metal.molten.bronze");
fluids[7] = moltenBronzeFluid;
fluidBlocks[7] = moltenBronze;
moltenBronzeFluid.setBlockID(moltenBronze).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenBronzeFluid, 1000), new ItemStack(buckets, 1, 7), new ItemStack(Item.bucketEmpty)));
moltenAlubrassFluid = new Fluid("aluminumbrass.molten");
if (!FluidRegistry.registerFluid(moltenAlubrassFluid))
moltenAlubrassFluid = FluidRegistry.getFluid("aluminumbrass.molten");
moltenAlubrass = new TConstructFluid(PHConstruct.moltenAlubrass, moltenAlubrassFluid, Material.lava, "liquid_alubrass").setUnlocalizedName("metal.molten.alubrass");
GameRegistry.registerBlock(moltenAlubrass, "metal.molten.alubrass");
fluids[8] = moltenAlubrassFluid;
fluidBlocks[8] = moltenAlubrass;
moltenAlubrassFluid.setBlockID(moltenAlubrass).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenAlubrassFluid, 1000), new ItemStack(buckets, 1, 8), new ItemStack(Item.bucketEmpty)));
moltenManyullynFluid = new Fluid("manyullyn.molten");
if (!FluidRegistry.registerFluid(moltenManyullynFluid))
moltenManyullynFluid = FluidRegistry.getFluid("manyullyn.molten");
moltenManyullyn = new TConstructFluid(PHConstruct.moltenManyullyn, moltenManyullynFluid, Material.lava, "liquid_manyullyn").setUnlocalizedName("metal.molten.manyullyn");
GameRegistry.registerBlock(moltenManyullyn, "metal.molten.manyullyn");
fluids[9] = moltenManyullynFluid;
fluidBlocks[9] = moltenManyullyn;
moltenManyullynFluid.setBlockID(moltenManyullyn).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenManyullynFluid, 1000), new ItemStack(buckets, 1, 9), new ItemStack(Item.bucketEmpty)));
moltenAlumiteFluid = new Fluid("alumite.molten");
if (!FluidRegistry.registerFluid(moltenAlumiteFluid))
moltenAlumiteFluid = FluidRegistry.getFluid("alumite.molten");
moltenAlumite = new TConstructFluid(PHConstruct.moltenAlumite, moltenAlumiteFluid, Material.lava, "liquid_alumite").setUnlocalizedName("metal.molten.alumite");
GameRegistry.registerBlock(moltenAlumite, "metal.molten.alumite");
fluids[10] = moltenAlumiteFluid;
fluidBlocks[10] = moltenAlumite;
moltenAlumiteFluid.setBlockID(moltenAlumite).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenAlumiteFluid, 1000), new ItemStack(buckets, 1, 10), new ItemStack(Item.bucketEmpty)));
moltenObsidianFluid = new Fluid("obsidian.molten");
if (!FluidRegistry.registerFluid(moltenObsidianFluid))
moltenObsidianFluid = FluidRegistry.getFluid("obsidian.molten");
moltenObsidian = new TConstructFluid(PHConstruct.moltenObsidian, moltenObsidianFluid, Material.lava, "liquid_obsidian").setUnlocalizedName("metal.molten.obsidian");
GameRegistry.registerBlock(moltenObsidian, "metal.molten.obsidian");
fluids[11] = moltenObsidianFluid;
fluidBlocks[11] = moltenObsidian;
moltenObsidianFluid.setBlockID(moltenObsidian).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenObsidianFluid, 1000), new ItemStack(buckets, 1, 11), new ItemStack(Item.bucketEmpty)));
moltenSteelFluid = new Fluid("steel.molten");
if (!FluidRegistry.registerFluid(moltenSteelFluid))
moltenSteelFluid = FluidRegistry.getFluid("steel.molten");
moltenSteel = new TConstructFluid(PHConstruct.moltenSteel, moltenSteelFluid, Material.lava, "liquid_steel").setUnlocalizedName("metal.molten.steel");
GameRegistry.registerBlock(moltenSteel, "metal.molten.steel");
fluids[12] = moltenSteelFluid;
fluidBlocks[12] = moltenSteel;
moltenSteelFluid.setBlockID(moltenSteel).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenSteelFluid, 1000), new ItemStack(buckets, 1, 12), new ItemStack(Item.bucketEmpty)));
moltenGlassFluid = new Fluid("glass.molten");
if (!FluidRegistry.registerFluid(moltenGlassFluid))
moltenGlassFluid = FluidRegistry.getFluid("glass.molten");
moltenGlass = new TConstructFluid(PHConstruct.moltenGlass, moltenGlassFluid, Material.lava, "liquid_glass", true).setUnlocalizedName("metal.molten.glass");
GameRegistry.registerBlock(moltenGlass, "metal.molten.glass");
fluids[13] = moltenGlassFluid;
fluidBlocks[13] = moltenGlass;
moltenGlassFluid.setBlockID(moltenGlass).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenGlassFluid, 1000), new ItemStack(buckets, 1, 13), new ItemStack(Item.bucketEmpty)));
moltenStoneFluid = new Fluid("stone.seared");
if (!FluidRegistry.registerFluid(moltenStoneFluid))
moltenStoneFluid = FluidRegistry.getFluid("stone.seared");
moltenStone = new TConstructFluid(PHConstruct.moltenStone, moltenStoneFluid, Material.lava, "liquid_stone").setUnlocalizedName("molten.stone");
GameRegistry.registerBlock(moltenStone, "molten.stone");
fluids[14] = moltenStoneFluid;
fluidBlocks[14] = moltenStone;
moltenStoneFluid.setBlockID(moltenStone).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenStoneFluid, 1000), new ItemStack(buckets, 1, 14), new ItemStack(Item.bucketEmpty)));
moltenEmeraldFluid = new Fluid("emerald.liquid");
if (!FluidRegistry.registerFluid(moltenEmeraldFluid))
moltenEmeraldFluid = FluidRegistry.getFluid("emerald.liquid");
moltenEmerald = new TConstructFluid(PHConstruct.moltenEmerald, moltenEmeraldFluid, Material.water, "liquid_villager").setUnlocalizedName("molten.emerald");
GameRegistry.registerBlock(moltenEmerald, "molten.emerald");
fluids[15] = moltenEmeraldFluid;
fluidBlocks[15] = moltenEmerald;
moltenEmeraldFluid.setBlockID(moltenEmerald).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenEmeraldFluid, 1000), new ItemStack(buckets, 1, 15), new ItemStack(Item.bucketEmpty)));
bloodFluid = new Fluid("blood");
if (!FluidRegistry.registerFluid(bloodFluid))
bloodFluid = FluidRegistry.getFluid("blood");
blood = new TConstructFluid(PHConstruct.blood, bloodFluid, Material.water, "liquid_cow").setUnlocalizedName("liquid.blood");
GameRegistry.registerBlock(blood, "liquid.blood");
fluids[16] = bloodFluid;
fluidBlocks[16] = blood;
bloodFluid.setBlockID(blood).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(bloodFluid, 1000), new ItemStack(buckets, 1, 16), new ItemStack(Item.bucketEmpty)));
moltenNickelFluid = new Fluid("nickel.molten");
if (!FluidRegistry.registerFluid(moltenNickelFluid))
moltenNickelFluid = FluidRegistry.getFluid("nickel.molten");
moltenNickel = new TConstructFluid(PHConstruct.moltenNickel, moltenNickelFluid, Material.lava, "liquid_ferrous").setUnlocalizedName("metal.molten.nickel");
GameRegistry.registerBlock(moltenNickel, "metal.molten.nickel");
fluids[17] = moltenNickelFluid;
fluidBlocks[17] = moltenNickel;
moltenNickelFluid.setBlockID(moltenNickel).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenNickelFluid, 1000), new ItemStack(buckets, 1, 17), new ItemStack(Item.bucketEmpty)));
moltenLeadFluid = new Fluid("lead.molten");
if (!FluidRegistry.registerFluid(moltenLeadFluid))
moltenLeadFluid = FluidRegistry.getFluid("lead.molten");
moltenLead = new TConstructFluid(PHConstruct.moltenLead, moltenLeadFluid, Material.lava, "liquid_lead").setUnlocalizedName("metal.molten.lead");
GameRegistry.registerBlock(moltenLead, "metal.molten.lead");
fluids[18] = moltenLeadFluid;
fluidBlocks[18] = moltenLead;
moltenLeadFluid.setBlockID(moltenLead).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenLeadFluid, 1000), new ItemStack(buckets, 1, 18), new ItemStack(Item.bucketEmpty)));
moltenSilverFluid = new Fluid("silver.molten");
if (!FluidRegistry.registerFluid(moltenSilverFluid))
moltenSilverFluid = FluidRegistry.getFluid("silver.molten");
moltenSilver = new TConstructFluid(PHConstruct.moltenSilver, moltenSilverFluid, Material.lava, "liquid_silver").setUnlocalizedName("metal.molten.silver");
GameRegistry.registerBlock(moltenSilver, "metal.molten.silver");
fluids[19] = moltenSilverFluid;
fluidBlocks[19] = moltenSilver;
moltenSilverFluid.setBlockID(moltenSilver).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenSilverFluid, 1000), new ItemStack(buckets, 1, 19), new ItemStack(Item.bucketEmpty)));
moltenShinyFluid = new Fluid("platinum.molten");
if (!FluidRegistry.registerFluid(moltenShinyFluid))
moltenShinyFluid = FluidRegistry.getFluid("platinum.molten");
moltenShiny = new TConstructFluid(PHConstruct.moltenShiny, moltenShinyFluid, Material.lava, "liquid_shiny").setUnlocalizedName("metal.molten.shiny");
GameRegistry.registerBlock(moltenShiny, "metal.molten.shiny");
fluids[20] = moltenLeadFluid;
fluidBlocks[20] = moltenShiny;
moltenShinyFluid.setBlockID(moltenShiny).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenShinyFluid, 1000), new ItemStack(buckets, 1, 20), new ItemStack(Item.bucketEmpty)));
moltenInvarFluid = new Fluid("invar.molten");
if (!FluidRegistry.registerFluid(moltenInvarFluid))
moltenInvarFluid = FluidRegistry.getFluid("invar.molten");
moltenInvar = new TConstructFluid(PHConstruct.moltenInvar, moltenInvarFluid, Material.lava, "liquid_invar").setUnlocalizedName("metal.molten.invar");
GameRegistry.registerBlock(moltenInvar, "metal.molten.invar");
fluids[21] = moltenInvarFluid;
fluidBlocks[21] = moltenInvar;
moltenInvarFluid.setBlockID(moltenInvar).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenInvarFluid, 1000), new ItemStack(buckets, 1, 21), new ItemStack(Item.bucketEmpty)));
moltenElectrumFluid = new Fluid("electrum.molten");
if (!FluidRegistry.registerFluid(moltenElectrumFluid))
moltenElectrumFluid = FluidRegistry.getFluid("electrum.molten");
moltenElectrum = new TConstructFluid(PHConstruct.moltenElectrum, moltenElectrumFluid, Material.lava, "liquid_electrum").setUnlocalizedName("metal.molten.electrum");
GameRegistry.registerBlock(moltenElectrum, "metal.molten.electrum");
fluids[22] = moltenElectrumFluid;
fluidBlocks[22] = moltenElectrum;
moltenElectrumFluid.setBlockID(moltenElectrum).setDensity(3000).setViscosity(6000).setTemperature(1300);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenElectrumFluid, 1000), new ItemStack(buckets, 1, 22), new ItemStack(Item.bucketEmpty)));
moltenEnderFluid = new Fluid("ender");
if (GameRegistry.findBlock("ThermalExpansion", "fluid.ender") == null)
{
if (FluidRegistry.registerFluid(moltenEnderFluid))
{
moltenEnder = new TConstructFluid(PHConstruct.moltenEnder, moltenEnderFluid, Material.water, "liquid_ender").setUnlocalizedName("fluid.ender");
GameRegistry.registerBlock(moltenEnder, "fluid.ender");
moltenEnderFluid.setBlockID(moltenEnder).setDensity(3000).setViscosity(6000);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenEnderFluid, 1000), new ItemStack(buckets, 1, 23), new ItemStack(Item.bucketEmpty)));
}
else
{
moltenEnderFluid = FluidRegistry.getFluid("ender");
moltenEnder = new TConstructFluid(PHConstruct.moltenEnder, moltenEnderFluid, Material.water, "liquid_ender").setUnlocalizedName("fluid.ender");
}
}
else
{
moltenEnderFluid = FluidRegistry.getFluid("ender");
moltenEnder = GameRegistry.findBlock("ThermalExpansion", "fluid.ender");
}
fluids[23] = moltenEnderFluid;
fluidBlocks[23] = moltenEnder;
//Slime
slimeStep = new StepSoundSlime("mob.slime", 1.0f, 1.0f);
blueSlimeFluid = new Fluid("slime.blue");
if (!FluidRegistry.registerFluid(blueSlimeFluid))
blueSlimeFluid = FluidRegistry.getFluid("slime.blue");
slimePool = new SlimeFluid(PHConstruct.slimePoolBlue, blueSlimeFluid, Material.water).setCreativeTab(TConstructRegistry.blockTab).setStepSound(slimeStep).setUnlocalizedName("liquid.slime");
GameRegistry.registerBlock(slimePool, "liquid.slime");
fluids[24] = blueSlimeFluid;
fluidBlocks[24] = slimePool;
blueSlimeFluid.setBlockID(slimePool);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(blueSlimeFluid, 1000), new ItemStack(buckets, 1, 24), new ItemStack(Item.bucketEmpty)));
slimeGel = new SlimeGel(PHConstruct.slimeGel).setStepSound(slimeStep).setLightOpacity(0).setUnlocalizedName("slime.gel");
GameRegistry.registerBlock(slimeGel, SlimeGelItemBlock.class, "slime.gel");
slimeGrass = new SlimeGrass(PHConstruct.slimeGrass).setStepSound(Block.soundGrassFootstep).setLightOpacity(0).setUnlocalizedName("slime.grass");
GameRegistry.registerBlock(slimeGrass, SlimeGrassItemBlock.class, "slime.grass");
slimeTallGrass = new SlimeTallGrass(PHConstruct.slimeTallGrass).setStepSound(Block.soundGrassFootstep).setUnlocalizedName("slime.grass.tall");
GameRegistry.registerBlock(slimeTallGrass, SlimeTallGrassItem.class, "slime.grass.tall");
slimeLeaves = (SlimeLeaves) new SlimeLeaves(PHConstruct.slimeLeaves).setStepSound(slimeStep).setLightOpacity(0).setUnlocalizedName("slime.leaves");
GameRegistry.registerBlock(slimeLeaves, SlimeLeavesItemBlock.class, "slime.leaves");
slimeSapling = (SlimeSapling) new SlimeSapling(PHConstruct.slimeSapling).setStepSound(slimeStep).setUnlocalizedName("slime.sapling");
GameRegistry.registerBlock(slimeSapling, SlimeSaplingItemBlock.class, "slime.sapling");
slimeChannel = new ConveyorBase(PHConstruct.slimeChannel, Material.water).setStepSound(slimeStep).setUnlocalizedName("slime.channel");
GameRegistry.registerBlock(slimeChannel, "slime.channel");
TConstructRegistry.drawbridgeState[slimeChannel.blockID] = 1;
slimePad = new SlimePad(PHConstruct.slimePad, Material.cloth).setStepSound(slimeStep).setUnlocalizedName("slime.pad");
GameRegistry.registerBlock(slimePad, "slime.pad");
TConstructRegistry.drawbridgeState[slimePad.blockID] = 1;
//Decoration
stoneTorch = new StoneTorch(PHConstruct.stoneTorch).setUnlocalizedName("decoration.stonetorch");
GameRegistry.registerBlock(stoneTorch, "decoration.stonetorch");
stoneLadder = new StoneLadder(PHConstruct.stoneLadder).setUnlocalizedName("decoration.stoneladder");
GameRegistry.registerBlock(stoneLadder, "decoration.stoneladder");
multiBrick = new MultiBrick(PHConstruct.multiBrick).setUnlocalizedName("Decoration.Brick");
GameRegistry.registerBlock(multiBrick, MultiBrickItem.class, "decoration.multibrick");
multiBrickFancy = new MultiBrickFancy(PHConstruct.multiBrickFancy).setUnlocalizedName("Decoration.BrickFancy");
GameRegistry.registerBlock(multiBrickFancy, MultiBrickFancyItem.class, "decoration.multibrickfancy");
//Ores
String[] berryOres = new String[] { "berry_iron", "berry_gold", "berry_copper", "berry_tin", "berry_iron_ripe", "berry_gold_ripe", "berry_copper_ripe", "berry_tin_ripe" };
oreBerry = (OreberryBush) new OreberryBush(PHConstruct.oreBerry, berryOres, 0, 4, new String[] { "oreIron", "oreGold", "oreCopper", "oreTin" }).setUnlocalizedName("ore.berries.one");
GameRegistry.registerBlock(oreBerry, OreberryBushItem.class, "ore.berries.one");
String[] berryOresTwo = new String[] { "berry_aluminum", "berry_essence", "", "", "berry_aluminum_ripe", "berry_essence_ripe", "", "" };
oreBerrySecond = (OreberryBush) new OreberryBushEssence(PHConstruct.oreBerrySecond, berryOresTwo, 4, 2, new String[] { "oreAluminum", "oreSilver" }).setUnlocalizedName("ore.berries.two");
GameRegistry.registerBlock(oreBerrySecond, OreberryBushSecondItem.class, "ore.berries.two");
String[] oreTypes = new String[] { "nether_slag", "nether_cobalt", "nether_ardite", "ore_copper", "ore_tin", "ore_aluminum", "ore_slag" };
oreSlag = new MetalOre(PHConstruct.oreSlag, Material.iron, 10.0F, oreTypes).setUnlocalizedName("tconstruct.stoneore");
GameRegistry.registerBlock(oreSlag, MetalOreItemBlock.class, "SearedBrick");
MinecraftForge.setBlockHarvestLevel(oreSlag, 1, "pickaxe", 4);
MinecraftForge.setBlockHarvestLevel(oreSlag, 2, "pickaxe", 4);
MinecraftForge.setBlockHarvestLevel(oreSlag, 3, "pickaxe", 1);
MinecraftForge.setBlockHarvestLevel(oreSlag, 4, "pickaxe", 1);
MinecraftForge.setBlockHarvestLevel(oreSlag, 5, "pickaxe", 1);
oreGravel = new GravelOre(PHConstruct.oreGravel).setUnlocalizedName("GravelOre").setUnlocalizedName("tconstruct.gravelore");
GameRegistry.registerBlock(oreGravel, GravelOreItem.class, "GravelOre");
MinecraftForge.setBlockHarvestLevel(oreGravel, 0, "shovel", 1);
MinecraftForge.setBlockHarvestLevel(oreGravel, 1, "shovel", 2);
MinecraftForge.setBlockHarvestLevel(oreGravel, 2, "shovel", 1);
MinecraftForge.setBlockHarvestLevel(oreGravel, 3, "shovel", 1);
MinecraftForge.setBlockHarvestLevel(oreGravel, 4, "shovel", 1);
MinecraftForge.setBlockHarvestLevel(oreGravel, 5, "shovel", 4);
speedBlock = new SpeedBlock(PHConstruct.speedBlock).setUnlocalizedName("SpeedBlock");
GameRegistry.registerBlock(speedBlock, SpeedBlockItem.class, "SpeedBlock");
//Glass
clearGlass = new GlassBlockConnected(PHConstruct.glass, "clear", false).setUnlocalizedName("GlassBlock");
clearGlass.stepSound = Block.soundGlassFootstep;
GameRegistry.registerBlock(clearGlass, GlassBlockItem.class, "GlassBlock");
glassPane = new GlassPaneConnected(PHConstruct.glassPane, "clear", false);
GameRegistry.registerBlock(glassPane, GlassPaneItem.class, "GlassPane");
stainedGlassClear = new GlassBlockConnectedMeta(PHConstruct.stainedGlassClear, "stained", true, "white", "orange", "magenta", "light_blue", "yellow", "lime", "pink", "gray", "light_gray",
"cyan", "purple", "blue", "brown", "green", "red", "black").setUnlocalizedName("GlassBlock.StainedClear");
stainedGlassClear.stepSound = Block.soundGlassFootstep;
GameRegistry.registerBlock(stainedGlassClear, StainedGlassClearItem.class, "GlassBlock.StainedClear");
stainedGlassClearPane = new GlassPaneStained(PHConstruct.stainedGlassClearPane);
GameRegistry.registerBlock(stainedGlassClearPane, StainedGlassClearPaneItem.class, "GlassPaneClearStained");
//Crystalline
essenceExtractor = new EssenceExtractor(PHConstruct.essenceExtractor).setHardness(12f).setUnlocalizedName("extractor.essence");
GameRegistry.registerBlock(essenceExtractor, "extractor.essence");
GameRegistry.registerTileEntity(EssenceExtractorLogic.class, "extractor.essence");
//Rail
woodenRail = new WoodRail(PHConstruct.woodenRail).setStepSound(Block.soundWoodFootstep).setCreativeTab(TConstructRegistry.blockTab).setUnlocalizedName("rail.wood");
GameRegistry.registerBlock(woodenRail, "rail.wood");
//Signal & Logic
signalBus = (new SignalBus(PHConstruct.signalBus)).setUnlocalizedName("tconstruct.signalbus");
GameRegistry.registerBlock(signalBus, SignalBusItem.class, "SignalBus");
GameRegistry.registerTileEntity(SignalBusLogic.class, "SignalBus");
signalTerminal = (new SignalTerminal(PHConstruct.signalTerminal)).setUnlocalizedName("tconstruct.signalterminal");
GameRegistry.registerBlock(signalTerminal, SignalTerminalItem.class, "SignalTerminal");
GameRegistry.registerTileEntity(SignalTerminalLogic.class, "SignalTerminal");
}
void registerItems ()
{
titleIcon = new TitleIcon(PHConstruct.uselessItem).setUnlocalizedName("tconstruct.titleicon");
String[] blanks = new String[] { "blank_pattern", "blank_cast", "blank_cast" };
blankPattern = new CraftingItem(PHConstruct.blankPattern, blanks, blanks, "materials/").setUnlocalizedName("tconstruct.Pattern");
materials = new MaterialItem(PHConstruct.materials).setUnlocalizedName("tconstruct.Materials");
toolRod = new ToolPart(PHConstruct.toolRod, "_rod", "ToolRod").setUnlocalizedName("tconstruct.ToolRod");
toolShard = new ToolShard(PHConstruct.toolShard, "_chunk").setUnlocalizedName("tconstruct.ToolShard");
woodPattern = new Pattern(PHConstruct.woodPattern, "WoodPattern", "pattern_", "materials/").setUnlocalizedName("tconstruct.Pattern");
metalPattern = new MetalPattern(PHConstruct.metalPattern, "MetalPattern", "cast_", "materials/").setUnlocalizedName("tconstruct.MetalPattern");
armorPattern = new ArmorPattern(PHConstruct.armorPattern, "ArmorPattern", "armorcast_", "materials/").setUnlocalizedName("tconstruct.ArmorPattern");
TConstructRegistry.addItemToDirectory("blankPattern", blankPattern);
TConstructRegistry.addItemToDirectory("woodPattern", woodPattern);
TConstructRegistry.addItemToDirectory("metalPattern", metalPattern);
TConstructRegistry.addItemToDirectory("armorPattern", armorPattern);
String[] patternTypes = { "ingot", "toolRod", "pickaxeHead", "shovelHead", "hatchetHead", "swordBlade", "wideGuard", "handGuard", "crossbar", "binding", "frypanHead", "signHead",
"knifeBlade", "chiselHead", "toughRod", "toughBinding", "largePlate", "broadAxeHead", "scytheHead", "excavatorHead", "largeBlade", "hammerHead", "fullGuard" };
for (int i = 1; i < patternTypes.length; i++)
{
TConstructRegistry.addItemStackToDirectory(patternTypes[i] + "Pattern", new ItemStack(woodPattern, 1, i));
}
for (int i = 0; i < patternTypes.length; i++)
{
TConstructRegistry.addItemStackToDirectory(patternTypes[i] + "Cast", new ItemStack(metalPattern, 1, i));
}
String[] armorPartTypes = { "helmet", "chestplate", "leggings", "boots" };
for (int i = 1; i < armorPartTypes.length; i++)
{
TConstructRegistry.addItemStackToDirectory(armorPartTypes[i] + "Cast", new ItemStack(armorPattern, 1, i));
}
manualBook = new Manual(PHConstruct.manual);
buckets = new FilledBucket(PHConstruct.buckets);
pickaxe = new Pickaxe(PHConstruct.pickaxe);
shovel = new Shovel(PHConstruct.shovel);
hatchet = new Hatchet(PHConstruct.axe);
broadsword = new Broadsword(PHConstruct.broadsword);
longsword = new Longsword(PHConstruct.longsword);
rapier = new Rapier(PHConstruct.rapier);
dagger = new Dagger(PHConstruct.dagger);
cutlass = new Cutlass(PHConstruct.cutlass);
frypan = new FryingPan(PHConstruct.frypan);
battlesign = new BattleSign(PHConstruct.battlesign);
mattock = new Mattock(PHConstruct.mattock);
chisel = new Chisel(PHConstruct.chisel);
lumberaxe = new LumberAxe(PHConstruct.lumberaxe);
cleaver = new Cleaver(PHConstruct.cleaver);
scythe = new Scythe(PHConstruct.scythe);
excavator = new Excavator(PHConstruct.excavator);
hammer = new Hammer(PHConstruct.hammer);
battleaxe = new Battleaxe(PHConstruct.battleaxe);
shortbow = new Shortbow(PHConstruct.shortbow);
arrow = new Arrow(PHConstruct.arrow);
Item[] tools = { pickaxe, shovel, hatchet, broadsword, longsword, rapier, cutlass, frypan, battlesign, mattock, chisel, lumberaxe, cleaver, scythe, excavator, hammer, battleaxe };
String[] toolStrings = { "pickaxe", "shovel", "hatchet", "broadsword", "longsword", "rapier", "cutlass", "frypan", "battlesign", "mattock", "chisel", "lumberaxe", "cleaver", "scythe",
"excavator", "hammer", "battleaxe" };
for (int i = 0; i < tools.length; i++)
{
TConstructRegistry.addItemToDirectory(toolStrings[i], tools[i]);
}
potionLauncher = new PotionLauncher(PHConstruct.potionLauncher).setUnlocalizedName("tconstruct.PotionLauncher");
pickaxeHead = new ToolPart(PHConstruct.pickaxeHead, "_pickaxe_head", "PickHead").setUnlocalizedName("tconstruct.PickaxeHead");
shovelHead = new ToolPart(PHConstruct.shovelHead, "_shovel_head", "ShovelHead").setUnlocalizedName("tconstruct.ShovelHead");
hatchetHead = new ToolPart(PHConstruct.axeHead, "_axe_head", "AxeHead").setUnlocalizedName("tconstruct.AxeHead");
binding = new ToolPart(PHConstruct.binding, "_binding", "Binding").setUnlocalizedName("tconstruct.Binding");
toughBinding = new ToolPart(PHConstruct.toughBinding, "_toughbind", "ToughBind").setUnlocalizedName("tconstruct.ThickBinding");
toughRod = new ToolPart(PHConstruct.toughRod, "_toughrod", "ToughRod").setUnlocalizedName("tconstruct.ThickRod");
largePlate = new ToolPart(PHConstruct.largePlate, "_largeplate", "LargePlate").setUnlocalizedName("tconstruct.LargePlate");
swordBlade = new ToolPart(PHConstruct.swordBlade, "_sword_blade", "SwordBlade").setUnlocalizedName("tconstruct.SwordBlade");
wideGuard = new ToolPart(PHConstruct.largeGuard, "_large_guard", "LargeGuard").setUnlocalizedName("tconstruct.LargeGuard");
handGuard = new ToolPart(PHConstruct.medGuard, "_medium_guard", "MediumGuard").setUnlocalizedName("tconstruct.MediumGuard");
crossbar = new ToolPart(PHConstruct.crossbar, "_crossbar", "Crossbar").setUnlocalizedName("tconstruct.Crossbar");
knifeBlade = new ToolPart(PHConstruct.knifeBlade, "_knife_blade", "KnifeBlade").setUnlocalizedName("tconstruct.KnifeBlade");
fullGuard = new ToolPartHidden(PHConstruct.fullGuard, "_full_guard", "FullGuard").setUnlocalizedName("tconstruct.FullGuard");
frypanHead = new ToolPart(PHConstruct.frypanHead, "_frypan_head", "FrypanHead").setUnlocalizedName("tconstruct.FrypanHead");
signHead = new ToolPart(PHConstruct.signHead, "_battlesign_head", "SignHead").setUnlocalizedName("tconstruct.SignHead");
chiselHead = new ToolPart(PHConstruct.chiselHead, "_chisel_head", "ChiselHead").setUnlocalizedName("tconstruct.ChiselHead");
scytheBlade = new ToolPart(PHConstruct.scytheBlade, "_scythe_head", "ScytheHead").setUnlocalizedName("tconstruct.ScytheBlade");
broadAxeHead = new ToolPart(PHConstruct.lumberHead, "_lumberaxe_head", "LumberHead").setUnlocalizedName("tconstruct.LumberHead");
excavatorHead = new ToolPart(PHConstruct.excavatorHead, "_excavator_head", "ExcavatorHead").setUnlocalizedName("tconstruct.ExcavatorHead");
largeSwordBlade = new ToolPart(PHConstruct.largeSwordBlade, "_large_sword_blade", "LargeSwordBlade").setUnlocalizedName("tconstruct.LargeSwordBlade");
hammerHead = new ToolPart(PHConstruct.hammerHead, "_hammer_head", "HammerHead").setUnlocalizedName("tconstruct.HammerHead");
bowstring = new Bowstring(PHConstruct.bowstring).setUnlocalizedName("tconstruct.Bowstring");
arrowhead = new ToolPart(PHConstruct.arrowhead, "_arrowhead", "ArrowHead").setUnlocalizedName("tconstruct.Arrowhead");
fletching = new Fletching(PHConstruct.fletching).setUnlocalizedName("tconstruct.Fletching");
Item[] toolParts = { toolRod, toolShard, pickaxeHead, shovelHead, hatchetHead, binding, toughBinding, toughRod, largePlate, swordBlade, wideGuard, handGuard, crossbar, knifeBlade, fullGuard,
frypanHead, signHead, chiselHead, scytheBlade, broadAxeHead, excavatorHead, largeSwordBlade, hammerHead, bowstring, fletching, arrowhead };
String[] toolPartStrings = { "toolRod", "toolShard", "pickaxeHead", "shovelHead", "hatchetHead", "binding", "toughBinding", "toughRod", "heavyPlate", "swordBlade", "wideGuard", "handGuard",
"crossbar", "knifeBlade", "fullGuard", "frypanHead", "signHead", "chiselHead", "scytheBlade", "broadAxeHead", "excavatorHead", "largeSwordBlade", "hammerHead", "bowstring",
"fletching", "arrowhead" };
for (int i = 0; i < toolParts.length; i++)
{
TConstructRegistry.addItemToDirectory(toolPartStrings[i], toolParts[i]);
}
diamondApple = new DiamondApple(PHConstruct.diamondApple).setUnlocalizedName("tconstruct.apple.diamond");
strangeFood = new StrangeFood(PHConstruct.slimefood).setUnlocalizedName("tconstruct.strangefood");
oreBerries = new OreBerries(PHConstruct.oreChunks).setUnlocalizedName("oreberry");
jerky = new Jerky(PHConstruct.jerky, Loader.isModLoaded("HungerOverhaul")).setUnlocalizedName("tconstruct.jerky");
//Wearables
//heavyHelmet = new TArmorBase(PHConstruct.heavyHelmet, 0).setUnlocalizedName("tconstruct.HeavyHelmet");
heartCanister = new HeartCanister(PHConstruct.heartCanister).setUnlocalizedName("tconstruct.canister");
//heavyBoots = new TArmorBase(PHConstruct.heavyBoots, 3).setUnlocalizedName("tconstruct.HeavyBoots");
//glove = new Glove(PHConstruct.glove).setUnlocalizedName("tconstruct.Glove");
knapsack = new Knapsack(PHConstruct.knapsack).setUnlocalizedName("tconstruct.storage");
//Crystalline
essenceCrystal = new EssenceCrystal(PHConstruct.essenceCrystal).setUnlocalizedName("tconstruct.crystal.essence");
goldHead = new GoldenHead(PHConstruct.goldHead, 4, 1.2F, false).setAlwaysEdible().setPotionEffect(Potion.regeneration.id, 10, 0, 1.0F).setUnlocalizedName("goldenhead");
LiquidCasting basinCasting = TConstruct.getBasinCasting();
materialWood = EnumHelper.addArmorMaterial("WOOD", 2, new int[] { 1, 2, 2, 1 }, 3);
helmetWood = new ArmorBasic(PHConstruct.woodHelmet, materialWood, 0, "wood").setUnlocalizedName("tconstruct.helmetWood");
chestplateWood = new ArmorBasic(PHConstruct.woodChestplate, materialWood, 1, "wood").setUnlocalizedName("tconstruct.chestplateWood");
leggingsWood = new ArmorBasic(PHConstruct.woodPants, materialWood, 2, "wood").setUnlocalizedName("tconstruct.leggingsWood");
bootsWood = new ArmorBasic(PHConstruct.woodBoots, materialWood, 3, "wood").setUnlocalizedName("tconstruct.bootsWood");
spoolWire = new SpoolOfWire(PHConstruct.spoolWire).setUnlocalizedName("spoolwire");
lengthWire = new LengthWire(PHConstruct.lengthWire).setUnlocalizedName("lengthwire");
// essenceCrystal = new EssenceCrystal(PHConstruct.essenceCrystal).setUnlocalizedName("tconstruct.crystal.essence");
String[] materialStrings = { "paperStack", "greenSlimeCrystal", "searedBrick", "ingotCobalt", "ingotArdite", "ingotManyullyn", "mossBall", "lavaCrystal", "necroticBone", "ingotCopper",
"ingotTin", "ingotAluminum", "rawAluminum", "ingotBronze", "ingotAluminumBrass", "ingotAlumite", "ingotSteel", "blueSlimeCrystal", "ingotObsidian", "nuggetIron", "nuggetCopper",
"nuggetTin", "nuggetAluminum", "nuggetSilver", "nuggetAluminumBrass", "silkyCloth", "silkyJewel", "nuggetObsidian", "nuggetCobalt", "nuggetArdite", "nuggetManyullyn", "nuggetBronze",
"nuggetAlumite", "nuggetSteel" };
for (int i = 0; i < materialStrings.length; i++)
{
TConstructRegistry.addItemStackToDirectory(materialStrings[i], new ItemStack(materials, 1, i));
}
String[] oreberries = { "Iron", "Gold", "Copper", "Tin", "Aluminum", "Essence" };
for (int i = 0; i < oreberries.length; i++)
{
TConstructRegistry.addItemStackToDirectory("oreberry" + oreberries[i], new ItemStack(oreBerries, 1, i));
}
TConstructRegistry.addItemStackToDirectory("diamondApple", new ItemStack(diamondApple, 1, 0));
TConstructRegistry.addItemStackToDirectory("blueSlimeFood", new ItemStack(strangeFood, 1, 0));
TConstructRegistry.addItemStackToDirectory("canisterEmpty", new ItemStack(heartCanister, 1, 0));
TConstructRegistry.addItemStackToDirectory("miniRedHeart", new ItemStack(heartCanister, 1, 1));
TConstructRegistry.addItemStackToDirectory("canisterRedHeart", new ItemStack(heartCanister, 1, 2));
TConstructRegistry.addItemStackToDirectory("spoolWire", new ItemStack(spoolWire, 1, 0));
TConstructRegistry.addItemStackToDirectory("lengthWire", new ItemStack(lengthWire, 1, 0));
//Vanilla stack sizes
Item.doorWood.setMaxStackSize(16);
Item.doorIron.setMaxStackSize(16);
Item.snowball.setMaxStackSize(64);
Item.boat.setMaxStackSize(16);
Item.minecartEmpty.setMaxStackSize(3);
Item.minecartCrate.setMaxStackSize(3);
Item.minecartPowered.setMaxStackSize(3);
Item.itemsList[Block.cake.blockID].setMaxStackSize(16);
//Block.torchWood.setTickRandomly(false);
}
void registerMaterials ()
{
TConstructRegistry.addToolMaterial(0, "Wood", "Wooden ", 0, 59, 200, 0, 1.0F, 0, 0f, "\u00A7e", "");
TConstructRegistry.addToolMaterial(1, "Stone", 1, 131, 400, 1, 0.5F, 0, 1f, "", "Stonebound");
TConstructRegistry.addToolMaterial(2, "Iron", 2, 250, 600, 2, 1.3F, 1, 0f, "\u00A7f", "");
TConstructRegistry.addToolMaterial(3, "Flint", 1, 171, 525, 2, 0.7F, 0, 0f, "\u00A78", "");
TConstructRegistry.addToolMaterial(4, "Cactus", 1, 150, 500, 2, 1.0F, 0, -1f, "\u00A72", "Jagged");
TConstructRegistry.addToolMaterial(5, "Bone", 1, 200, 400, 1, 1.0F, 0, 0f, "\u00A7e", "");
TConstructRegistry.addToolMaterial(6, "Obsidian", 3, 89, 700, 2, 0.8F, 3, 0f, "\u00A7d", "");
TConstructRegistry.addToolMaterial(7, "Netherrack", 2, 131, 400, 1, 1.2F, 0, 1f, "\u00A74", "Stonebound");
TConstructRegistry.addToolMaterial(8, "Slime", 0, 500, 150, 0, 1.5F, 0, 0f, "\u00A7a", "");
TConstructRegistry.addToolMaterial(9, "Paper", 0, 30, 200, 0, 0.3F, 0, 0f, "\u00A7f", "Writable");
TConstructRegistry.addToolMaterial(10, "Cobalt", 4, 800, 1100, 3, 1.75F, 2, 0f, "\u00A73", "");
TConstructRegistry.addToolMaterial(11, "Ardite", 4, 600, 800, 3, 2.0F, 0, 2f, "\u00A74", "Stonebound");
TConstructRegistry.addToolMaterial(12, "Manyullyn", 5, 1200, 900, 4, 2.5F, 0, 0f, "\u00A75", "");
TConstructRegistry.addToolMaterial(13, "Copper", 1, 180, 500, 2, 1.15F, 0, 0f, "\u00A7c", "");
TConstructRegistry.addToolMaterial(14, "Bronze", 2, 350, 700, 2, 1.3F, 1, 0f, "\u00A76", "");
TConstructRegistry.addToolMaterial(15, "Alumite", 4, 550, 800, 3, 1.3F, 2, 0f, "\u00A7d", "");
TConstructRegistry.addToolMaterial(16, "Steel", 4, 750, 800, 3, 1.3F, 2, 0f, "", "");
TConstructRegistry.addToolMaterial(17, "BlueSlime", "Slime ", 0, 1200, 150, 0, 2.0F, 0, 0f, "\u00A7b", "");
TConstructRegistry.addBowMaterial(0, 384, 20, 1.0f); //Wood
TConstructRegistry.addBowMaterial(1, 10, 80, 0.2f); //Stone
TConstructRegistry.addBowMaterial(2, 576, 40, 1.2f); //Iron
TConstructRegistry.addBowMaterial(3, 10, 80, 0.2f); //Flint
TConstructRegistry.addBowMaterial(4, 384, 20, 1.0f); //Cactus
TConstructRegistry.addBowMaterial(5, 192, 30, 1.0f); //Bone
TConstructRegistry.addBowMaterial(6, 10, 80, 0.2f); //Obsidian
TConstructRegistry.addBowMaterial(7, 10, 80, 0.2f); //Netherrack
TConstructRegistry.addBowMaterial(8, 1536, 20, 1.2f); //Slime
TConstructRegistry.addBowMaterial(9, 48, 25, 0.5f); //Paper
TConstructRegistry.addBowMaterial(10, 1152, 40, 1.2f); //Cobalt
TConstructRegistry.addBowMaterial(11, 960, 40, 1.2f); //Ardite
TConstructRegistry.addBowMaterial(12, 1536, 40, 1.2f); //Manyullyn
TConstructRegistry.addBowMaterial(13, 384, 40, 1.2f); //Copper
TConstructRegistry.addBowMaterial(14, 576, 40, 1.2f); //Bronze
TConstructRegistry.addBowMaterial(15, 768, 40, 1.2f); //Alumite
TConstructRegistry.addBowMaterial(16, 768, 40, 1.2f); //Steel
TConstructRegistry.addBowMaterial(17, 576, 20, 1.2f); //Blue Slime
//Material ID, mass, fragility
TConstructRegistry.addArrowMaterial(0, 0.69F, 1.0F, 100F); //Wood
TConstructRegistry.addArrowMaterial(1, 2.5F, 5.0F, 100F); //Stone
TConstructRegistry.addArrowMaterial(2, 7.2F, 0.5F, 100F); //Iron
TConstructRegistry.addArrowMaterial(3, 2.65F, 1.0F, 100F); //Flint
TConstructRegistry.addArrowMaterial(4, 0.76F, 1.0F, 100F); //Cactus
TConstructRegistry.addArrowMaterial(5, 0.69F, 1.0F, 100); //Bone
TConstructRegistry.addArrowMaterial(6, 2.4F, 1.0F, 100F); //Obsidian
TConstructRegistry.addArrowMaterial(7, 3.5F, 1.0F, 100F); //Netherrack
TConstructRegistry.addArrowMaterial(8, 0.42F, 0.0F, 100F); //Slime
TConstructRegistry.addArrowMaterial(9, 1.1F, 3.0F, 90F); //Paper
TConstructRegistry.addArrowMaterial(10, 8.9F, 0.25F, 100F); //Cobalt
TConstructRegistry.addArrowMaterial(11, 7.2F, 0.25F, 100F); //Ardite
TConstructRegistry.addArrowMaterial(12, 10.6F, 0.1F, 100F); //Manyullyn
TConstructRegistry.addArrowMaterial(13, 8.96F, 0.5F, 100F); //Copper
TConstructRegistry.addArrowMaterial(14, 7.9F, 0.25F, 100F); //Bronze
TConstructRegistry.addArrowMaterial(15, 4.7F, 0.25F, 100F); //Alumite
TConstructRegistry.addArrowMaterial(16, 7.6F, 0.25F, 100F); //Steel
TConstructRegistry.addArrowMaterial(17, 0.42F, 0.0F, 100F); //Blue Slime
TConstructRegistry.addBowstringMaterial(0, 2, new ItemStack(Item.silk), new ItemStack(bowstring, 1, 0), 1F, 1F, 1f); //String
TConstructRegistry.addFletchingMaterial(0, 2, new ItemStack(Item.feather), new ItemStack(fletching, 1, 0), 100F, 0F, 0.05F); //Feather
for (int i = 0; i < 4; i++)
TConstructRegistry.addFletchingMaterial(1, 2, new ItemStack(Block.leaves, 1, i), new ItemStack(fletching, 1, 1), 75F, 0F, 0.2F); //All four vanialla Leaves
TConstructRegistry.addFletchingMaterial(2, 2, new ItemStack(materials, 1, 1), new ItemStack(fletching, 1, 2), 100F, 0F, 0.12F); //Slime
TConstructRegistry.addFletchingMaterial(3, 2, new ItemStack(materials, 1, 17), new ItemStack(fletching, 1, 3), 100F, 0F, 0.12F); //BlueSlime
PatternBuilder pb = PatternBuilder.instance;
if (PHConstruct.enableTWood)
pb.registerFullMaterial(Block.planks, 2, "Wood", new ItemStack(Item.stick), new ItemStack(Item.stick), 0);
else
pb.registerMaterialSet("Wood", new ItemStack(Item.stick, 2), new ItemStack(Item.stick), 0);
if (PHConstruct.enableTStone)
{
pb.registerFullMaterial(Block.stone, 2, "Stone", new ItemStack(TContent.toolShard, 1, 1), new ItemStack(TContent.toolRod, 1, 1), 1);
pb.registerMaterial(Block.cobblestone, 2, "Stone");
}
else
pb.registerMaterialSet("Stone", new ItemStack(TContent.toolShard, 1, 1), new ItemStack(TContent.toolRod, 1, 1), 0);
pb.registerFullMaterial(Item.ingotIron, 2, "Iron", new ItemStack(TContent.toolShard, 1, 2), new ItemStack(TContent.toolRod, 1, 2), 2);
if (PHConstruct.enableTFlint)
pb.registerFullMaterial(Item.flint, 2, "Flint", new ItemStack(TContent.toolShard, 1, 3), new ItemStack(TContent.toolRod, 1, 3), 3);
else
pb.registerMaterialSet("Flint", new ItemStack(TContent.toolShard, 1, 3), new ItemStack(TContent.toolRod, 1, 3), 3);
if (PHConstruct.enableTCactus)
pb.registerFullMaterial(Block.cactus, 2, "Cactus", new ItemStack(TContent.toolShard, 1, 4), new ItemStack(TContent.toolRod, 1, 4), 4);
else
pb.registerMaterialSet("Cactus", new ItemStack(TContent.toolShard, 1, 4), new ItemStack(TContent.toolRod, 1, 4), 4);
if (PHConstruct.enableTBone)
pb.registerFullMaterial(Item.bone, 2, "Bone", new ItemStack(Item.dyePowder, 1, 15), new ItemStack(Item.bone), 5);
else
pb.registerMaterialSet("Bone", new ItemStack(Item.dyePowder, 1, 15), new ItemStack(Item.bone), 5);
pb.registerFullMaterial(Block.obsidian, 2, "Obsidian", new ItemStack(TContent.toolShard, 1, 6), new ItemStack(TContent.toolRod, 1, 6), 6);
pb.registerMaterial(new ItemStack(materials, 1, 18), 2, "Obsidian");
if (PHConstruct.enableTNetherrack)
pb.registerFullMaterial(Block.netherrack, 2, "Netherrack", new ItemStack(TContent.toolShard, 1, 7), new ItemStack(TContent.toolRod, 1, 7), 7);
else
pb.registerMaterialSet("Netherrack", new ItemStack(TContent.toolShard, 1, 7), new ItemStack(TContent.toolRod, 1, 7), 7);
if (PHConstruct.enableTSlime)
pb.registerFullMaterial(new ItemStack(materials, 1, 1), 2, "Slime", new ItemStack(toolShard, 1, 8), new ItemStack(toolRod, 1, 8), 8);
else
pb.registerMaterialSet("Slime", new ItemStack(TContent.toolShard, 1, 8), new ItemStack(TContent.toolRod, 1, 17), 8);
if (PHConstruct.enableTPaper)
pb.registerFullMaterial(new ItemStack(materials, 1, 0), 2, "Paper", new ItemStack(Item.paper, 2), new ItemStack(toolRod, 1, 9), 9);
else
pb.registerMaterialSet("BlueSlime", new ItemStack(Item.paper, 2), new ItemStack(TContent.toolRod, 1, 9), 9);
pb.registerMaterialSet("Cobalt", new ItemStack(toolShard, 1, 10), new ItemStack(toolRod, 1, 10), 10);
pb.registerMaterialSet("Ardite", new ItemStack(toolShard, 1, 11), new ItemStack(toolRod, 1, 11), 11);
pb.registerMaterialSet("Manyullyn", new ItemStack(toolShard, 1, 12), new ItemStack(toolRod, 1, 12), 12);
pb.registerMaterialSet("Copper", new ItemStack(toolShard, 1, 13), new ItemStack(toolRod, 1, 13), 13);
pb.registerMaterialSet("Bronze", new ItemStack(toolShard, 1, 14), new ItemStack(toolRod, 1, 14), 14);
pb.registerMaterialSet("Alumite", new ItemStack(toolShard, 1, 15), new ItemStack(toolRod, 1, 15), 15);
pb.registerMaterialSet("Steel", new ItemStack(toolShard, 1, 16), new ItemStack(toolRod, 1, 16), 16);
if (PHConstruct.enableTBlueSlime)
pb.registerFullMaterial(new ItemStack(materials, 1, 17), 2, "BlueSlime", new ItemStack(toolShard, 1, 17), new ItemStack(toolRod, 1, 17), 17);
else
pb.registerMaterialSet("BlueSlime", new ItemStack(TContent.toolShard, 1, 17), new ItemStack(TContent.toolRod, 1, 17), 17);
pb.addToolPattern((IPattern) woodPattern);
}
public static Item[] patternOutputs;
public static FluidStack[] liquids;
void addCraftingRecipes ()
{
addPartMapping();
addRecipesForToolBuilder();
addRecipesForTableCasting();
addRecipesForBasinCasting();
addRecipesForSmeltery();
addRecipesForChisel();
addRecipesForFurnace();
addRecipesForCraftingTable();
addRecipesForDryingRack();
}
private void addRecipesForCraftingTable ()
{
String[] patBlock = { "###", "###", "###" };
String[] patSurround = { "###", "#m#", "###" };
Object[] toolForgeBlocks = { "blockIron", "blockGold", Block.blockDiamond, Block.blockEmerald, "blockCobalt", "blockArdite", "blockManyullyn", "blockCopper", "blockBronze", "blockTin",
"blockNaturalAluminum", "blockAluminumBrass", "blockAlumite", "blockSteel" };
// ToolForge Recipes (Metal Version)
for (int sc = 0; sc < toolForgeBlocks.length; sc++)
{
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolForge, 1, sc), "bbb", "msm", "m m", 'b', new ItemStack(smeltery, 1, 2), 's', new ItemStack(toolStationWood, 1, 0), 'm',
toolForgeBlocks[sc]));
// adding slab version recipe
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(craftingSlabWood, 1, 5), "bbb", "msm", "m m", 'b', new ItemStack(smeltery, 1, 2), 's', new ItemStack(craftingSlabWood, 1, 1), 'm',
toolForgeBlocks[sc]));
}
// Drawbridge Recipes
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(redstoneMachine, 1, 0), "aca", "#d#", "#r#", '#', "ingotBronze", 'a', "ingotAluminumBrass", 'c', new ItemStack(blankPattern, 1, 1),
'r', new ItemStack(Item.redstone), 'd', new ItemStack(Block.dispenser)));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(redstoneMachine, 1, 0), "aca", "#d#", "#r#", '#', "ingotBronze", 'a', "ingotAluminumBrass", 'c', new ItemStack(blankPattern, 1, 2),
'r', new ItemStack(Item.redstone), 'd', new ItemStack(Block.dispenser)));
// Igniter Recipes
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(redstoneMachine, 1, 1), "aca", "#d#", "#r#", '#', "ingotBronze", 'a', "ingotAluminumBrass", 'c', new ItemStack(largePlate, 1, 7), 'r',
new ItemStack(Item.redstone), 'd', new ItemStack(Item.flintAndSteel)));
// Advanced Drawbridge Recipes
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(redstoneMachine, 1, 2), " c ", "rdr", " a ", 'a', "ingotAluminumBrass", 'c', new ItemStack(blankPattern, 1, 1), 'r', new ItemStack(
Item.redstone), 'd', new ItemStack(redstoneMachine, 1, 0)));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(redstoneMachine, 1, 2), " c ", "rdr", " a ", 'a', "ingotAluminumBrass", 'c', new ItemStack(blankPattern, 1, 2), 'r', new ItemStack(
Item.redstone), 'd', new ItemStack(redstoneMachine, 1, 0)));
// ToolStation Recipes (Wooden Version)
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolStationWood, 1, 0), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', "crafterWood"));
GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 0), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(craftingStationWood, 1, 0));
GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 0), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(craftingSlabWood, 1, 0));
GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 2), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.wood, 1, 1));
GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 3), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.wood, 1, 2));
GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 4), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.wood, 1, 3));
GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 5), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', Block.chest);
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolStationWood, 1, 1), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', "logWood"));
if (PHConstruct.stencilTableCrafting)
{
GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 10), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.planks, 1, 0));
GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 11), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.planks, 1, 1));
GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 12), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.planks, 1, 2));
GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 13), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.planks, 1, 3));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolStationWood, 1, 10), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', "plankWood"));
}
// Blank Pattern Recipe
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(blankPattern, 1, 0), "ps", "sp", 'p', "plankWood", 's', "stickWood"));
// Manual Book Recipes
GameRegistry.addRecipe(new ItemStack(manualBook), "wp", 'w', new ItemStack(blankPattern, 1, 0), 'p', Item.paper);
GameRegistry.addShapelessRecipe(new ItemStack(manualBook, 2, 0), new ItemStack(manualBook, 1, 0), Item.book);
GameRegistry.addShapelessRecipe(new ItemStack(manualBook, 1, 1), new ItemStack(manualBook, 1, 0));
GameRegistry.addShapelessRecipe(new ItemStack(manualBook, 2, 1), new ItemStack(manualBook, 1, 1), Item.book);
GameRegistry.addShapelessRecipe(new ItemStack(manualBook, 1, 2), new ItemStack(manualBook, 1, 1));
GameRegistry.addShapelessRecipe(new ItemStack(manualBook, 2, 2), new ItemStack(manualBook, 1, 2), Item.book);
// alternativ Vanilla Book Recipe
GameRegistry.addShapelessRecipe(new ItemStack(Item.book), Item.paper, Item.paper, Item.paper, Item.silk, blankPattern, blankPattern);
// Paperstack Recipe
GameRegistry.addRecipe(new ItemStack(materials, 1, 0), "pp", "pp", 'p', Item.paper);
// Mossball Recipe
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(materials, 1, 6), patBlock, '#', "stoneMossy"));
// LavaCrystal Recipes -Auto-smelt
GameRegistry.addRecipe(new ItemStack(materials, 1, 7), "xcx", "cbc", "xcx", 'b', Item.bucketLava, 'c', Item.fireballCharge, 'x', Item.blazeRod);
GameRegistry.addRecipe(new ItemStack(materials, 1, 7), "xcx", "cbc", "xcx", 'b', Item.bucketLava, 'x', Item.fireballCharge, 'c', Item.blazeRod);
// Slimy sand Recipes
GameRegistry.addShapelessRecipe(new ItemStack(craftedSoil, 1, 0), Item.slimeBall, Item.slimeBall, Item.slimeBall, Item.slimeBall, Block.sand, Block.dirt);
GameRegistry.addShapelessRecipe(new ItemStack(craftedSoil, 1, 2), strangeFood, strangeFood, strangeFood, strangeFood, Block.sand, Block.dirt);
// Grout Recipes
GameRegistry.addShapelessRecipe(new ItemStack(craftedSoil, 2, 1), Item.clay, Block.sand, Block.gravel);
GameRegistry.addRecipe(new ItemStack(craftedSoil, 8, 1), "sgs", "gcg", "sgs", 'c', new ItemStack(Block.stainedClay, 1, Short.MAX_VALUE), 's', Block.sand, 'g', Block.gravel);
GameRegistry.addRecipe(new ItemStack(craftedSoil, 8, 1), "sgs", "gcg", "sgs", 'c', new ItemStack(Block.blockClay, 1, Short.MAX_VALUE), 's', Block.sand, 'g', Block.gravel);
// Graveyard Soil Recipes
GameRegistry.addShapelessRecipe(new ItemStack(craftedSoil, 1, 3), Block.dirt, Item.rottenFlesh, new ItemStack(Item.dyePowder, 1, 15));
// Silky Cloth Recipes
GameRegistry.addRecipe(new ItemStack(materials, 1, 25), patSurround, 'm', new ItemStack(materials, 1, 24), '#', new ItemStack(Item.silk));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(materials, 1, 25), patSurround, 'm', "nuggetGold", '#', new ItemStack(Item.silk)));
// Silky Jewel Recipes
GameRegistry.addRecipe(new ItemStack(materials, 1, 26), " c ", "cec", " c ", 'c', new ItemStack(materials, 1, 25), 'e', new ItemStack(Item.emerald));
// Ender Stuff
GameRegistry.addRecipe(new ItemStack(Item.enderPearl, 9), "m", 'm', new ItemStack(metalBlock.blockID, 1, 10));
// Wooden Armor Recipes
GameRegistry.addRecipe(new ShapedOreRecipe(helmetWood, new Object[] { "www", "w w", 'w', "logWood" }));
GameRegistry.addRecipe(new ShapedOreRecipe(chestplateWood, new Object[] { "w w", "www", "www", 'w', "logWood" }));
GameRegistry.addRecipe(new ShapedOreRecipe(leggingsWood, new Object[] { "www", "w w", "w w", 'w', "logWood" }));
GameRegistry.addRecipe(new ShapedOreRecipe(bootsWood, new Object[] { "w w", "w w", 'w', "logWood" }));
// Metal conversion Recipes
GameRegistry.addRecipe(new ItemStack(materials, 9, 9), "m", 'm', new ItemStack(metalBlock, 1, 3)); //Copper
GameRegistry.addRecipe(new ItemStack(materials, 9, 10), "m", 'm', new ItemStack(metalBlock, 1, 5)); //Tin
GameRegistry.addRecipe(new ItemStack(materials, 9, 12), "m", 'm', new ItemStack(metalBlock, 1, 6)); //Aluminum
GameRegistry.addRecipe(new ItemStack(materials, 9, 13), "m", 'm', new ItemStack(metalBlock, 1, 4)); //Bronze
GameRegistry.addRecipe(new ItemStack(materials, 9, 14), "m", 'm', new ItemStack(metalBlock, 1, 7)); //AluBrass
GameRegistry.addRecipe(new ItemStack(materials, 9, 3), "m", 'm', new ItemStack(metalBlock, 1, 0)); //Cobalt
GameRegistry.addRecipe(new ItemStack(materials, 9, 4), "m", 'm', new ItemStack(metalBlock, 1, 1)); //Ardite
GameRegistry.addRecipe(new ItemStack(materials, 9, 5), "m", 'm', new ItemStack(metalBlock, 1, 2)); //Manyullyn
GameRegistry.addRecipe(new ItemStack(materials, 9, 15), "m", 'm', new ItemStack(metalBlock, 1, 8)); //Alumite
GameRegistry.addRecipe(new ItemStack(materials, 9, 16), "m", 'm', new ItemStack(metalBlock, 1, 9)); //Steel
GameRegistry.addRecipe(new ItemStack(Item.ingotIron), patBlock, '#', new ItemStack(materials, 1, 19)); //Iron
GameRegistry.addRecipe(new ItemStack(materials, 1, 9), patBlock, '#', new ItemStack(materials, 1, 20)); //Copper
GameRegistry.addRecipe(new ItemStack(materials, 1, 10), patBlock, '#', new ItemStack(materials, 1, 21)); //Tin
GameRegistry.addRecipe(new ItemStack(materials, 1, 12), patBlock, '#', new ItemStack(materials, 1, 22)); //Aluminum
GameRegistry.addRecipe(new ItemStack(materials, 1, 14), patBlock, '#', new ItemStack(materials, 1, 24)); //Aluminum Brass
GameRegistry.addRecipe(new ItemStack(materials, 1, 18), patBlock, '#', new ItemStack(materials, 1, 27)); //Obsidian
GameRegistry.addRecipe(new ItemStack(materials, 1, 3), patBlock, '#', new ItemStack(materials, 1, 28)); //Cobalt
GameRegistry.addRecipe(new ItemStack(materials, 1, 4), patBlock, '#', new ItemStack(materials, 1, 29)); //Ardite
GameRegistry.addRecipe(new ItemStack(materials, 1, 5), patBlock, '#', new ItemStack(materials, 1, 30)); //Manyullyn
GameRegistry.addRecipe(new ItemStack(materials, 1, 13), patBlock, '#', new ItemStack(materials, 1, 31)); //Bronze
GameRegistry.addRecipe(new ItemStack(materials, 1, 15), patBlock, '#', new ItemStack(materials, 1, 32)); //Alumite
GameRegistry.addRecipe(new ItemStack(materials, 1, 16), patBlock, '#', new ItemStack(materials, 1, 33)); //Steel
GameRegistry.addRecipe(new ItemStack(materials, 9, 19), "m", 'm', new ItemStack(Item.ingotIron)); //Iron
GameRegistry.addRecipe(new ItemStack(materials, 9, 20), "m", 'm', new ItemStack(materials, 1, 9)); //Copper
GameRegistry.addRecipe(new ItemStack(materials, 9, 21), "m", 'm', new ItemStack(materials, 1, 10)); //Tin
GameRegistry.addRecipe(new ItemStack(materials, 9, 22), "m", 'm', new ItemStack(materials, 1, 12)); //Aluminum
GameRegistry.addRecipe(new ItemStack(materials, 9, 24), "m", 'm', new ItemStack(materials, 1, 14)); //Aluminum Brass
GameRegistry.addRecipe(new ItemStack(materials, 9, 27), "m", 'm', new ItemStack(materials, 1, 18)); //Obsidian
GameRegistry.addRecipe(new ItemStack(materials, 9, 28), "m", 'm', new ItemStack(materials, 1, 3)); //Cobalt
GameRegistry.addRecipe(new ItemStack(materials, 9, 29), "m", 'm', new ItemStack(materials, 1, 4)); //Ardite
GameRegistry.addRecipe(new ItemStack(materials, 9, 30), "m", 'm', new ItemStack(materials, 1, 5)); //Manyullyn
GameRegistry.addRecipe(new ItemStack(materials, 9, 31), "m", 'm', new ItemStack(materials, 1, 13)); //Bronze
GameRegistry.addRecipe(new ItemStack(materials, 9, 32), "m", 'm', new ItemStack(materials, 1, 15)); //Alumite
GameRegistry.addRecipe(new ItemStack(materials, 9, 33), "m", 'm', new ItemStack(materials, 1, 16)); //Steel
// stained Glass Recipes
String[] dyeTypes = { "dyeBlack", "dyeRed", "dyeGreen", "dyeBrown", "dyeBlue", "dyePurple", "dyeCyan", "dyeLightGray", "dyeGray", "dyePink", "dyeLime", "dyeYellow", "dyeLightBlue",
"dyeMagenta", "dyeOrange", "dyeWhite" };
String color = "";
for (int i = 0; i < 16; i++)
{
color = dyeTypes[15 - i];
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(Block.cloth, 8, i), patSurround, 'm', color, '#', new ItemStack(Block.cloth, 1, Short.MAX_VALUE)));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(stainedGlassClear, 8, i), patSurround, 'm', color, '#', clearGlass));
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(stainedGlassClear, 1, i), color, clearGlass));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(stainedGlassClear, 8, i), patSurround, 'm', color, '#', new ItemStack(stainedGlassClear, 1, Short.MAX_VALUE)));
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(stainedGlassClear, 1, i), color, new ItemStack(stainedGlassClear, 1, Short.MAX_VALUE)));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(stainedGlassClearPane, 8, i), patSurround, 'm', color, '#', glassPane));
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(stainedGlassClearPane, 1, i), color, glassPane));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(stainedGlassClearPane, 8, i), patSurround, 'm', color, '#', new ItemStack(stainedGlassClearPane, 1, Short.MAX_VALUE)));
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(stainedGlassClearPane, 1, i), color, new ItemStack(stainedGlassClearPane, 1, Short.MAX_VALUE)));
}
// Glass Recipes
GameRegistry.addRecipe(new ItemStack(Item.glassBottle, 3), new Object[] { "# #", " # ", '#', clearGlass });
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(Block.daylightSensor), new Object[] { "GGG", "QQQ", "WWW", 'G', "glass", 'Q', Item.netherQuartz, 'W', "slabWood" }));
GameRegistry.addRecipe(new ItemStack(Block.beacon, 1), new Object[] { "GGG", "GSG", "OOO", 'G', clearGlass, 'S', Item.netherStar, 'O', Block.obsidian });
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(glassPane, 16, 0), "GGG", "GGG", 'G', clearGlass));
// Smeltery Components Recipes
ItemStack searedBrick = new ItemStack(materials, 1, 2);
GameRegistry.addRecipe(new ItemStack(smeltery, 1, 0), "bbb", "b b", "bbb", 'b', searedBrick); //Controller
GameRegistry.addRecipe(new ItemStack(smeltery, 1, 1), "b b", "b b", "b b", 'b', searedBrick); //Drain
GameRegistry.addRecipe(new ItemStack(smeltery, 1, 2), "bb", "bb", 'b', searedBrick); //Bricks
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(lavaTank, 1, 0), patSurround, '#', searedBrick, 'm', "glass")); //Tank
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(lavaTank, 1, 1), "bgb", "ggg", "bgb", 'b', searedBrick, 'g', "glass")); //Glass
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(lavaTank, 1, 2), "bgb", "bgb", "bgb", 'b', searedBrick, 'g', "glass")); //Window
GameRegistry.addRecipe(new ItemStack(searedBlock, 1, 0), "bbb", "b b", "b b", 'b', searedBrick); //Table
GameRegistry.addRecipe(new ItemStack(searedBlock, 1, 1), "b b", " b ", 'b', searedBrick); //Faucet
GameRegistry.addRecipe(new ItemStack(searedBlock, 1, 2), "b b", "b b", "bbb", 'b', searedBrick); //Basin
GameRegistry.addRecipe(new ItemStack(castingChannel, 4, 0), "b b", "bbb", 'b', searedBrick); //Channel
// Jack o'Latern Recipe - Stone Torch
GameRegistry.addRecipe(new ItemStack(Block.pumpkinLantern, 1, 0), "p", "s", 'p', new ItemStack(Block.pumpkin), 's', new ItemStack(stoneTorch));
// Stone Torch Recipe
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(stoneTorch, 4), "p", "w", 'p', new ItemStack(Item.coal, 1, Short.MAX_VALUE), 'w', "stoneRod"));
// Stone Ladder Recipe
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(stoneLadder, 3), "w w", "www", "w w", 'w', "stoneRod"));
// Wooden Rail Recipe
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(woodenRail, 4, 0), "b b", "bxb", "b b", 'b', "plankWood", 'x', "stickWood"));
// Stonesticks Recipes
GameRegistry.addRecipe(new ItemStack(toolRod, 4, 1), "c", "c", 'c', new ItemStack(Block.stone));
GameRegistry.addRecipe(new ItemStack(toolRod, 2, 1), "c", "c", 'c', new ItemStack(Block.cobblestone));
//
ItemStack aluBrass = new ItemStack(materials, 1, 14);
// Clock Recipe - Vanilla alternativ
GameRegistry.addRecipe(new ItemStack(Item.pocketSundial), " i ", "iri", " i ", 'i', aluBrass, 'r', new ItemStack(Item.redstone));
// Gold Pressure Plate - Vanilla alternativ
GameRegistry.addRecipe(new ItemStack(Block.pressurePlateGold), "ii", 'i', aluBrass);
//Accessories
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(heartCanister, 1, 0), "##", "##", '#', "ingotNaturalAluminum"));
GameRegistry.addRecipe(new ItemStack(diamondApple), " d ", "d#d", " d ", 'd', new ItemStack(Item.diamond), '#', new ItemStack(Item.appleRed));
GameRegistry.addShapelessRecipe(new ItemStack(heartCanister, 1, 2), new ItemStack(diamondApple), new ItemStack(materials, 1, 8), new ItemStack(heartCanister, 1, 0), new ItemStack(
heartCanister, 1, 1));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(knapsack, 1, 0), "###", "rmr", "###", '#', new ItemStack(Item.leather), 'r', new ItemStack(toughRod, 1, 2), 'm', "ingotGold"));
GameRegistry.addRecipe(new ItemStack(knapsack, 1, 0), "###", "rmr", "###", '#', new ItemStack(Item.leather), 'r', new ItemStack(toughRod, 1, 2), 'm', aluBrass);
// Drying Rack Recipes
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(dryingRack, 1, 0), "bbb", 'b', "slabWood"));
//Landmine Recipes
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(landmine, 1, 0), "mcm", "rpr", 'm', "plankWood", 'c', new ItemStack(blankPattern, 1, 1), 'r', Item.redstone, 'p',
Block.pressurePlateStone));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(landmine, 1, 1), "mcm", "rpr", 'm', Block.stone, 'c', new ItemStack(blankPattern, 1, 1), 'r', Item.redstone, 'p',
Block.pressurePlateStone));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(landmine, 1, 2), "mcm", "rpr", 'm', Block.obsidian, 'c', new ItemStack(blankPattern, 1, 1), 'r', Item.redstone, 'p',
Block.pressurePlateStone));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(landmine, 1, 3), "mcm", "rpr", 'm', Item.redstoneRepeater, 'c', new ItemStack(blankPattern, 1, 1), 'r', Item.redstone, 'p',
Block.pressurePlateStone));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(signalBus.blockID, 1, 0), "www", "sss", 'w', lengthWire, 's', new ItemStack(Block.stoneSingleSlab, 1, OreDictionary.WILDCARD_VALUE)));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(signalTerminal.blockID, 1, 0), "b", "g", "b", 'b', new ItemStack(signalBus.blockID, 1, 0), 'g', new ItemStack(Block.glass, 1,
OreDictionary.WILDCARD_VALUE)));
GameRegistry.addRecipe(new ItemStack(lengthWire, 8), "a", "a", 'a', aluBrass);
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(spoolWire, 1, 256 - 8), "www", "wrw", "www", 'w', lengthWire, 'r', "stoneRod"));
GameRegistry.addRecipe(new SpoolRepairRecipe(new ItemStack(spoolWire, 1, 256), new ItemStack(lengthWire, 1)));
//Ultra hardcore recipes
GameRegistry.addRecipe(new ItemStack(goldHead), patSurround, '#', new ItemStack(Item.ingotGold), 'm', new ItemStack(Item.skull, 1, 3));
// Slab Smeltery Components Recipes
for (int i = 0; i < 7; i++)
{
GameRegistry.addRecipe(new ItemStack(speedSlab, 6, i), "bbb", 'b', new ItemStack(speedBlock, 1, i));
}
GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 0), "bbb", 'b', new ItemStack(smeltery, 1, 2));
GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 1), "bbb", 'b', new ItemStack(smeltery, 1, 4));
GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 2), "bbb", 'b', new ItemStack(smeltery, 1, 5));
GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 3), "bbb", 'b', new ItemStack(smeltery, 1, 6));
GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 4), "bbb", 'b', new ItemStack(smeltery, 1, 8));
GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 5), "bbb", 'b', new ItemStack(smeltery, 1, 9));
GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 6), "bbb", 'b', new ItemStack(smeltery, 1, 10));
GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 7), "bbb", 'b', new ItemStack(smeltery, 1, 11));
// Wool Slab Recipes
for (int sc = 0; sc <= 7; sc++)
{
GameRegistry.addRecipe(new ItemStack(woolSlab1, 6, sc), "www", 'w', new ItemStack(Block.cloth, 1, sc));
GameRegistry.addRecipe(new ItemStack(woolSlab2, 6, sc), "www", 'w', new ItemStack(Block.cloth, 1, sc + 8));
GameRegistry.addShapelessRecipe(new ItemStack(Block.cloth, 1, sc), new ItemStack(woolSlab1, 1, sc), new ItemStack(woolSlab1, 1, sc));
GameRegistry.addShapelessRecipe(new ItemStack(Block.cloth, 1, sc + 8), new ItemStack(woolSlab2, 1, sc), new ItemStack(woolSlab2, 1, sc));
}
GameRegistry.addRecipe(new ItemStack(woolSlab1, 6, 0), "www", 'w', new ItemStack(Block.cloth, 1, Short.MAX_VALUE));
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(Block.cloth, 1, 0), "slabCloth", "slabCloth"));
//Trap Recipes
GameRegistry.addRecipe(new ItemStack(punji, 5, 0), "b b", " b ", "b b", 'b', new ItemStack(Item.reed));
GameRegistry.addRecipe(new ItemStack(barricadeSpruce, 1, 0), "b", "b", 'b', new ItemStack(Block.wood, 1, 1));
GameRegistry.addRecipe(new ItemStack(barricadeBirch, 1, 0), "b", "b", 'b', new ItemStack(Block.wood, 1, 2));
GameRegistry.addRecipe(new ItemStack(barricadeJungle, 1, 0), "b", "b", 'b', new ItemStack(Block.wood, 1, 3));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(barricadeOak, 1, 0), "b", "b", 'b', "logWood"));
// Advanced WorkBench Recipes
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(craftingStationWood, 1, 0), "b", 'b', "crafterWood"));
//Slab crafters
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(craftingSlabWood, 6, 0), "bbb", 'b', "crafterWood"));
GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 0), "b", 'b', new ItemStack(craftingStationWood, 1, 0));
GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 1), "b", 'b', new ItemStack(toolStationWood, 1, 0));
GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 2), "b", 'b', new ItemStack(toolStationWood, 1, 1));
GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 2), "b", 'b', new ItemStack(toolStationWood, 1, 2));
GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 2), "b", 'b', new ItemStack(toolStationWood, 1, 3));
GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 2), "b", 'b', new ItemStack(toolStationWood, 1, 4));
GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 4), "b", 'b', new ItemStack(toolStationWood, 1, 5));
GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 3), "b", 'b', new ItemStack(toolStationWood, 1, 10));
GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 3), "b", 'b', new ItemStack(toolStationWood, 1, 11));
GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 3), "b", 'b', new ItemStack(toolStationWood, 1, 12));
GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 3), "b", 'b', new ItemStack(toolStationWood, 1, 13));
GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 5), "b", 'b', new ItemStack(toolForge, 1, Short.MAX_VALUE));
// EssenceExtractor Recipe
GameRegistry.addRecipe(new ItemStack(essenceExtractor, 1, 0), " b ", "eme", "mmm", 'b', Item.book, 'e', Item.emerald, 'm', Block.whiteStone);
//Slime Recipes
GameRegistry.addRecipe(new ItemStack(slimeGel, 1, 0), "##", "##", '#', strangeFood);
GameRegistry.addRecipe(new ItemStack(strangeFood, 4, 0), "#", '#', new ItemStack(slimeGel, 1, 0));
GameRegistry.addRecipe(new ItemStack(slimeGel, 1, 1), "##", "##", '#', Item.slimeBall);
GameRegistry.addRecipe(new ItemStack(Item.slimeBall, 4, 0), "#", '#', new ItemStack(slimeGel, 1, 1));
//slimeExplosive
GameRegistry.addShapelessRecipe(new ItemStack(slimeExplosive, 1, 0), Item.slimeBall, Block.tnt);
GameRegistry.addShapelessRecipe(new ItemStack(slimeExplosive, 1, 2), strangeFood, Block.tnt);
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(slimeExplosive, 1, 0), "slimeball", Block.tnt));
GameRegistry.addShapelessRecipe(new ItemStack(slimeChannel, 1, 0), new ItemStack(slimeGel, 1, Short.MAX_VALUE), new ItemStack(Item.redstone));
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(slimePad, 1, 0), slimeChannel, new ItemStack(slimeGel, 1, Short.MAX_VALUE), "slimeBall"));
}
private void addRecipesForFurnace ()
{
FurnaceRecipes.smelting().addSmelting(craftedSoil.blockID, 3, new ItemStack(craftedSoil, 1, 4), 0.2f); //Concecrated Soil
FurnaceRecipes.smelting().addSmelting(craftedSoil.blockID, 0, new ItemStack(materials, 1, 1), 2f); //Slime
FurnaceRecipes.smelting().addSmelting(craftedSoil.blockID, 1, new ItemStack(materials, 1, 2), 2f); //Seared brick item
FurnaceRecipes.smelting().addSmelting(craftedSoil.blockID, 2, new ItemStack(materials, 1, 17), 2f); //Blue Slime
//FurnaceRecipes.smelting().addSmelting(oreSlag.blockID, 1, new ItemStack(materials, 1, 3), 3f);
//FurnaceRecipes.smelting().addSmelting(oreSlag.blockID, 2, new ItemStack(materials, 1, 4), 3f);
FurnaceRecipes.smelting().addSmelting(oreSlag.blockID, 3, new ItemStack(materials, 1, 9), 0.5f);
FurnaceRecipes.smelting().addSmelting(oreSlag.blockID, 4, new ItemStack(materials, 1, 10), 0.5f);
FurnaceRecipes.smelting().addSmelting(oreSlag.blockID, 5, new ItemStack(materials, 1, 12), 0.5f);
FurnaceRecipes.smelting().addSmelting(oreBerries.itemID, 0, new ItemStack(materials, 1, 19), 0.2f);
FurnaceRecipes.smelting().addSmelting(oreBerries.itemID, 1, new ItemStack(Item.goldNugget), 0.2f);
FurnaceRecipes.smelting().addSmelting(oreBerries.itemID, 2, new ItemStack(materials, 1, 20), 0.2f);
FurnaceRecipes.smelting().addSmelting(oreBerries.itemID, 3, new ItemStack(materials, 1, 21), 0.2f);
FurnaceRecipes.smelting().addSmelting(oreBerries.itemID, 4, new ItemStack(materials, 1, 22), 0.2f);
//FurnaceRecipes.smelting().addSmelting(oreBerries.itemID, 5, new ItemStack(materials, 1, 23), 0.2f);
FurnaceRecipes.smelting().addSmelting(oreGravel.blockID, 0, new ItemStack(Item.ingotIron), 0.2f);
FurnaceRecipes.smelting().addSmelting(oreGravel.blockID, 1, new ItemStack(Item.ingotGold), 0.2f);
FurnaceRecipes.smelting().addSmelting(oreGravel.blockID, 2, new ItemStack(materials, 1, 9), 0.2f);
FurnaceRecipes.smelting().addSmelting(oreGravel.blockID, 3, new ItemStack(materials, 1, 10), 0.2f);
FurnaceRecipes.smelting().addSmelting(oreGravel.blockID, 4, new ItemStack(materials, 1, 12), 0.2f);
FurnaceRecipes.smelting().addSmelting(speedBlock.blockID, 0, new ItemStack(speedBlock, 1, 2), 0.2f);
}
private void addPartMapping ()
{
/* Tools */
patternOutputs = new Item[] { toolRod, pickaxeHead, shovelHead, hatchetHead, swordBlade, wideGuard, handGuard, crossbar, binding, frypanHead, signHead, knifeBlade, chiselHead, toughRod,
toughBinding, largePlate, broadAxeHead, scytheBlade, excavatorHead, largeSwordBlade, hammerHead, fullGuard, null, null, arrowhead };
int[] nonMetals = { 0, 1, 3, 4, 5, 6, 7, 8, 9 };
if (PHConstruct.craftMetalTools)
{
for (int mat = 0; mat < 18; mat++)
{
for (int meta = 0; meta < patternOutputs.length; meta++)
{
if (patternOutputs[meta] != null)
TConstructRegistry.addPartMapping(woodPattern.itemID, meta + 1, mat, new ItemStack(patternOutputs[meta], 1, mat));
}
}
}
else
{
for (int mat = 0; mat < nonMetals.length; mat++)
{
for (int meta = 0; meta < patternOutputs.length; meta++)
{
if (patternOutputs[meta] != null)
TConstructRegistry.addPartMapping(woodPattern.itemID, meta + 1, nonMetals[mat], new ItemStack(patternOutputs[meta], 1, nonMetals[mat]));
}
}
}
}
private void addRecipesForToolBuilder ()
{
ToolBuilder tb = ToolBuilder.instance;
tb.addNormalToolRecipe(pickaxe, pickaxeHead, toolRod, binding);
tb.addNormalToolRecipe(broadsword, swordBlade, toolRod, wideGuard);
tb.addNormalToolRecipe(hatchet, hatchetHead, toolRod);
tb.addNormalToolRecipe(shovel, shovelHead, toolRod);
tb.addNormalToolRecipe(longsword, swordBlade, toolRod, handGuard);
tb.addNormalToolRecipe(rapier, swordBlade, toolRod, crossbar);
tb.addNormalToolRecipe(frypan, frypanHead, toolRod);
tb.addNormalToolRecipe(battlesign, signHead, toolRod);
tb.addNormalToolRecipe(mattock, hatchetHead, toolRod, shovelHead);
tb.addNormalToolRecipe(dagger, knifeBlade, toolRod, crossbar);
tb.addNormalToolRecipe(cutlass, swordBlade, toolRod, fullGuard);
tb.addNormalToolRecipe(chisel, chiselHead, toolRod);
tb.addNormalToolRecipe(scythe, scytheBlade, toughRod, toughBinding, toughRod);
tb.addNormalToolRecipe(lumberaxe, broadAxeHead, toughRod, largePlate, toughBinding);
tb.addNormalToolRecipe(cleaver, largeSwordBlade, toughRod, largePlate, toughRod);
tb.addNormalToolRecipe(excavator, excavatorHead, toughRod, largePlate, toughBinding);
tb.addNormalToolRecipe(hammer, hammerHead, toughRod, largePlate, largePlate);
tb.addNormalToolRecipe(battleaxe, broadAxeHead, toughRod, broadAxeHead, toughBinding);
//tb.addNormalToolRecipe(shortbow, toolRod, bowstring, toolRod);
BowRecipe recipe = new BowRecipe(toolRod, bowstring, toolRod, shortbow);
tb.addCustomToolRecipe(recipe);
tb.addNormalToolRecipe(arrow, arrowhead, toolRod, fletching);
ItemStack diamond = new ItemStack(Item.diamond);
tb.registerToolMod(new ModRepair());
tb.registerToolMod(new ModDurability(new ItemStack[] { diamond }, 0, 500, 0f, 3, "Diamond", "\u00a7bDurability +500", "\u00a7b"));
tb.registerToolMod(new ModDurability(new ItemStack[] { new ItemStack(Item.emerald) }, 1, 0, 0.5f, 2, "Emerald", "\u00a72Durability +50%", "\u00a72"));
modE = new ModElectric();
tb.registerToolMod(modE);
ItemStack redstoneItem = new ItemStack(Item.redstone);
ItemStack redstoneBlock = new ItemStack(Block.blockRedstone);
tb.registerToolMod(new ModRedstone(new ItemStack[] { redstoneItem }, 2, 1));
tb.registerToolMod(new ModRedstone(new ItemStack[] { redstoneItem, redstoneItem }, 2, 2));
tb.registerToolMod(new ModRedstone(new ItemStack[] { redstoneBlock }, 2, 9));
tb.registerToolMod(new ModRedstone(new ItemStack[] { redstoneItem, redstoneBlock }, 2, 10));
tb.registerToolMod(new ModRedstone(new ItemStack[] { redstoneBlock, redstoneBlock }, 2, 18));
ItemStack lapisItem = new ItemStack(Item.dyePowder, 1, 4);
ItemStack lapisBlock = new ItemStack(Block.blockLapis);
modL = new ModLapis(new ItemStack[] { lapisItem }, 10, 1);
tb.registerToolMod(modL);
tb.registerToolMod(new ModLapis(new ItemStack[] { lapisItem, lapisItem }, 10, 2));
tb.registerToolMod(new ModLapis(new ItemStack[] { lapisBlock }, 10, 9));
tb.registerToolMod(new ModLapis(new ItemStack[] { lapisItem, lapisBlock }, 10, 10));
tb.registerToolMod(new ModLapis(new ItemStack[] { lapisBlock, lapisBlock }, 10, 18));
tb.registerToolMod(new ModInteger(new ItemStack[] { new ItemStack(materials, 1, 6) }, 4, "Moss", 3, "\u00a72", "Auto-Repair"));
ItemStack blazePowder = new ItemStack(Item.blazePowder);
tb.registerToolMod(new ModBlaze(new ItemStack[] { blazePowder }, 7, 1));
tb.registerToolMod(new ModBlaze(new ItemStack[] { blazePowder, blazePowder }, 7, 2));
tb.registerToolMod(new ModAutoSmelt(new ItemStack[] { new ItemStack(materials, 1, 7) }, 6, "Lava", "\u00a74", "Auto-Smelt"));
tb.registerToolMod(new ModInteger(new ItemStack[] { new ItemStack(materials, 1, 8) }, 8, "Necrotic", 1, "\u00a78", "Life Steal"));
ItemStack quartzItem = new ItemStack(Item.netherQuartz);
ItemStack quartzBlock = new ItemStack(Block.blockNetherQuartz, 1, Short.MAX_VALUE);
tb.registerToolMod(new ModAttack("Quartz", new ItemStack[] { quartzItem }, 11, 1));
tb.registerToolMod(new ModAttack("Quartz", new ItemStack[] { quartzItem, quartzItem }, 11, 2));
tb.registerToolMod(new ModAttack("Quartz", new ItemStack[] { quartzBlock }, 11, 4));
tb.registerToolMod(new ModAttack("Quartz", new ItemStack[] { quartzItem, quartzBlock }, 11, 5));
tb.registerToolMod(new ModAttack("Quartz", new ItemStack[] { quartzBlock, quartzBlock }, 11, 8));
tb.registerToolMod(new ModExtraModifier(new ItemStack[] { diamond, new ItemStack(Block.blockGold) }, "Tier1Free"));
tb.registerToolMod(new ModExtraModifier(new ItemStack[] { new ItemStack(Item.netherStar) }, "Tier2Free"));
ItemStack silkyJewel = new ItemStack(materials, 1, 26);
tb.registerToolMod(new ModButtertouch(new ItemStack[] { silkyJewel }, 12));
ItemStack piston = new ItemStack(Block.pistonBase);
tb.registerToolMod(new ModPiston(new ItemStack[] { piston }, 3, 1));
tb.registerToolMod(new ModPiston(new ItemStack[] { piston, piston }, 3, 2));
tb.registerToolMod(new ModInteger(new ItemStack[] { new ItemStack(Block.obsidian), new ItemStack(Item.enderPearl) }, 13, "Beheading", 1, "\u00a7d", "Beheading"));
ItemStack holySoil = new ItemStack(craftedSoil, 1, 4);
tb.registerToolMod(new ModSmite("Smite", new ItemStack[] { holySoil }, 14, 1));
tb.registerToolMod(new ModSmite("Smite", new ItemStack[] { holySoil, holySoil }, 14, 2));
ItemStack spidereyeball = new ItemStack(Item.fermentedSpiderEye);
tb.registerToolMod(new ModAntiSpider("Anti-Spider", new ItemStack[] { spidereyeball }, 15, 1));
tb.registerToolMod(new ModAntiSpider("Anti-Spider", new ItemStack[] { spidereyeball, spidereyeball }, 15, 2));
ItemStack obsidianPlate = new ItemStack(largePlate, 1, 6);
tb.registerToolMod(new ModReinforced(new ItemStack[] { obsidianPlate }, 16, 1));
TConstructRegistry.registerActiveToolMod(new TActiveOmniMod());
}
private void addRecipesForTableCasting ()
{
/* Smeltery */
ItemStack ingotcast = new ItemStack(metalPattern, 1, 0);
LiquidCasting tableCasting = TConstructRegistry.instance.getTableCasting();
//Blank
tableCasting.addCastingRecipe(new ItemStack(blankPattern, 1, 1), new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue), 80);
tableCasting.addCastingRecipe(new ItemStack(blankPattern, 1, 2), new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2), 80);
//Ingots
tableCasting.addCastingRecipe(new ItemStack(materials, 1, 2), new FluidStack(moltenStoneFluid, TConstruct.ingotLiquidValue), ingotcast, 80); //stone
//Buckets
ItemStack bucket = new ItemStack(Item.bucketEmpty);
for (int sc = 0; sc < 24; sc++)
{
tableCasting.addCastingRecipe(new ItemStack(buckets, 1, sc), new FluidStack(fluids[sc], FluidContainerRegistry.BUCKET_VOLUME), bucket, true, 10);
}
// Clear glass pane casting
tableCasting.addCastingRecipe(new ItemStack(glassPane), new FluidStack(moltenGlassFluid, 250), null, 80);
// Metal toolpart casting
liquids = new FluidStack[] { new FluidStack(moltenIronFluid, 1), new FluidStack(moltenCopperFluid, 1), new FluidStack(moltenCobaltFluid, 1), new FluidStack(moltenArditeFluid, 1),
new FluidStack(moltenManyullynFluid, 1), new FluidStack(moltenBronzeFluid, 1), new FluidStack(moltenAlumiteFluid, 1), new FluidStack(moltenObsidianFluid, 1),
new FluidStack(moltenSteelFluid, 1) };
int[] liquidDamage = new int[] { 2, 13, 10, 11, 12, 14, 15, 6, 16 };
int fluidAmount = 0;
Fluid fs = null;
for (int iter = 0; iter < patternOutputs.length; iter++)
{
if (patternOutputs[iter] != null)
{
ItemStack cast = new ItemStack(metalPattern, 1, iter + 1);
tableCasting.addCastingRecipe(cast, new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue), new ItemStack(patternOutputs[iter], 1, Short.MAX_VALUE), false, 50);
tableCasting.addCastingRecipe(cast, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2), new ItemStack(patternOutputs[iter], 1, Short.MAX_VALUE), false, 50);
for (int iterTwo = 0; iterTwo < liquids.length; iterTwo++)
{
fs = liquids[iterTwo].getFluid();
fluidAmount = ((IPattern) metalPattern).getPatternCost(cast) * TConstruct.ingotLiquidValue / 2;
ItemStack metalCast = new ItemStack(patternOutputs[iter], 1, liquidDamage[iterTwo]);
tableCasting.addCastingRecipe(metalCast, new FluidStack(fs, fluidAmount), cast, 50);
Smeltery.addMelting(FluidType.getFluidType(fs), metalCast, 0, fluidAmount);
}
}
}
ItemStack[] ingotShapes = { new ItemStack(Item.brick), new ItemStack(Item.netherrackBrick), new ItemStack(materials, 1, 2) };
for (int i = 0; i < ingotShapes.length; i++)
{
tableCasting.addCastingRecipe(ingotcast, new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue), ingotShapes[i], false, 50);
tableCasting.addCastingRecipe(ingotcast, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2), ingotShapes[i], false, 50);
}
ItemStack fullguardCast = new ItemStack(metalPattern, 1, 22);
tableCasting.addCastingRecipe(fullguardCast, new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue), new ItemStack(fullGuard, 1, Short.MAX_VALUE), false, 50);
tableCasting.addCastingRecipe(fullguardCast, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2), new ItemStack(fullGuard, 1, Short.MAX_VALUE), false, 50);
// Golden Food Stuff
FluidStack goldAmount = null;
if (PHConstruct.goldAppleRecipe)
{
goldAmount = new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 8);
}
else
{
goldAmount = new FluidStack(moltenGoldFluid, TConstruct.nuggetLiquidValue * 8);
}
tableCasting.addCastingRecipe(new ItemStack(Item.appleGold, 1), goldAmount, new ItemStack(Item.appleRed), true, 50);
tableCasting.addCastingRecipe(new ItemStack(Item.goldenCarrot, 1), goldAmount, new ItemStack(Item.carrot), true, 50);
tableCasting.addCastingRecipe(new ItemStack(Item.speckledMelon, 1), goldAmount, new ItemStack(Item.melon), true, 50);
tableCasting.addCastingRecipe(new ItemStack(goldHead), goldAmount, new ItemStack(Item.skull, 1, 3), true, 50);
}
private void addRecipesForBasinCasting ()
{
LiquidCasting basinCasting = TConstructRegistry.getBasinCasting();
// Block Casting
basinCasting.addCastingRecipe(new ItemStack(Block.blockIron), new FluidStack(moltenIronFluid, TConstruct.blockLiquidValue), null, true, 100); //Iron
basinCasting.addCastingRecipe(new ItemStack(Block.blockGold), new FluidStack(moltenGoldFluid, TConstruct.blockLiquidValue), null, true, 100); //gold
basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 3), new FluidStack(moltenCopperFluid, TConstruct.blockLiquidValue), null, true, 100); //copper
basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 5), new FluidStack(moltenTinFluid, TConstruct.blockLiquidValue), null, true, 100); //tin
basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 6), new FluidStack(moltenAluminumFluid, TConstruct.blockLiquidValue), null, true, 100); //aluminum
basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 0), new FluidStack(moltenCobaltFluid, TConstruct.blockLiquidValue), null, true, 100); //cobalt
basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 1), new FluidStack(moltenArditeFluid, TConstruct.blockLiquidValue), null, true, 100); //ardite
basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 4), new FluidStack(moltenBronzeFluid, TConstruct.blockLiquidValue), null, true, 100); //bronze
basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 7), new FluidStack(moltenAlubrassFluid, TConstruct.blockLiquidValue), null, true, 100); //albrass
basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 2), new FluidStack(moltenManyullynFluid, TConstruct.blockLiquidValue), null, true, 100); //manyullyn
basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 8), new FluidStack(moltenAlumiteFluid, TConstruct.blockLiquidValue), null, true, 100); //alumite
basinCasting.addCastingRecipe(new ItemStack(Block.obsidian), new FluidStack(moltenObsidianFluid, TConstruct.oreLiquidValue), null, true, 100);// obsidian
basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 9), new FluidStack(moltenSteelFluid, TConstruct.blockLiquidValue), null, true, 100); //steel
basinCasting.addCastingRecipe(new ItemStack(clearGlass, 1, 0), new FluidStack(moltenGlassFluid, FluidContainerRegistry.BUCKET_VOLUME), null, true, 100); //glass
basinCasting.addCastingRecipe(new ItemStack(smeltery, 1, 4), new FluidStack(moltenStoneFluid, TConstruct.ingotLiquidValue), null, true, 100); //seared stone
basinCasting.addCastingRecipe(new ItemStack(smeltery, 1, 5), new FluidStack(moltenStoneFluid, TConstruct.chunkLiquidValue), new ItemStack(Block.cobblestone), true, 100);
basinCasting.addCastingRecipe(new ItemStack(speedBlock, 1, 0), new FluidStack(moltenTinFluid, TConstruct.nuggetLiquidValue), new ItemStack(Block.gravel), true, 100); //brownstone
basinCasting.addCastingRecipe(new ItemStack(Block.whiteStone), new FluidStack(moltenEnderFluid, TConstruct.chunkLiquidValue), new ItemStack(Block.obsidian), true, 100); //endstone
basinCasting.addCastingRecipe(new ItemStack(metalBlock.blockID, 1, 10), new FluidStack(moltenEnderFluid, TConstruct.blockLiquidValue), null, true, 100); //ender
// basinCasting.addCastingRecipe(new ItemStack(slimeGel, 1, 0), new FluidStack(blueSlimeFluid, FluidContainerRegistry.BUCKET_VOLUME), null, true, 100);
//Armor casts
FluidRenderProperties frp = new FluidRenderProperties(Applications.BASIN.minHeight, 0.65F, Applications.BASIN);
FluidStack aluFlu = new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue * 10);
FluidStack gloFlu = new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 10);
ItemStack[] armor = { new ItemStack(helmetWood), new ItemStack(chestplateWood), new ItemStack(leggingsWood), new ItemStack(bootsWood) };
for (int sc = 0; sc < armor.length; sc++)
{
basinCasting.addCastingRecipe(new ItemStack(armorPattern, 1, sc), aluFlu, armor[sc], 50, frp);
basinCasting.addCastingRecipe(new ItemStack(armorPattern, 1, sc), gloFlu, armor[sc], 50, frp);
}
}
private void addRecipesForSmeltery ()
{
//Alloys Smelting
if (PHConstruct.harderBronze)
Smeltery.addAlloyMixing(new FluidStack(moltenBronzeFluid, 16), new FluidStack(moltenCopperFluid, 24), new FluidStack(moltenTinFluid, 8)); //Bronze
else
Smeltery.addAlloyMixing(new FluidStack(moltenBronzeFluid, 24), new FluidStack(moltenCopperFluid, 24), new FluidStack(moltenTinFluid, 8)); //Bronze
Smeltery.addAlloyMixing(new FluidStack(moltenAlubrassFluid, 32), new FluidStack(moltenAluminumFluid, 24), new FluidStack(moltenCopperFluid, 8)); //Aluminum Brass
Smeltery.addAlloyMixing(new FluidStack(moltenManyullynFluid, 16), new FluidStack(moltenCobaltFluid, 32), new FluidStack(moltenArditeFluid, 32)); //Manyullyn
Smeltery.addAlloyMixing(new FluidStack(moltenAlumiteFluid, 48), new FluidStack(moltenAluminumFluid, 80), new FluidStack(moltenIronFluid, 32), new FluidStack(moltenObsidianFluid, 32)); //Alumite
// Stone parts
for (int sc = 0; sc < patternOutputs.length; sc++)
{
if (patternOutputs[sc] != null)
{
Smeltery.addMelting(FluidType.Stone, new ItemStack(patternOutputs[sc], 1, 1), 1, (8 * ((IPattern) woodPattern).getPatternCost(new ItemStack(woodPattern, 1, sc + 1))) / 2);
}
}
// Chunks
Smeltery.addMelting(FluidType.Stone, new ItemStack(toolShard, 1, 1), 0, 4);
Smeltery.addMelting(FluidType.Iron, new ItemStack(toolShard, 1, 2), 0, TConstruct.chunkLiquidValue);
Smeltery.addMelting(FluidType.Obsidian, new ItemStack(toolShard, 1, 6), 0, TConstruct.chunkLiquidValue);
Smeltery.addMelting(FluidType.Cobalt, new ItemStack(toolShard, 1, 10), 0, TConstruct.chunkLiquidValue);
Smeltery.addMelting(FluidType.Ardite, new ItemStack(toolShard, 1, 11), 0, TConstruct.chunkLiquidValue);
Smeltery.addMelting(FluidType.Manyullyn, new ItemStack(toolShard, 1, 12), 0, TConstruct.chunkLiquidValue);
Smeltery.addMelting(FluidType.Copper, new ItemStack(toolShard, 1, 13), 0, TConstruct.chunkLiquidValue);
Smeltery.addMelting(FluidType.Bronze, new ItemStack(toolShard, 1, 14), 0, TConstruct.chunkLiquidValue);
Smeltery.addMelting(FluidType.Alumite, new ItemStack(toolShard, 1, 15), 0, TConstruct.chunkLiquidValue);
Smeltery.addMelting(FluidType.Steel, new ItemStack(toolShard, 1, 16), 0, TConstruct.chunkLiquidValue);
// Items
Smeltery.addMelting(FluidType.AluminumBrass, new ItemStack(blankPattern, 4, 1), -50, TConstruct.ingotLiquidValue);
Smeltery.addMelting(FluidType.Gold, new ItemStack(blankPattern, 4, 2), -50, TConstruct.ingotLiquidValue);
Smeltery.addMelting(FluidType.Ender, new ItemStack(Item.enderPearl, 4), 0, 250);
Smeltery.addMelting(metalBlock, 10, 50, new FluidStack(moltenEnderFluid, 1000));
Smeltery.addMelting(FluidType.Water, new ItemStack(Item.snowball, 1, 0), 0, 125);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.flintAndSteel, 1, 0), 0, TConstruct.ingotLiquidValue);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.compass, 1, 0), 0, TConstruct.ingotLiquidValue * 4);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.bucketEmpty), 0, TConstruct.ingotLiquidValue * 3);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.minecartEmpty), 0, TConstruct.ingotLiquidValue * 5);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.minecartCrate), 0, TConstruct.ingotLiquidValue * 5);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.minecartPowered), 0, TConstruct.ingotLiquidValue * 5);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.minecartHopper), 50, TConstruct.ingotLiquidValue * 10);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.doorIron), 0, TConstruct.ingotLiquidValue * 6);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.cauldron), 0, TConstruct.ingotLiquidValue * 7);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.shears), 0, TConstruct.oreLiquidValue);
// Smeltery.addMelting(FluidType.Slime, new ItemStack(slimeGel, 1, 0), 0, TConstruct.ingotLiquidValue * 4);
// Smeltery.addMelting(FluidType.Slime, new ItemStack(strangeFood, 1, 0), 0, TConstruct.ingotLiquidValue);
// Smeltery.addMelting(FluidType.Slime, new ItemStack(multiBrick, 1, 11), 0, TConstruct.ingotLiquidValue);
// Smeltery.addMelting(FluidType.Slime, new ItemStack(multiBrickFancy, 1, 11), 0, TConstruct.ingotLiquidValue);
//Blocks melt at themselves!
//Ore
Smeltery.addMelting(Block.oreIron, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 2));
Smeltery.addMelting(Block.oreGold, 0, 400, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2));
Smeltery.addMelting(oreGravel, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 2));
Smeltery.addMelting(oreGravel, 1, 400, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2));
//Blocks
Smeltery.addMelting(Block.blockIron, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 9));
Smeltery.addMelting(Block.blockGold, 0, 400, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 9));
Smeltery.addMelting(Block.obsidian, 0, 800, new FluidStack(moltenObsidianFluid, TConstruct.ingotLiquidValue * 2));
Smeltery.addMelting(Block.ice, 0, 75, new FluidStack(FluidRegistry.getFluid("water"), 1000));
Smeltery.addMelting(Block.blockSnow, 0, 75, new FluidStack(FluidRegistry.getFluid("water"), 500));
Smeltery.addMelting(Block.snow, 0, 75, new FluidStack(FluidRegistry.getFluid("water"), 250));
Smeltery.addMelting(Block.sand, 0, 625, new FluidStack(moltenGlassFluid, FluidContainerRegistry.BUCKET_VOLUME));
Smeltery.addMelting(Block.glass, 0, 625, new FluidStack(moltenGlassFluid, FluidContainerRegistry.BUCKET_VOLUME));
Smeltery.addMelting(Block.thinGlass, 0, 625, new FluidStack(moltenGlassFluid, 250));
Smeltery.addMelting(Block.stone, 0, 800, new FluidStack(moltenStoneFluid, TConstruct.ingotLiquidValue / 18));
Smeltery.addMelting(Block.cobblestone, 0, 800, new FluidStack(moltenStoneFluid, TConstruct.ingotLiquidValue / 18));
Smeltery.addMelting(clearGlass, 0, 500, new FluidStack(moltenGlassFluid, 1000));
Smeltery.addMelting(glassPane, 0, 350, new FluidStack(moltenGlassFluid, 250));
for (int i = 0; i < 16; i++)
{
Smeltery.addMelting(stainedGlassClear, i, 500, new FluidStack(moltenGlassFluid, 1000));
Smeltery.addMelting(stainedGlassClearPane, i, 350, new FluidStack(moltenGlassFluid, 250));
}
//Bricks
Smeltery.addMelting(multiBrick, 4, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue));
Smeltery.addMelting(multiBrickFancy, 4, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue));
Smeltery.addMelting(multiBrick, 5, 400, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue));
Smeltery.addMelting(multiBrickFancy, 5, 400, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue));
Smeltery.addMelting(multiBrick, 0, 800, new FluidStack(moltenObsidianFluid, TConstruct.ingotLiquidValue * 2));
Smeltery.addMelting(multiBrickFancy, 0, 800, new FluidStack(moltenObsidianFluid, TConstruct.ingotLiquidValue * 2));
//Vanilla blocks
Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.fenceIron), 0, TConstruct.ingotLiquidValue * 6 / 16);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.pressurePlateIron), 0, TConstruct.oreLiquidValue);
Smeltery.addMelting(FluidType.Gold, new ItemStack(Block.pressurePlateGold, 4), 0, TConstruct.oreLiquidValue);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.rail), 0, TConstruct.ingotLiquidValue * 6 / 16);
Smeltery.addMelting(FluidType.Gold, new ItemStack(Block.railPowered), 0, TConstruct.ingotLiquidValue);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.railDetector), 0, TConstruct.ingotLiquidValue);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.railActivator), 0, TConstruct.ingotLiquidValue);
Smeltery.addMelting(FluidType.Obsidian, new ItemStack(Block.enchantmentTable), 0, TConstruct.ingotLiquidValue * 4);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.cauldron), 0, TConstruct.ingotLiquidValue * 7);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.anvil, 1, 0), 200, TConstruct.ingotLiquidValue * 31);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.anvil, 1, 1), 200, TConstruct.ingotLiquidValue * 31);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.anvil, 1, 2), 200, TConstruct.ingotLiquidValue * 31);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.hopperBlock), 0, TConstruct.ingotLiquidValue * 5);
//Vanilla Armor
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.helmetIron, 1, 0), 50, TConstruct.ingotLiquidValue * 5);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.plateIron, 1, 0), 50, TConstruct.ingotLiquidValue * 8);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.legsIron, 1, 0), 50, TConstruct.ingotLiquidValue * 7);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.bootsIron, 1, 0), 50, TConstruct.ingotLiquidValue * 4);
Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.helmetGold, 1, 0), 50, TConstruct.ingotLiquidValue * 5);
Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.plateGold, 1, 0), 50, TConstruct.ingotLiquidValue * 8);
Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.legsGold, 1, 0), 50, TConstruct.ingotLiquidValue * 7);
Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.bootsGold, 1, 0), 50, TConstruct.ingotLiquidValue * 4);
Smeltery.addMelting(FluidType.Steel, new ItemStack(Item.helmetChain, 1, 0), 25, TConstruct.ingotLiquidValue);
Smeltery.addMelting(FluidType.Steel, new ItemStack(Item.plateChain, 1, 0), 50, TConstruct.oreLiquidValue);
Smeltery.addMelting(FluidType.Steel, new ItemStack(Item.legsChain, 1, 0), 50, TConstruct.oreLiquidValue);
Smeltery.addMelting(FluidType.Steel, new ItemStack(Item.bootsChain, 1, 0), 25, TConstruct.ingotLiquidValue);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.horseArmorIron, 1), 100, TConstruct.ingotLiquidValue * 8);
Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.horseArmorGold, 1), 100, TConstruct.ingotLiquidValue * 8);
//Vanilla tools
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.hoeIron, 1, 0), 0, TConstruct.oreLiquidValue);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.swordIron, 1, 0), 0, TConstruct.oreLiquidValue);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.shovelIron, 1, 0), 0, TConstruct.ingotLiquidValue);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.pickaxeIron, 1, 0), 0, TConstruct.ingotLiquidValue * 3);
Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.axeIron, 1, 0), 0, TConstruct.ingotLiquidValue * 3);
Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.hoeGold, 1, 0), 0, TConstruct.oreLiquidValue);
Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.swordGold, 1, 0), 0, TConstruct.oreLiquidValue);
Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.shovelGold, 1, 0), 0, TConstruct.ingotLiquidValue);
Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.pickaxeGold, 1, 0), 0, TConstruct.ingotLiquidValue * 3);
Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.axeGold, 1, 0), 0, TConstruct.ingotLiquidValue * 3);
}
private void addRecipesForDryingRack ()
{
//Drying rack
DryingRackRecipes.addDryingRecipe(Item.beefRaw, 20 * 60 * 5, new ItemStack(jerky, 1, 0));
DryingRackRecipes.addDryingRecipe(Item.chickenRaw, 20 * 60 * 5, new ItemStack(jerky, 1, 1));
DryingRackRecipes.addDryingRecipe(Item.porkRaw, 20 * 60 * 5, new ItemStack(jerky, 1, 2));
//DryingRackRecipes.addDryingRecipe(Item.muttonRaw, 20 * 60 * 5, new ItemStack(jerky, 1, 3));
DryingRackRecipes.addDryingRecipe(Item.fishRaw, 20 * 60 * 5, new ItemStack(jerky, 1, 4));
DryingRackRecipes.addDryingRecipe(Item.rottenFlesh, 20 * 60 * 5, new ItemStack(jerky, 1, 5));
//DryingRackRecipes.addDryingRecipe(new ItemStack(jerky, 1, 5), 20 * 60 * 10, Item.leather);
}
private void addRecipesForChisel ()
{
/* Detailing */
Detailing chiseling = TConstructRegistry.getChiselDetailing();
chiseling.addDetailing(Block.stone, 0, Block.stoneBrick, 0, chisel);
chiseling.addDetailing(speedBlock, 0, speedBlock, 1, chisel);
chiseling.addDetailing(speedBlock, 2, speedBlock, 3, chisel);
chiseling.addDetailing(speedBlock, 3, speedBlock, 4, chisel);
chiseling.addDetailing(speedBlock, 4, speedBlock, 5, chisel);
chiseling.addDetailing(speedBlock, 5, speedBlock, 6, chisel);
chiseling.addDetailing(Block.obsidian, 0, multiBrick, 0, chisel);
chiseling.addDetailing(Block.sandStone, 0, Block.sandStone, 2, chisel);
chiseling.addDetailing(Block.sandStone, 2, Block.sandStone, 1, chisel);
chiseling.addDetailing(Block.sandStone, 1, multiBrick, 1, chisel);
//chiseling.addDetailing(Block.netherrack, 0, multiBrick, 2, chisel);
//chiseling.addDetailing(Block.stone_refined, 0, multiBrick, 3, chisel);
chiseling.addDetailing(Item.ingotIron, 0, multiBrick, 4, chisel);
chiseling.addDetailing(Item.ingotGold, 0, multiBrick, 5, chisel);
chiseling.addDetailing(Item.dyePowder, 4, multiBrick, 6, chisel);
chiseling.addDetailing(Item.diamond, 0, multiBrick, 7, chisel);
chiseling.addDetailing(Item.redstone, 0, multiBrick, 8, chisel);
chiseling.addDetailing(Item.bone, 0, multiBrick, 9, chisel);
chiseling.addDetailing(Item.slimeBall, 0, multiBrick, 10, chisel);
chiseling.addDetailing(strangeFood, 0, multiBrick, 11, chisel);
chiseling.addDetailing(Block.whiteStone, 0, multiBrick, 12, chisel);
chiseling.addDetailing(materials, 18, multiBrick, 13, chisel);
// adding multiBrick / multiBrickFanxy meta 0-13 to list
for (int sc = 0; sc < 14; sc++)
{
chiseling.addDetailing(multiBrick, sc, multiBrickFancy, sc, chisel);
}
chiseling.addDetailing(Block.stoneBrick, 0, multiBrickFancy, 15, chisel);
chiseling.addDetailing(multiBrickFancy, 15, multiBrickFancy, 14, chisel);
chiseling.addDetailing(multiBrickFancy, 14, Block.stoneBrick, 3, chisel);
/*chiseling.addDetailing(multiBrick, 14, multiBrickFancy, 14, chisel);
chiseling.addDetailing(multiBrick, 15, multiBrickFancy, 15, chisel);*/
chiseling.addDetailing(smeltery, 4, smeltery, 6, chisel);
chiseling.addDetailing(smeltery, 6, smeltery, 11, chisel);
chiseling.addDetailing(smeltery, 11, smeltery, 2, chisel);
chiseling.addDetailing(smeltery, 2, smeltery, 8, chisel);
chiseling.addDetailing(smeltery, 8, smeltery, 9, chisel);
chiseling.addDetailing(smeltery, 9, smeltery, 10, chisel);
}
void setupToolTabs ()
{
TConstructRegistry.materialTab.init(new ItemStack(titleIcon, 1, 255));
TConstructRegistry.blockTab.init(new ItemStack(toolStationWood));
ItemStack tool = new ItemStack(longsword, 1, 0);
NBTTagCompound compound = new NBTTagCompound();
compound.setCompoundTag("InfiTool", new NBTTagCompound());
compound.getCompoundTag("InfiTool").setInteger("RenderHead", 2);
compound.getCompoundTag("InfiTool").setInteger("RenderHandle", 0);
compound.getCompoundTag("InfiTool").setInteger("RenderAccessory", 10);
tool.setTagCompound(compound);
//TConstruct.
TConstructRegistry.toolTab.init(tool);
}
public void addLoot ()
{
//Item, min, max, weight
ChestGenHooks.getInfo(ChestGenHooks.DUNGEON_CHEST).addItem(new WeightedRandomChestContent(new ItemStack(heartCanister, 1, 1), 1, 1, 5));
ChestGenHooks.getInfo(ChestGenHooks.PYRAMID_DESERT_CHEST).addItem(new WeightedRandomChestContent(new ItemStack(heartCanister, 1, 1), 1, 1, 10));
ChestGenHooks.getInfo(ChestGenHooks.PYRAMID_JUNGLE_CHEST).addItem(new WeightedRandomChestContent(new ItemStack(heartCanister, 1, 1), 1, 1, 10));
tinkerHouseChest = new ChestGenHooks("TinkerHouse", new WeightedRandomChestContent[0], 3, 27);
tinkerHouseChest.addItem(new WeightedRandomChestContent(new ItemStack(heartCanister, 1, 1), 1, 1, 1));
int[] validTypes = { 0, 1, 2, 3, 4, 5, 6, 8, 9, 13, 14, 17 };
Item[] partTypes = { pickaxeHead, shovelHead, hatchetHead, binding, swordBlade, wideGuard, handGuard, crossbar, knifeBlade, frypanHead, signHead, chiselHead };
for (int partIter = 0; partIter < partTypes.length; partIter++)
{
for (int typeIter = 0; typeIter < validTypes.length; typeIter++)
{
tinkerHouseChest.addItem(new WeightedRandomChestContent(new ItemStack(partTypes[partIter], 1, validTypes[typeIter]), 1, 1, 15));
}
}
tinkerHousePatterns = new ChestGenHooks("TinkerPatterns", new WeightedRandomChestContent[0], 5, 30);
for (int i = 0; i < 13; i++)
{
tinkerHousePatterns.addItem(new WeightedRandomChestContent(new ItemStack(woodPattern, 1, i + 1), 1, 3, 20));
}
tinkerHousePatterns.addItem(new WeightedRandomChestContent(new ItemStack(woodPattern, 1, 22), 1, 3, 40));
}
public static String[] liquidNames;
public void oreRegistry ()
{
OreDictionary.registerOre("oreCobalt", new ItemStack(oreSlag, 1, 1));
OreDictionary.registerOre("oreArdite", new ItemStack(oreSlag, 1, 2));
OreDictionary.registerOre("oreCopper", new ItemStack(oreSlag, 1, 3));
OreDictionary.registerOre("oreTin", new ItemStack(oreSlag, 1, 4));
OreDictionary.registerOre("oreNaturalAluminum", new ItemStack(oreSlag, 1, 5));
OreDictionary.registerOre("oreIron", new ItemStack(oreGravel, 1, 0));
OreDictionary.registerOre("oreGold", new ItemStack(oreGravel, 1, 1));
OreDictionary.registerOre("oreCobalt", new ItemStack(oreGravel, 1, 5));
OreDictionary.registerOre("oreCopper", new ItemStack(oreGravel, 1, 2));
OreDictionary.registerOre("oreTin", new ItemStack(oreGravel, 1, 3));
OreDictionary.registerOre("oreNaturalAluminum", new ItemStack(oreGravel, 1, 4));
OreDictionary.registerOre("ingotCobalt", new ItemStack(materials, 1, 3));
OreDictionary.registerOre("ingotArdite", new ItemStack(materials, 1, 4));
OreDictionary.registerOre("ingotManyullyn", new ItemStack(materials, 1, 5));
OreDictionary.registerOre("ingotCopper", new ItemStack(materials, 1, 9));
OreDictionary.registerOre("ingotTin", new ItemStack(materials, 1, 10));
OreDictionary.registerOre("ingotNaturalAluminum", new ItemStack(materials, 1, 11));
OreDictionary.registerOre("naturalAluminum", new ItemStack(materials, 1, 12));
OreDictionary.registerOre("ingotBronze", new ItemStack(materials, 1, 13));
OreDictionary.registerOre("ingotAluminumBrass", new ItemStack(materials, 1, 14));
OreDictionary.registerOre("ingotAlumite", new ItemStack(materials, 1, 15));
OreDictionary.registerOre("ingotSteel", new ItemStack(materials, 1, 16));
ensureOreIsRegistered("ingotIron", new ItemStack(Item.ingotIron));
ensureOreIsRegistered("ingotGold", new ItemStack(Item.ingotGold));
OreDictionary.registerOre("ingotObsidian", new ItemStack(materials, 1, 18));
OreDictionary.registerOre("blockCobalt", new ItemStack(metalBlock, 1, 0));
OreDictionary.registerOre("blockArdite", new ItemStack(metalBlock, 1, 1));
OreDictionary.registerOre("blockManyullyn", new ItemStack(metalBlock, 1, 2));
OreDictionary.registerOre("blockCopper", new ItemStack(metalBlock, 1, 3));
OreDictionary.registerOre("blockBronze", new ItemStack(metalBlock, 1, 4));
OreDictionary.registerOre("blockTin", new ItemStack(metalBlock, 1, 5));
OreDictionary.registerOre("blockNaturalAluminum", new ItemStack(metalBlock, 1, 6));
OreDictionary.registerOre("blockAluminumBrass", new ItemStack(metalBlock, 1, 7));
OreDictionary.registerOre("blockAlumite", new ItemStack(metalBlock, 1, 8));
OreDictionary.registerOre("blockSteel", new ItemStack(metalBlock, 1, 9));
ensureOreIsRegistered("blockIron", new ItemStack(Block.blockIron));
ensureOreIsRegistered("blockGold", new ItemStack(Block.blockGold));
OreDictionary.registerOre("nuggetIron", new ItemStack(materials, 1, 19));
OreDictionary.registerOre("nuggetIron", new ItemStack(oreBerries, 1, 0));
OreDictionary.registerOre("nuggetCopper", new ItemStack(materials, 1, 20));
OreDictionary.registerOre("nuggetCopper", new ItemStack(oreBerries, 1, 2));
OreDictionary.registerOre("nuggetTin", new ItemStack(materials, 1, 21));
OreDictionary.registerOre("nuggetTin", new ItemStack(oreBerries, 1, 3));
OreDictionary.registerOre("nuggetNaturalAluminum", new ItemStack(materials, 1, 22));
OreDictionary.registerOre("nuggetNaturalAluminum", new ItemStack(oreBerries, 1, 4));
OreDictionary.registerOre("nuggetAluminumBrass", new ItemStack(materials, 1, 24));
OreDictionary.registerOre("nuggetObsidian", new ItemStack(materials, 1, 27));
OreDictionary.registerOre("nuggetCobalt", new ItemStack(materials, 1, 28));
OreDictionary.registerOre("nuggetArdite", new ItemStack(materials, 1, 29));
OreDictionary.registerOre("nuggetManyullyn", new ItemStack(materials, 1, 30));
OreDictionary.registerOre("nuggetBronze", new ItemStack(materials, 1, 31));
OreDictionary.registerOre("nuggetAlumite", new ItemStack(materials, 1, 32));
OreDictionary.registerOre("nuggetSteel", new ItemStack(materials, 1, 33));
OreDictionary.registerOre("nuggetGold", new ItemStack(oreBerries, 1, 1));
ensureOreIsRegistered("nuggetGold", new ItemStack(Item.goldNugget));
OreDictionary.registerOre("slabCloth", new ItemStack(woolSlab1, 1, Short.MAX_VALUE));
OreDictionary.registerOre("slabCloth", new ItemStack(woolSlab2, 1, Short.MAX_VALUE));
ensureOreIsRegistered("stoneMossy", new ItemStack(Block.stoneBrick, 1, 1));
ensureOreIsRegistered("stoneMossy", new ItemStack(Block.cobblestoneMossy));
ensureOreIsRegistered("crafterWood", new ItemStack(Block.workbench, 1));
String[] matNames = { "wood", "stone", "iron", "flint", "cactus", "bone", "obsidian", "netherrack", "slime", "paper", "cobalt", "ardite", "manyullyn", "copper", "bronze", "alumite", "steel",
"blueslime" };
for (int i = 0; i < matNames.length; i++)
OreDictionary.registerOre(matNames[i] + "Rod", new ItemStack(toolRod, 1, i));
OreDictionary.registerOre("thaumiumRod", new ItemStack(toolRod, 1, 31));
String[] glassTypes = { "glassBlack", "glassRed", "glassGreen", "glassBrown", "glassBlue", "glassPurple", "glassCyan", "glassLightGray", "glassGray", "glassPink", "glassLime", "glassYellow",
"glassLightBlue", "glassMagenta", "glassOrange", "glassWhite" };
for (int i = 0; i < 16; i++)
{
OreDictionary.registerOre(glassTypes[15 - i], new ItemStack(stainedGlassClear, 1, i));
}
BlockDispenser.dispenseBehaviorRegistry.putObject(titleIcon, new TDispenserBehaviorSpawnEgg());
BlockDispenser.dispenseBehaviorRegistry.putObject(arrow, new TDispenserBehaviorArrow());
//Vanilla stuff
OreDictionary.registerOre("slimeball", new ItemStack(Item.slimeBall));
OreDictionary.registerOre("slimeball", new ItemStack(strangeFood, 1, 0));
OreDictionary.registerOre("glass", new ItemStack(clearGlass));
OreDictionary.registerOre("glass", new ItemStack(Block.glass));
RecipeRemover.removeShapedRecipe(new ItemStack(Block.pistonStickyBase));
RecipeRemover.removeShapedRecipe(new ItemStack(Item.magmaCream));
RecipeRemover.removeShapedRecipe(new ItemStack(Item.leash));
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(Block.pistonStickyBase), "slimeball", Block.pistonBase));
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(Item.magmaCream), "slimeball", Item.blazePowder));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(Item.leash, 2), "ss ", "sS ", " s", 's', Item.silk, 'S', "slimeball"));
}
private void ensureOreIsRegistered (String oreName, ItemStack is)
{
int oreId = OreDictionary.getOreID(is);
if (oreId == -1)
{
OreDictionary.registerOre(oreName, is);
}
}
public static boolean thaumcraftAvailable;
public void intermodCommunication ()
{
if (Loader.isModLoaded("Thaumcraft"))
{
FMLInterModComms.sendMessage("Thaumcraft", "harvestClickableCrop", new ItemStack(oreBerry, 1, 12));
FMLInterModComms.sendMessage("Thaumcraft", "harvestClickableCrop", new ItemStack(oreBerry, 1, 13));
FMLInterModComms.sendMessage("Thaumcraft", "harvestClickableCrop", new ItemStack(oreBerry, 1, 14));
FMLInterModComms.sendMessage("Thaumcraft", "harvestClickableCrop", new ItemStack(oreBerry, 1, 15));
FMLInterModComms.sendMessage("Thaumcraft", "harvestClickableCrop", new ItemStack(oreBerrySecond, 1, 12));
FMLInterModComms.sendMessage("Thaumcraft", "harvestClickableCrop", new ItemStack(oreBerrySecond, 1, 13));
}
if (Loader.isModLoaded("Mystcraft"))
{
MystImcHandler.blacklistFluids();
}
if (Loader.isModLoaded("BuildCraft|Transport"))
{
BCImcHandler.registerFacades();
}
/* FORESTRY
* Edit these strings to change what items are added to the backpacks
* Format info: "[backpack ID]@[item ID].[metadata or *]:[next item]" and so on
* Avaliable backpack IDs: forester, miner, digger, hunter, adventurer, builder
* May add more backpack items later - Spyboticsguy
*/
if (Loader.isModLoaded("Forestry"))
{
String builderItems = "builder@" + String.valueOf(stoneTorch.blockID) + ":*";
FMLInterModComms.sendMessage("Forestry", "add-backpack-items", builderItems);
}
if (!Loader.isModLoaded("AppliedEnergistics"))
{
AEImcHandler.registerForSpatialIO();
}
}
private static boolean initRecipes;
public static void modRecipes ()
{
if (!initRecipes)
{
initRecipes = true;
if (PHConstruct.removeVanillaToolRecipes)
{
RecipeRemover.removeAnyRecipe(new ItemStack(Item.pickaxeWood));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.axeWood));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.shovelWood));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.hoeWood));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.swordWood));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.pickaxeStone));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.axeStone));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.shovelStone));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.hoeStone));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.swordStone));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.pickaxeIron));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.axeIron));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.shovelIron));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.hoeIron));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.swordIron));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.pickaxeDiamond));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.axeDiamond));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.shovelDiamond));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.hoeDiamond));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.swordDiamond));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.pickaxeGold));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.axeGold));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.shovelGold));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.hoeGold));
RecipeRemover.removeAnyRecipe(new ItemStack(Item.swordGold));
}
}
}
public static void addShapedRecipeFirst (List recipeList, ItemStack itemstack, Object... objArray)
{
String var3 = "";
int var4 = 0;
int var5 = 0;
int var6 = 0;
if (objArray[var4] instanceof String[])
{
String[] var7 = ((String[]) objArray[var4++]);
for (int var8 = 0; var8 < var7.length; ++var8)
{
String var9 = var7[var8];
++var6;
var5 = var9.length();
var3 = var3 + var9;
}
}
else
{
while (objArray[var4] instanceof String)
{
String var11 = (String) objArray[var4++];
++var6;
var5 = var11.length();
var3 = var3 + var11;
}
}
HashMap var12;
for (var12 = new HashMap(); var4 < objArray.length; var4 += 2)
{
Character var13 = (Character) objArray[var4];
ItemStack var14 = null;
if (objArray[var4 + 1] instanceof Item)
{
var14 = new ItemStack((Item) objArray[var4 + 1]);
}
else if (objArray[var4 + 1] instanceof Block)
{
var14 = new ItemStack((Block) objArray[var4 + 1], 1, Short.MAX_VALUE);
}
else if (objArray[var4 + 1] instanceof ItemStack)
{
var14 = (ItemStack) objArray[var4 + 1];
}
var12.put(var13, var14);
}
ItemStack[] var15 = new ItemStack[var5 * var6];
for (int var16 = 0; var16 < var5 * var6; ++var16)
{
char var10 = var3.charAt(var16);
if (var12.containsKey(Character.valueOf(var10)))
{
var15[var16] = ((ItemStack) var12.get(Character.valueOf(var10))).copy();
}
else
{
var15[var16] = null;
}
}
ShapedRecipes var17 = new ShapedRecipes(var5, var6, var15, itemstack);
recipeList.add(0, var17);
}
public void modIntegration ()
{
ItemStack ironpick = ToolBuilder.instance.buildTool(new ItemStack(TContent.pickaxeHead, 1, 6), new ItemStack(TContent.toolRod, 1, 2), new ItemStack(TContent.binding, 1, 6), "");
/* IC2 */
//ItemStack reBattery = ic2.api.item.Items.getItem("reBattery");
Object reBattery = getStaticItem("reBattery", "ic2.core.Ic2Items");
if (reBattery != null)
{
modE.batteries.add((ItemStack) reBattery);
}
//ItemStack chargedReBattery = ic2.api.item.Items.getItem("chargedReBattery");
Object chargedReBattery = getStaticItem("chargedReBattery", "ic2.core.Ic2Items");
if (chargedReBattery != null)
{
modE.batteries.add((ItemStack) chargedReBattery);
}
//ItemStack electronicCircuit = ic2.api.item.Items.getItem("electronicCircuit");
Object electronicCircuit = getStaticItem("electronicCircuit", "ic2.core.Ic2Items");
if (electronicCircuit != null)
modE.circuits.add((ItemStack) electronicCircuit);
if (chargedReBattery != null && electronicCircuit != null)
TConstructClientRegistry.registerManualModifier("electricmod", ironpick.copy(), (ItemStack) chargedReBattery, (ItemStack) electronicCircuit);
/* Thaumcraft */
Object obj = getStaticItem("itemResource", "thaumcraft.common.config.ConfigItems");
if (obj != null)
{
TConstruct.logger.info("Thaumcraft detected. Adding thaumium tools.");
thaumcraftAvailable = true;
TConstructClientRegistry.addMaterialRenderMapping(31, "tinker", "thaumium", true);
TConstructRegistry.addToolMaterial(31, "Thaumium", 3, 400, 700, 2, 1.3F, 0, 0f, "\u00A75", "Thaumic");
PatternBuilder.instance.registerFullMaterial(new ItemStack((Item) obj, 1, 2), 2, "Thaumium", new ItemStack(toolShard, 1, 31), new ItemStack(toolRod, 1, 31), 31);
for (int meta = 0; meta < patternOutputs.length; meta++)
{
if (patternOutputs[meta] != null)
TConstructRegistry.addPartMapping(woodPattern.itemID, meta + 1, 31, new ItemStack(patternOutputs[meta], 1, 31));
}
TConstructRegistry.addBowstringMaterial(1, 2, new ItemStack((Item) obj, 1, 7), new ItemStack(bowstring, 1, 1), 1F, 1F, 0.9f);
TConstructRegistry.addBowMaterial(31, 576, 40, 1.2f);
TConstructRegistry.addArrowMaterial(31, 1.8F, 0.5F, 100F);
}
else
{
TConstruct.logger.warning("Thaumcraft not detected.");
}
if (Loader.isModLoaded("Natura"))
{
try
{
Object plantItem = getStaticItem("plantItem", "mods.natura.common.NContent");
TConstructRegistry.addBowstringMaterial(2, 2, new ItemStack((Item) plantItem, 1, 7), new ItemStack(bowstring, 1, 2), 1.2F, 0.8F, 1.3f);
}
catch (Exception e)
{
} //No need to handle
}
ItemStack ingotcast = new ItemStack(metalPattern, 1, 0);
LiquidCasting tableCasting = TConstructRegistry.instance.getTableCasting();
LiquidCasting basinCasting = TConstructRegistry.instance.getBasinCasting();
/* Thermal Expansion */
ArrayList<ItemStack> ores = OreDictionary.getOres("ingotNickel");
if (ores.size() > 0)
{
tableCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenNickelFluid, TConstruct.ingotLiquidValue), ingotcast, 80);
}
ores = OreDictionary.getOres("ingotLead");
if (ores.size() > 0)
{
tableCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenLeadFluid, TConstruct.ingotLiquidValue), ingotcast, 80);
}
ores = OreDictionary.getOres("ingotSilver");
if (ores.size() > 0)
{
tableCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenSilverFluid, TConstruct.ingotLiquidValue), ingotcast, 80);
}
ores = OreDictionary.getOres("ingotPlatinum");
if (ores.size() > 0)
{
tableCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenShinyFluid, TConstruct.ingotLiquidValue), ingotcast, 80);
}
ores = OreDictionary.getOres("ingotInvar");
if (ores.size() > 0)
{
tableCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenInvarFluid, TConstruct.ingotLiquidValue), ingotcast, 80);
Smeltery.addAlloyMixing(new FluidStack(moltenInvarFluid, 24), new FluidStack(moltenIronFluid, 16), new FluidStack(moltenNickelFluid, 8)); //Invar
}
ores = OreDictionary.getOres("ingotElectrum");
if (ores.size() > 0)
{
tableCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenElectrumFluid, TConstruct.ingotLiquidValue), ingotcast, 80);
Smeltery.addAlloyMixing(new FluidStack(moltenElectrumFluid, 16), new FluidStack(moltenGoldFluid, 8), new FluidStack(moltenSilverFluid, 8)); //Electrum
}
ores = OreDictionary.getOres("blockNickel");
if (ores.size() > 0)
{
basinCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenNickelFluid, TConstruct.blockLiquidValue), null, 100);
}
ores = OreDictionary.getOres("blockLead");
if (ores.size() > 0)
{
basinCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenLeadFluid, TConstruct.blockLiquidValue), null, 100);
}
ores = OreDictionary.getOres("blockSilver");
if (ores.size() > 0)
{
basinCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenSilverFluid, TConstruct.blockLiquidValue), null, 100);
}
ores = OreDictionary.getOres("blockPlatinum");
if (ores.size() > 0)
{
basinCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenShinyFluid, TConstruct.blockLiquidValue), null, 100);
}
ores = OreDictionary.getOres("blockInvar");
if (ores.size() > 0)
{
basinCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenInvarFluid, TConstruct.blockLiquidValue), null, 100);
}
ores = OreDictionary.getOres("blockElectrum");
if (ores.size() > 0)
{
basinCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenElectrumFluid, TConstruct.blockLiquidValue), null, 100);
}
}
public static Object getStaticItem (String name, String classPackage)
{
try
{
Class clazz = Class.forName(classPackage);
Field field = clazz.getDeclaredField(name);
Object ret = field.get(null);
if (ret != null && (ret instanceof ItemStack || ret instanceof Item))
return ret;
return null;
}
catch (Exception e)
{
TConstruct.logger.warning("Could not find " + name);
return null;
}
}
@Override
public int getBurnTime (ItemStack fuel)
{
if (fuel.itemID == materials.itemID && fuel.getItemDamage() == 7)
return 26400;
if (fuel.itemID == woodPattern.itemID)
return 800;
return 0;
}
public void addOreDictionarySmelteryRecipes ()
{
List<FluidType> exceptions = Arrays.asList(new FluidType[] { FluidType.Water, FluidType.Stone, FluidType.Ender, FluidType.Glass, FluidType.Slime });
for (FluidType ft : FluidType.values())
{
if (exceptions.contains(ft))
continue;
// Nuggets
Smeltery.addDictionaryMelting("nugget" + ft.toString(), ft, -100, TConstruct.nuggetLiquidValue);
// Ingots, Dust
registerIngotCasting(ft);
Smeltery.addDictionaryMelting("ingot" + ft.toString(), ft, -50, TConstruct.ingotLiquidValue);
Smeltery.addDictionaryMelting("dust" + ft.toString(), ft, -75, TConstruct.ingotLiquidValue);
// Factorization support
Smeltery.addDictionaryMelting("crystalline" + ft.toString(), ft, -50, TConstruct.ingotLiquidValue);
// Ores
Smeltery.addDictionaryMelting("ore" + ft.toString(), ft, 0, TConstruct.oreLiquidValue);
// NetherOres support
Smeltery.addDictionaryMelting("oreNether" + ft.toString(), ft, 75, TConstruct.oreLiquidValue * 2);
// Blocks
Smeltery.addDictionaryMelting("block" + ft.toString(), ft, 100, TConstruct.blockLiquidValue);
if (ft.isToolpart)
{
registerPatternMaterial("ingot" + ft.toString(), 2, ft.toString());
registerPatternMaterial("block" + ft.toString(), 18, ft.toString());
}
}
registerPatternMaterial("plankWood", 2, "Wood");
registerPatternMaterial("stickWood", 1, "Wood");
registerPatternMaterial("slabWood", 1, "Wood");
}
private void registerPatternMaterial (String oreName, int value, String materialName)
{
for (ItemStack ore : OreDictionary.getOres(oreName))
{
PatternBuilder.instance.registerMaterial(ore, value, materialName);
}
}
private void registerIngotCasting (FluidType ft)
{
ItemStack pattern = new ItemStack(TContent.metalPattern, 1, 0);
LiquidCasting tableCasting = TConstructRegistry.instance.getTableCasting();
for (ItemStack ore : OreDictionary.getOres("ingot" + ft.toString()))
{
tableCasting.addCastingRecipe(pattern, new FluidStack(TContent.moltenAlubrassFluid, TConstruct.ingotLiquidValue), new ItemStack(ore.itemID, 1, ore.getItemDamage()), false, 50);
tableCasting.addCastingRecipe(pattern, new FluidStack(TContent.moltenGoldFluid, TConstruct.oreLiquidValue), new ItemStack(ore.itemID, 1, ore.getItemDamage()), false, 50);
tableCasting.addCastingRecipe(new ItemStack(ore.itemID, 1, ore.getItemDamage()), new FluidStack(ft.fluid, TConstruct.ingotLiquidValue), pattern, 80);
}
}
}
|
diff --git a/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/storage/jdbc/optimisation/db/DB2SingleDbJDBCConnection.java b/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/storage/jdbc/optimisation/db/DB2SingleDbJDBCConnection.java
index 69d2612ed..3a2fc8611 100644
--- a/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/storage/jdbc/optimisation/db/DB2SingleDbJDBCConnection.java
+++ b/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/storage/jdbc/optimisation/db/DB2SingleDbJDBCConnection.java
@@ -1,80 +1,80 @@
/*
* Copyright (C) 2003-2010 eXo Platform SAS.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* 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.exoplatform.services.jcr.impl.storage.jdbc.optimisation.db;
import org.exoplatform.services.jcr.impl.util.io.FileCleaner;
import org.exoplatform.services.jcr.storage.value.ValueStoragePluginProvider;
import java.io.File;
import java.sql.Connection;
import java.sql.SQLException;
/**
* Created by The eXo Platform SAS.
*
* Date: 8 02 2011
*
* @author <a href="mailto:[email protected]">Anatoliy Bazko</a>
* @version $Id: MSSQLSingleDbJDBCConnection.java 34360 2010-11-11 11:11:11Z tolusha $
*/
public class DB2SingleDbJDBCConnection extends SingleDbJDBCConnection
{
/**
* Sybase Singledatabase JDBC Connection constructor.
*
* @param dbConnection
* JDBC connection, should be opened before
* @param readOnly
* boolean if true the dbConnection was marked as READ-ONLY.
* @param containerName
* Workspace Storage Container name (see configuration)
* @param valueStorageProvider
* External Value Storages provider
* @param maxBufferSize
* Maximum buffer size (see configuration)
* @param swapDirectory
* Swap directory File (see configuration)
* @param swapCleaner
* Swap cleaner (internal FileCleaner).
* @throws SQLException
*
* @see org.exoplatform.services.jcr.impl.util.io.FileCleaner
*/
public DB2SingleDbJDBCConnection(Connection dbConnection, boolean readOnly, String containerName,
ValueStoragePluginProvider valueStorageProvider, int maxBufferSize, File swapDirectory, FileCleaner swapCleaner)
throws SQLException
{
super(dbConnection, readOnly, containerName, valueStorageProvider, maxBufferSize, swapDirectory, swapCleaner);
}
/**
* {@inheritDoc}
*/
@Override
protected void prepareQueries() throws SQLException
{
super.prepareQueries();
FIND_NODES_AND_PROPERTIES =
"select J.*, P.ID AS P_ID, P.NAME AS P_NAME, P.VERSION AS P_VERSION, P.P_TYPE, P.P_MULTIVALUED,"
+ " V.DATA, V.ORDER_NUM, V.STORAGE_DESC from JCR_SVALUE V, JCR_SITEM P"
+ " join (select A.* from"
+ " (select Row_Number() over (order by I.ID) as r__, I.ID, I.PARENT_ID, I.NAME, I.VERSION, I.I_INDEX, I.N_ORDER_NUM"
- + " from JCR_SITEM I where I.CONTAINER_NAME='?' and I.I_CLASS=1) as A where A.r__ <= ? and A.r__ > ?"
+ + " from JCR_SITEM I where I.CONTAINER_NAME=? and I.I_CLASS=1) as A where A.r__ <= ? and A.r__ > ?"
+ ") J on P.PARENT_ID = J.ID"
- + " where P.I_CLASS=2 and P.CONTAINER_NAME='?' and V.PROPERTY_ID=P.ID order by J.ID";
+ + " where P.I_CLASS=2 and P.CONTAINER_NAME=? and V.PROPERTY_ID=P.ID order by J.ID";
}
}
| false | true | protected void prepareQueries() throws SQLException
{
super.prepareQueries();
FIND_NODES_AND_PROPERTIES =
"select J.*, P.ID AS P_ID, P.NAME AS P_NAME, P.VERSION AS P_VERSION, P.P_TYPE, P.P_MULTIVALUED,"
+ " V.DATA, V.ORDER_NUM, V.STORAGE_DESC from JCR_SVALUE V, JCR_SITEM P"
+ " join (select A.* from"
+ " (select Row_Number() over (order by I.ID) as r__, I.ID, I.PARENT_ID, I.NAME, I.VERSION, I.I_INDEX, I.N_ORDER_NUM"
+ " from JCR_SITEM I where I.CONTAINER_NAME='?' and I.I_CLASS=1) as A where A.r__ <= ? and A.r__ > ?"
+ ") J on P.PARENT_ID = J.ID"
+ " where P.I_CLASS=2 and P.CONTAINER_NAME='?' and V.PROPERTY_ID=P.ID order by J.ID";
}
| protected void prepareQueries() throws SQLException
{
super.prepareQueries();
FIND_NODES_AND_PROPERTIES =
"select J.*, P.ID AS P_ID, P.NAME AS P_NAME, P.VERSION AS P_VERSION, P.P_TYPE, P.P_MULTIVALUED,"
+ " V.DATA, V.ORDER_NUM, V.STORAGE_DESC from JCR_SVALUE V, JCR_SITEM P"
+ " join (select A.* from"
+ " (select Row_Number() over (order by I.ID) as r__, I.ID, I.PARENT_ID, I.NAME, I.VERSION, I.I_INDEX, I.N_ORDER_NUM"
+ " from JCR_SITEM I where I.CONTAINER_NAME=? and I.I_CLASS=1) as A where A.r__ <= ? and A.r__ > ?"
+ ") J on P.PARENT_ID = J.ID"
+ " where P.I_CLASS=2 and P.CONTAINER_NAME=? and V.PROPERTY_ID=P.ID order by J.ID";
}
|
diff --git a/VectorTileMap/src/org/mapsforge/android/utils/GlConfigChooser.java b/VectorTileMap/src/org/mapsforge/android/utils/GlConfigChooser.java
index 16e015e..621af76 100644
--- a/VectorTileMap/src/org/mapsforge/android/utils/GlConfigChooser.java
+++ b/VectorTileMap/src/org/mapsforge/android/utils/GlConfigChooser.java
@@ -1,159 +1,158 @@
package org.mapsforge.android.utils;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLDisplay;
import android.opengl.GLSurfaceView;
import android.util.Log;
/**
*
*
*/
public class GlConfigChooser implements GLSurfaceView.EGLConfigChooser {
static private final String TAG = "ConfigChooser";
/**
*
*/
public static int stencilSize = 0;
@Override
public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display) {
mValue = new int[1];
// Try to find a normal multisample configuration first.
int[] configSpec = {
EGL10.EGL_RED_SIZE, 5,
EGL10.EGL_GREEN_SIZE, 6,
EGL10.EGL_BLUE_SIZE, 5,
- EGL10.EGL_ALPHA_SIZE, 0,
- EGL10.EGL_DEPTH_SIZE, 24,
+ EGL10.EGL_ALPHA_SIZE, 8,
+ EGL10.EGL_DEPTH_SIZE, 16,
// Requires that setEGLContextClientVersion(2) is called on the view.
EGL10.EGL_RENDERABLE_TYPE, 4 /* EGL_OPENGL_ES2_BIT */,
- // EGL10.EGL_SAMPLE_BUFFERS, 1 /* true */,
- // EGL10.EGL_SAMPLES, 2,
EGL10.EGL_STENCIL_SIZE, 8,
EGL10.EGL_NONE };
if (!egl.eglChooseConfig(display, configSpec, null, 0, mValue)) {
throw new IllegalArgumentException("eglChooseConfig failed");
}
int numConfigs = mValue[0];
if (numConfigs <= 0) {
stencilSize = 4;
configSpec = new int[] {
- EGL10.EGL_RED_SIZE, 5,
- EGL10.EGL_GREEN_SIZE, 6,
- EGL10.EGL_BLUE_SIZE, 5,
- EGL10.EGL_ALPHA_SIZE, 0,
- EGL10.EGL_DEPTH_SIZE, 24,
+ // EGL10.EGL_RENDERABLE_TYPE, 4, EGL10.EGL_NONE };
+ EGL10.EGL_RED_SIZE, 8,
+ EGL10.EGL_GREEN_SIZE, 8,
+ EGL10.EGL_BLUE_SIZE, 8,
+ EGL10.EGL_ALPHA_SIZE, 8,
+ EGL10.EGL_DEPTH_SIZE, 16,
EGL10.EGL_RENDERABLE_TYPE, 4 /* EGL_OPENGL_ES2_BIT */,
EGL10.EGL_STENCIL_SIZE, 8,
EGL10.EGL_NONE };
if (!egl.eglChooseConfig(display, configSpec, null, 0, mValue)) {
- throw new IllegalArgumentException("3rd eglChooseConfig failed");
+ throw new IllegalArgumentException("eglChooseConfig failed");
}
numConfigs = mValue[0];
if (numConfigs <= 0) {
throw new IllegalArgumentException("No configs match configSpec");
}
} else {
stencilSize = 8;
}
// Get all matching configurations.
EGLConfig[] configs = new EGLConfig[numConfigs];
if (!egl.eglChooseConfig(display, configSpec, configs, numConfigs, mValue)) {
throw new IllegalArgumentException("data eglChooseConfig failed");
}
// CAUTION! eglChooseConfigs returns configs with higher bit depth
// first: Even though we asked for rgb565 configurations, rgb888
// configurations are considered to be "better" and returned first.
// You need to explicitly filter the data returned by eglChooseConfig!
for (int i = 0; i < configs.length; ++i) {
Log.i(TAG, printConfig(egl, display, configs[i]));
}
// int index = -1;
// for (int i = 0; i < configs.length; ++i) {
// // if (findConfigAttrib(egl, display, configs[i], EGL10.EGL_RED_SIZE, 0) == 8
// // &&
// // findConfigAttrib(egl, display, configs[i], EGL10.EGL_ALPHA_SIZE, 0) == 0) {
// // index = i;
// // break;
// // }
// // else
// if (findConfigAttrib(egl, display, configs[i], EGL10.EGL_RED_SIZE, 0) == 8
// &&
// findConfigAttrib(egl, display, configs[i], EGL10.EGL_ALPHA_SIZE, 0) == 0
// &&
// findConfigAttrib(egl, display, configs[i], EGL10.EGL_DEPTH_SIZE, 0) == 24) {
// index = i;
// break;
// }
// }
// if (index == -1) {
// Log.w(TAG, "Did not find sane config, using first");
// index = 0;
// }
int index = 0;
Log.i(TAG, "using: " + printConfig(egl, display, configs[index]));
EGLConfig config = configs.length > 0 ? configs[index] : null;
if (config == null) {
throw new IllegalArgumentException("No config chosen");
}
return config;
}
// from quake2android
private String printConfig(EGL10 egl, EGLDisplay display,
EGLConfig config) {
int r = findConfigAttrib(egl, display, config, EGL10.EGL_RED_SIZE, 0);
int g = findConfigAttrib(egl, display, config, EGL10.EGL_GREEN_SIZE, 0);
int b = findConfigAttrib(egl, display, config, EGL10.EGL_BLUE_SIZE, 0);
int a = findConfigAttrib(egl, display, config, EGL10.EGL_ALPHA_SIZE, 0);
int d = findConfigAttrib(egl, display, config, EGL10.EGL_DEPTH_SIZE, 0);
int s = findConfigAttrib(egl, display, config, EGL10.EGL_STENCIL_SIZE, 0);
/*
* EGL_CONFIG_CAVEAT value #define EGL_NONE 0x3038 #define EGL_SLOW_CONFIG 0x3050 #define
* EGL_NON_CONFORMANT_CONFIG 0x3051
*/
return String.format("EGLConfig rgba=%d%d%d%d depth=%d stencil=%d",
Integer.valueOf(r), Integer.valueOf(g),
Integer.valueOf(b), Integer.valueOf(a), Integer.valueOf(d),
Integer.valueOf(s))
+ " native="
+ findConfigAttrib(egl, display, config, EGL10.EGL_NATIVE_RENDERABLE, 0)
+ " buffer="
+ findConfigAttrib(egl, display, config, EGL10.EGL_BUFFER_SIZE, 0)
+ String.format(
" caveat=0x%04x",
Integer.valueOf(findConfigAttrib(egl, display, config,
EGL10.EGL_CONFIG_CAVEAT, 0)));
}
private int findConfigAttrib(EGL10 egl, EGLDisplay display, EGLConfig config,
int attribute, int defaultValue) {
if (egl.eglGetConfigAttrib(display, config, attribute, mValue)) {
return mValue[0];
}
return defaultValue;
}
private int[] mValue;
}
| false | true | public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display) {
mValue = new int[1];
// Try to find a normal multisample configuration first.
int[] configSpec = {
EGL10.EGL_RED_SIZE, 5,
EGL10.EGL_GREEN_SIZE, 6,
EGL10.EGL_BLUE_SIZE, 5,
EGL10.EGL_ALPHA_SIZE, 0,
EGL10.EGL_DEPTH_SIZE, 24,
// Requires that setEGLContextClientVersion(2) is called on the view.
EGL10.EGL_RENDERABLE_TYPE, 4 /* EGL_OPENGL_ES2_BIT */,
// EGL10.EGL_SAMPLE_BUFFERS, 1 /* true */,
// EGL10.EGL_SAMPLES, 2,
EGL10.EGL_STENCIL_SIZE, 8,
EGL10.EGL_NONE };
if (!egl.eglChooseConfig(display, configSpec, null, 0, mValue)) {
throw new IllegalArgumentException("eglChooseConfig failed");
}
int numConfigs = mValue[0];
if (numConfigs <= 0) {
stencilSize = 4;
configSpec = new int[] {
EGL10.EGL_RED_SIZE, 5,
EGL10.EGL_GREEN_SIZE, 6,
EGL10.EGL_BLUE_SIZE, 5,
EGL10.EGL_ALPHA_SIZE, 0,
EGL10.EGL_DEPTH_SIZE, 24,
EGL10.EGL_RENDERABLE_TYPE, 4 /* EGL_OPENGL_ES2_BIT */,
EGL10.EGL_STENCIL_SIZE, 8,
EGL10.EGL_NONE };
if (!egl.eglChooseConfig(display, configSpec, null, 0, mValue)) {
throw new IllegalArgumentException("3rd eglChooseConfig failed");
}
numConfigs = mValue[0];
if (numConfigs <= 0) {
throw new IllegalArgumentException("No configs match configSpec");
}
} else {
stencilSize = 8;
}
// Get all matching configurations.
EGLConfig[] configs = new EGLConfig[numConfigs];
if (!egl.eglChooseConfig(display, configSpec, configs, numConfigs, mValue)) {
throw new IllegalArgumentException("data eglChooseConfig failed");
}
// CAUTION! eglChooseConfigs returns configs with higher bit depth
// first: Even though we asked for rgb565 configurations, rgb888
// configurations are considered to be "better" and returned first.
// You need to explicitly filter the data returned by eglChooseConfig!
for (int i = 0; i < configs.length; ++i) {
Log.i(TAG, printConfig(egl, display, configs[i]));
}
// int index = -1;
// for (int i = 0; i < configs.length; ++i) {
// // if (findConfigAttrib(egl, display, configs[i], EGL10.EGL_RED_SIZE, 0) == 8
// // &&
// // findConfigAttrib(egl, display, configs[i], EGL10.EGL_ALPHA_SIZE, 0) == 0) {
// // index = i;
// // break;
// // }
// // else
// if (findConfigAttrib(egl, display, configs[i], EGL10.EGL_RED_SIZE, 0) == 8
// &&
// findConfigAttrib(egl, display, configs[i], EGL10.EGL_ALPHA_SIZE, 0) == 0
// &&
// findConfigAttrib(egl, display, configs[i], EGL10.EGL_DEPTH_SIZE, 0) == 24) {
// index = i;
// break;
// }
// }
// if (index == -1) {
// Log.w(TAG, "Did not find sane config, using first");
// index = 0;
// }
int index = 0;
Log.i(TAG, "using: " + printConfig(egl, display, configs[index]));
EGLConfig config = configs.length > 0 ? configs[index] : null;
if (config == null) {
throw new IllegalArgumentException("No config chosen");
}
return config;
}
| public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display) {
mValue = new int[1];
// Try to find a normal multisample configuration first.
int[] configSpec = {
EGL10.EGL_RED_SIZE, 5,
EGL10.EGL_GREEN_SIZE, 6,
EGL10.EGL_BLUE_SIZE, 5,
EGL10.EGL_ALPHA_SIZE, 8,
EGL10.EGL_DEPTH_SIZE, 16,
// Requires that setEGLContextClientVersion(2) is called on the view.
EGL10.EGL_RENDERABLE_TYPE, 4 /* EGL_OPENGL_ES2_BIT */,
EGL10.EGL_STENCIL_SIZE, 8,
EGL10.EGL_NONE };
if (!egl.eglChooseConfig(display, configSpec, null, 0, mValue)) {
throw new IllegalArgumentException("eglChooseConfig failed");
}
int numConfigs = mValue[0];
if (numConfigs <= 0) {
stencilSize = 4;
configSpec = new int[] {
// EGL10.EGL_RENDERABLE_TYPE, 4, EGL10.EGL_NONE };
EGL10.EGL_RED_SIZE, 8,
EGL10.EGL_GREEN_SIZE, 8,
EGL10.EGL_BLUE_SIZE, 8,
EGL10.EGL_ALPHA_SIZE, 8,
EGL10.EGL_DEPTH_SIZE, 16,
EGL10.EGL_RENDERABLE_TYPE, 4 /* EGL_OPENGL_ES2_BIT */,
EGL10.EGL_STENCIL_SIZE, 8,
EGL10.EGL_NONE };
if (!egl.eglChooseConfig(display, configSpec, null, 0, mValue)) {
throw new IllegalArgumentException("eglChooseConfig failed");
}
numConfigs = mValue[0];
if (numConfigs <= 0) {
throw new IllegalArgumentException("No configs match configSpec");
}
} else {
stencilSize = 8;
}
// Get all matching configurations.
EGLConfig[] configs = new EGLConfig[numConfigs];
if (!egl.eglChooseConfig(display, configSpec, configs, numConfigs, mValue)) {
throw new IllegalArgumentException("data eglChooseConfig failed");
}
// CAUTION! eglChooseConfigs returns configs with higher bit depth
// first: Even though we asked for rgb565 configurations, rgb888
// configurations are considered to be "better" and returned first.
// You need to explicitly filter the data returned by eglChooseConfig!
for (int i = 0; i < configs.length; ++i) {
Log.i(TAG, printConfig(egl, display, configs[i]));
}
// int index = -1;
// for (int i = 0; i < configs.length; ++i) {
// // if (findConfigAttrib(egl, display, configs[i], EGL10.EGL_RED_SIZE, 0) == 8
// // &&
// // findConfigAttrib(egl, display, configs[i], EGL10.EGL_ALPHA_SIZE, 0) == 0) {
// // index = i;
// // break;
// // }
// // else
// if (findConfigAttrib(egl, display, configs[i], EGL10.EGL_RED_SIZE, 0) == 8
// &&
// findConfigAttrib(egl, display, configs[i], EGL10.EGL_ALPHA_SIZE, 0) == 0
// &&
// findConfigAttrib(egl, display, configs[i], EGL10.EGL_DEPTH_SIZE, 0) == 24) {
// index = i;
// break;
// }
// }
// if (index == -1) {
// Log.w(TAG, "Did not find sane config, using first");
// index = 0;
// }
int index = 0;
Log.i(TAG, "using: " + printConfig(egl, display, configs[index]));
EGLConfig config = configs.length > 0 ? configs[index] : null;
if (config == null) {
throw new IllegalArgumentException("No config chosen");
}
return config;
}
|
diff --git a/omod/src/main/java/org/openmrs/web/controller/report/export/DataExportFormController.java b/omod/src/main/java/org/openmrs/web/controller/report/export/DataExportFormController.java
index 9b5b90b..5d6e00b 100644
--- a/omod/src/main/java/org/openmrs/web/controller/report/export/DataExportFormController.java
+++ b/omod/src/main/java/org/openmrs/web/controller/report/export/DataExportFormController.java
@@ -1,246 +1,246 @@
/**
* The contents of this file are subject to the OpenMRS Public License
* Version 1.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.web.controller.report.export;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.Concept;
import org.openmrs.api.APIException;
import org.openmrs.api.context.Context;
import org.openmrs.layout.web.address.AddressSupport;
import org.openmrs.layout.web.address.AddressTemplate;
import org.openmrs.module.reportingcompatibility.reporting.export.DataExportUtil;
import org.openmrs.propertyeditor.LocationEditor;
import org.openmrs.reporting.ReportObjectService;
import org.openmrs.reporting.export.DataExportReportObject;
import org.openmrs.reporting.export.ExportColumn;
import org.openmrs.util.OpenmrsConstants;
import org.openmrs.web.WebConstants;
import org.springframework.beans.propertyeditors.CustomNumberEditor;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.view.RedirectView;
public class DataExportFormController extends SimpleFormController {
/** Logger for this class and subclasses */
protected final Log log = LogFactory.getLog(getClass());
/**
* Allows for Integers to be used as values in input tags. Normally, only strings and lists are
* expected
*
* @see org.springframework.web.servlet.mvc.BaseCommandController#initBinder(javax.servlet.http.HttpServletRequest,
* org.springframework.web.bind.ServletRequestDataBinder)
*/
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
super.initBinder(request, binder);
binder.registerCustomEditor(java.lang.Integer.class, new CustomNumberEditor(java.lang.Integer.class, true));
binder.registerCustomEditor(org.openmrs.Location.class, new LocationEditor());
}
/**
* The onSubmit function receives the form/command object that was modified by the input form
* and saves it to the db
*
* @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse, java.lang.Object,
* org.springframework.validation.BindException)
*/
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object obj,
BindException errors) throws Exception {
HttpSession httpSession = request.getSession();
String view = getFormView();
if (Context.isAuthenticated()) {
DataExportReportObject report = (DataExportReportObject) obj;
// create PatientSet from selected values in report
String[] patientIds = request.getParameterValues("patientId");
report.setPatientIds(new Vector<Integer>());
if (patientIds != null)
for (String patientId : patientIds)
if (patientId != null && !patientId.equals(""))
report.addPatientId(Integer.valueOf(patientId));
Integer location = ServletRequestUtils.getIntParameter(request, "location", 0);
if (location > 0)
report.setLocation(Context.getLocationService().getLocation(location));
//String startDate = ServletRequestUtils.getStringParameter(request, "startDate", "");
//String endDate = ServletRequestUtils.getStringParameter(request, "endDate", "");
//if (!startDate.equals(""))
// report.setStartDate(dateFormat.parse(startDate));
//if (!endDate.equals(""))
// report.setEndDate(dateFormat.parse(endDate));
// define columns for report object
String[] columnIds = request.getParameterValues("columnId");
report.setColumns(new Vector<ExportColumn>());
if (columnIds != null) {
for (String columnId : columnIds) {
String columnName = request.getParameter("simpleName_" + columnId);
if (columnName != null)
// simple column
report.addSimpleColumn(columnName, request.getParameter("simpleValue_" + columnId));
else {
columnName = request.getParameter("conceptColumnName_" + columnId);
if (columnName != null) {
// concept column
String conceptId = request.getParameter("conceptId_" + columnId);
try {
Integer.valueOf(conceptId);
}
catch (NumberFormatException e) {
// for backwards compatibility to pre 1.0.43
Concept c = Context.getConceptService().getConceptByName(conceptId);
if (c == null)
- throw new APIException("Concept name : + '" + conceptId
+ throw new APIException("Concept name : '" + conceptId
+ "' could not be found in the dictionary");
conceptId = c.getConceptId().toString();
}
String[] extras = request.getParameterValues("conceptExtra_" + columnId);
String modifier = request.getParameter("conceptModifier_" + columnId);
String modifierNumStr = request.getParameter("conceptModifierNum_" + columnId);
Integer modifierNum = null;
if (modifierNumStr.length() > 0)
modifierNum = Integer.valueOf(modifierNumStr);
report.addConceptColumn(columnName, modifier, modifierNum, conceptId, extras);
} else {
columnName = request.getParameter("calculatedName_" + columnId);
if (columnName != null) {
// calculated column
String columnValue = request.getParameter("calculatedValue_" + columnId);
report.addCalculatedColumn(columnName, columnValue);
} else {
columnName = request.getParameter("cohortName_" + columnId);
if (columnName != null) {
// cohort column
String cohortIdValue = request.getParameter("cohortIdValue_" + columnId);
String filterIdValue = request.getParameter("filterIdValue_" + columnId);
String searchIdValue = request.getParameter("patientSearchIdValue_" + columnId);
String valueIfTrue = request.getParameter("cohortIfTrue_" + columnId);
String valueIfFalse = request.getParameter("cohortIfFalse_" + columnId);
Integer cohortId = null;
Integer filterId = null;
Integer searchId = null;
try {
cohortId = Integer.valueOf(cohortIdValue);
}
catch (Exception ex) {}
try {
filterId = Integer.valueOf(filterIdValue);
}
catch (Exception ex) {}
try {
searchId = Integer.valueOf(searchIdValue);
}
catch (Exception ex) {}
if (cohortId != null || filterId != null || searchId != null)
report.addCohortColumn(columnName, cohortId, filterId, searchId, valueIfTrue,
valueIfFalse);
} else
log.warn("Cannot determine column type for column: " + columnId);
}
}
}
}
}
String saveAsNew = ServletRequestUtils.getStringParameter(request, "saveAsNew", "");
if (!saveAsNew.equals(""))
report.setReportObjectId(null);
ReportObjectService rs = (ReportObjectService) Context.getService(ReportObjectService.class);
rs.saveReportObject(report);
// if there are cached results for this report, delete them
File cachedLastReportRun = DataExportUtil.getGeneratedFile(report);
if (cachedLastReportRun != null && cachedLastReportRun.exists()) {
cachedLastReportRun.delete();
}
String action = ServletRequestUtils.getRequiredStringParameter(request, "action");
MessageSourceAccessor msa = getMessageSourceAccessor();
if (action.equals(msa.getMessage("reportingcompatibility.DataExport.save"))) {
view = getSuccessView();
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "reportingcompatibility.DataExport.saved");
} else {
view = request.getContextPath() + "/moduleServlet/reportingcompatibility/dataExportServlet?dataExportId="
+ report.getReportObjectId();
}
}
return new ModelAndView(new RedirectView(view));
}
/**
* This is called prior to displaying a form for the first time. It tells Spring the
* form/command object to load into the request
*
* @see org.springframework.web.servlet.mvc.AbstractFormController#formBackingObject(javax.servlet.http.HttpServletRequest)
*/
protected Object formBackingObject(HttpServletRequest request) throws ServletException {
DataExportReportObject report = null;
if (Context.isAuthenticated()) {
ReportObjectService rs = (ReportObjectService) Context.getService(ReportObjectService.class);
String reportId = request.getParameter("dataExportId");
if (reportId != null)
report = (DataExportReportObject) rs.getReportObject(Integer.valueOf(reportId));
}
if (report == null)
report = new DataExportReportObject();
return report;
}
protected Map<String, Object> referenceData(HttpServletRequest request, Object obj, Errors errs) throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
String defaultVerbose = "false";
if (Context.isAuthenticated()) {
defaultVerbose = Context.getAuthenticatedUser().getUserProperty(OpenmrsConstants.USER_PROPERTY_SHOW_VERBOSE);
AddressSupport support = AddressSupport.getInstance();
AddressTemplate template = support.getDefaultLayoutTemplate();
map.put("addressTemplate", template);
}
map.put("defaultVerbose", defaultVerbose.equals("true") ? true : false);
map.put("personAttributeTypes", Context.getPersonService().getAllPersonAttributeTypes());
return map;
}
}
| true | true | protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object obj,
BindException errors) throws Exception {
HttpSession httpSession = request.getSession();
String view = getFormView();
if (Context.isAuthenticated()) {
DataExportReportObject report = (DataExportReportObject) obj;
// create PatientSet from selected values in report
String[] patientIds = request.getParameterValues("patientId");
report.setPatientIds(new Vector<Integer>());
if (patientIds != null)
for (String patientId : patientIds)
if (patientId != null && !patientId.equals(""))
report.addPatientId(Integer.valueOf(patientId));
Integer location = ServletRequestUtils.getIntParameter(request, "location", 0);
if (location > 0)
report.setLocation(Context.getLocationService().getLocation(location));
//String startDate = ServletRequestUtils.getStringParameter(request, "startDate", "");
//String endDate = ServletRequestUtils.getStringParameter(request, "endDate", "");
//if (!startDate.equals(""))
// report.setStartDate(dateFormat.parse(startDate));
//if (!endDate.equals(""))
// report.setEndDate(dateFormat.parse(endDate));
// define columns for report object
String[] columnIds = request.getParameterValues("columnId");
report.setColumns(new Vector<ExportColumn>());
if (columnIds != null) {
for (String columnId : columnIds) {
String columnName = request.getParameter("simpleName_" + columnId);
if (columnName != null)
// simple column
report.addSimpleColumn(columnName, request.getParameter("simpleValue_" + columnId));
else {
columnName = request.getParameter("conceptColumnName_" + columnId);
if (columnName != null) {
// concept column
String conceptId = request.getParameter("conceptId_" + columnId);
try {
Integer.valueOf(conceptId);
}
catch (NumberFormatException e) {
// for backwards compatibility to pre 1.0.43
Concept c = Context.getConceptService().getConceptByName(conceptId);
if (c == null)
throw new APIException("Concept name : + '" + conceptId
+ "' could not be found in the dictionary");
conceptId = c.getConceptId().toString();
}
String[] extras = request.getParameterValues("conceptExtra_" + columnId);
String modifier = request.getParameter("conceptModifier_" + columnId);
String modifierNumStr = request.getParameter("conceptModifierNum_" + columnId);
Integer modifierNum = null;
if (modifierNumStr.length() > 0)
modifierNum = Integer.valueOf(modifierNumStr);
report.addConceptColumn(columnName, modifier, modifierNum, conceptId, extras);
} else {
columnName = request.getParameter("calculatedName_" + columnId);
if (columnName != null) {
// calculated column
String columnValue = request.getParameter("calculatedValue_" + columnId);
report.addCalculatedColumn(columnName, columnValue);
} else {
columnName = request.getParameter("cohortName_" + columnId);
if (columnName != null) {
// cohort column
String cohortIdValue = request.getParameter("cohortIdValue_" + columnId);
String filterIdValue = request.getParameter("filterIdValue_" + columnId);
String searchIdValue = request.getParameter("patientSearchIdValue_" + columnId);
String valueIfTrue = request.getParameter("cohortIfTrue_" + columnId);
String valueIfFalse = request.getParameter("cohortIfFalse_" + columnId);
Integer cohortId = null;
Integer filterId = null;
Integer searchId = null;
try {
cohortId = Integer.valueOf(cohortIdValue);
}
catch (Exception ex) {}
try {
filterId = Integer.valueOf(filterIdValue);
}
catch (Exception ex) {}
try {
searchId = Integer.valueOf(searchIdValue);
}
catch (Exception ex) {}
if (cohortId != null || filterId != null || searchId != null)
report.addCohortColumn(columnName, cohortId, filterId, searchId, valueIfTrue,
valueIfFalse);
} else
log.warn("Cannot determine column type for column: " + columnId);
}
}
}
}
}
String saveAsNew = ServletRequestUtils.getStringParameter(request, "saveAsNew", "");
if (!saveAsNew.equals(""))
report.setReportObjectId(null);
ReportObjectService rs = (ReportObjectService) Context.getService(ReportObjectService.class);
rs.saveReportObject(report);
// if there are cached results for this report, delete them
File cachedLastReportRun = DataExportUtil.getGeneratedFile(report);
if (cachedLastReportRun != null && cachedLastReportRun.exists()) {
cachedLastReportRun.delete();
}
String action = ServletRequestUtils.getRequiredStringParameter(request, "action");
MessageSourceAccessor msa = getMessageSourceAccessor();
if (action.equals(msa.getMessage("reportingcompatibility.DataExport.save"))) {
view = getSuccessView();
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "reportingcompatibility.DataExport.saved");
} else {
view = request.getContextPath() + "/moduleServlet/reportingcompatibility/dataExportServlet?dataExportId="
+ report.getReportObjectId();
}
}
return new ModelAndView(new RedirectView(view));
}
| protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object obj,
BindException errors) throws Exception {
HttpSession httpSession = request.getSession();
String view = getFormView();
if (Context.isAuthenticated()) {
DataExportReportObject report = (DataExportReportObject) obj;
// create PatientSet from selected values in report
String[] patientIds = request.getParameterValues("patientId");
report.setPatientIds(new Vector<Integer>());
if (patientIds != null)
for (String patientId : patientIds)
if (patientId != null && !patientId.equals(""))
report.addPatientId(Integer.valueOf(patientId));
Integer location = ServletRequestUtils.getIntParameter(request, "location", 0);
if (location > 0)
report.setLocation(Context.getLocationService().getLocation(location));
//String startDate = ServletRequestUtils.getStringParameter(request, "startDate", "");
//String endDate = ServletRequestUtils.getStringParameter(request, "endDate", "");
//if (!startDate.equals(""))
// report.setStartDate(dateFormat.parse(startDate));
//if (!endDate.equals(""))
// report.setEndDate(dateFormat.parse(endDate));
// define columns for report object
String[] columnIds = request.getParameterValues("columnId");
report.setColumns(new Vector<ExportColumn>());
if (columnIds != null) {
for (String columnId : columnIds) {
String columnName = request.getParameter("simpleName_" + columnId);
if (columnName != null)
// simple column
report.addSimpleColumn(columnName, request.getParameter("simpleValue_" + columnId));
else {
columnName = request.getParameter("conceptColumnName_" + columnId);
if (columnName != null) {
// concept column
String conceptId = request.getParameter("conceptId_" + columnId);
try {
Integer.valueOf(conceptId);
}
catch (NumberFormatException e) {
// for backwards compatibility to pre 1.0.43
Concept c = Context.getConceptService().getConceptByName(conceptId);
if (c == null)
throw new APIException("Concept name : '" + conceptId
+ "' could not be found in the dictionary");
conceptId = c.getConceptId().toString();
}
String[] extras = request.getParameterValues("conceptExtra_" + columnId);
String modifier = request.getParameter("conceptModifier_" + columnId);
String modifierNumStr = request.getParameter("conceptModifierNum_" + columnId);
Integer modifierNum = null;
if (modifierNumStr.length() > 0)
modifierNum = Integer.valueOf(modifierNumStr);
report.addConceptColumn(columnName, modifier, modifierNum, conceptId, extras);
} else {
columnName = request.getParameter("calculatedName_" + columnId);
if (columnName != null) {
// calculated column
String columnValue = request.getParameter("calculatedValue_" + columnId);
report.addCalculatedColumn(columnName, columnValue);
} else {
columnName = request.getParameter("cohortName_" + columnId);
if (columnName != null) {
// cohort column
String cohortIdValue = request.getParameter("cohortIdValue_" + columnId);
String filterIdValue = request.getParameter("filterIdValue_" + columnId);
String searchIdValue = request.getParameter("patientSearchIdValue_" + columnId);
String valueIfTrue = request.getParameter("cohortIfTrue_" + columnId);
String valueIfFalse = request.getParameter("cohortIfFalse_" + columnId);
Integer cohortId = null;
Integer filterId = null;
Integer searchId = null;
try {
cohortId = Integer.valueOf(cohortIdValue);
}
catch (Exception ex) {}
try {
filterId = Integer.valueOf(filterIdValue);
}
catch (Exception ex) {}
try {
searchId = Integer.valueOf(searchIdValue);
}
catch (Exception ex) {}
if (cohortId != null || filterId != null || searchId != null)
report.addCohortColumn(columnName, cohortId, filterId, searchId, valueIfTrue,
valueIfFalse);
} else
log.warn("Cannot determine column type for column: " + columnId);
}
}
}
}
}
String saveAsNew = ServletRequestUtils.getStringParameter(request, "saveAsNew", "");
if (!saveAsNew.equals(""))
report.setReportObjectId(null);
ReportObjectService rs = (ReportObjectService) Context.getService(ReportObjectService.class);
rs.saveReportObject(report);
// if there are cached results for this report, delete them
File cachedLastReportRun = DataExportUtil.getGeneratedFile(report);
if (cachedLastReportRun != null && cachedLastReportRun.exists()) {
cachedLastReportRun.delete();
}
String action = ServletRequestUtils.getRequiredStringParameter(request, "action");
MessageSourceAccessor msa = getMessageSourceAccessor();
if (action.equals(msa.getMessage("reportingcompatibility.DataExport.save"))) {
view = getSuccessView();
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "reportingcompatibility.DataExport.saved");
} else {
view = request.getContextPath() + "/moduleServlet/reportingcompatibility/dataExportServlet?dataExportId="
+ report.getReportObjectId();
}
}
return new ModelAndView(new RedirectView(view));
}
|
diff --git a/src/main/java/IonCannon/mapreduce/sampling/SamplingMapper.java b/src/main/java/IonCannon/mapreduce/sampling/SamplingMapper.java
index 6e591cc..9621f3f 100644
--- a/src/main/java/IonCannon/mapreduce/sampling/SamplingMapper.java
+++ b/src/main/java/IonCannon/mapreduce/sampling/SamplingMapper.java
@@ -1,99 +1,99 @@
package IonCannon.mapreduce.sampling;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapreduce.Mapper;
import redis.clients.jedis.Jedis;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import java.util.regex.Pattern;
public class SamplingMapper extends Mapper<LongWritable, Text, LongWritable, Text> {
private static final String SEPARATOR = "[,\t]";
private static Pattern pattern = Pattern.compile(SEPARATOR);
private int strengthToLinkFactor = 10;
private int numberOfLinksPerCategory = 1500;
@Override
public void setup(Context context) {
Configuration conf = context.getConfiguration();
String strength = conf.get("strengthToLinkFactor");
if (strength.length() > 0) {
int tmp = Integer.parseInt(strength);
if (tmp != 0)
strengthToLinkFactor = tmp;
}
String numOfLinks = conf.get("numberOfLinksPerCategory");
if (numOfLinks.length() > 0) {
int tmp = Integer.parseInt(numOfLinks);
if (tmp != 0)
numberOfLinksPerCategory = tmp;
}
}
@Override
public void map(LongWritable line, Text input, Context context) throws IOException, InterruptedException {
System.out.println( input.toString());
String[] parsedConfigs = pattern.split(input.toString());
Float[] config = new Float[parsedConfigs.length - 1];
long userID = Long.parseLong(parsedConfigs[0]);
for (int i = 1; i < parsedConfigs.length; i++) {
config[i - 1] = Float.parseFloat(parsedConfigs[i]);
}
String redisHost = context.getConfiguration().get("redisHost");
Jedis con = new Jedis(redisHost);
for (int i = 0; i < config.length; i++) {
float numberOfLinksForCategory = config[i] * strengthToLinkFactor;
HashSet<Integer> linksInCategory = new HashSet<Integer>();
while (true) {
//got enough links
if (linksInCategory.size() >= numberOfLinksForCategory) {
break;
}
Random random = new Random();
//next random link index in this category
int nextLinkIndex = random.nextInt(numberOfLinksPerCategory) + (i * numberOfLinksPerCategory );
if (linksInCategory.contains(nextLinkIndex)) {
continue;
} else {
linksInCategory.add(nextLinkIndex);
String categoryIndex = new Integer(i).toString();
String linkIndexInCategory = new Integer(nextLinkIndex).toString();
String output = categoryIndex + "," + linkIndexInCategory;
long currentTime = System.currentTimeMillis() / 1000L;
long randomOffset = (long) (Math.random() * ((864000)));
long timestamp = currentTime - randomOffset;
output += "," + timestamp;
con.set("urls." + linkIndexInCategory + ".timestamp", new Long(timestamp).toString());
- con.rpush("user."+line.get()+".links",linkIndexInCategory);
+ con.rpush("user."+ userID +".links",linkIndexInCategory);
context.write(new LongWritable(userID), new Text(output));
}
}
}
con.disconnect();
}
}
| true | true | public void map(LongWritable line, Text input, Context context) throws IOException, InterruptedException {
System.out.println( input.toString());
String[] parsedConfigs = pattern.split(input.toString());
Float[] config = new Float[parsedConfigs.length - 1];
long userID = Long.parseLong(parsedConfigs[0]);
for (int i = 1; i < parsedConfigs.length; i++) {
config[i - 1] = Float.parseFloat(parsedConfigs[i]);
}
String redisHost = context.getConfiguration().get("redisHost");
Jedis con = new Jedis(redisHost);
for (int i = 0; i < config.length; i++) {
float numberOfLinksForCategory = config[i] * strengthToLinkFactor;
HashSet<Integer> linksInCategory = new HashSet<Integer>();
while (true) {
//got enough links
if (linksInCategory.size() >= numberOfLinksForCategory) {
break;
}
Random random = new Random();
//next random link index in this category
int nextLinkIndex = random.nextInt(numberOfLinksPerCategory) + (i * numberOfLinksPerCategory );
if (linksInCategory.contains(nextLinkIndex)) {
continue;
} else {
linksInCategory.add(nextLinkIndex);
String categoryIndex = new Integer(i).toString();
String linkIndexInCategory = new Integer(nextLinkIndex).toString();
String output = categoryIndex + "," + linkIndexInCategory;
long currentTime = System.currentTimeMillis() / 1000L;
long randomOffset = (long) (Math.random() * ((864000)));
long timestamp = currentTime - randomOffset;
output += "," + timestamp;
con.set("urls." + linkIndexInCategory + ".timestamp", new Long(timestamp).toString());
con.rpush("user."+line.get()+".links",linkIndexInCategory);
context.write(new LongWritable(userID), new Text(output));
}
}
}
con.disconnect();
}
| public void map(LongWritable line, Text input, Context context) throws IOException, InterruptedException {
System.out.println( input.toString());
String[] parsedConfigs = pattern.split(input.toString());
Float[] config = new Float[parsedConfigs.length - 1];
long userID = Long.parseLong(parsedConfigs[0]);
for (int i = 1; i < parsedConfigs.length; i++) {
config[i - 1] = Float.parseFloat(parsedConfigs[i]);
}
String redisHost = context.getConfiguration().get("redisHost");
Jedis con = new Jedis(redisHost);
for (int i = 0; i < config.length; i++) {
float numberOfLinksForCategory = config[i] * strengthToLinkFactor;
HashSet<Integer> linksInCategory = new HashSet<Integer>();
while (true) {
//got enough links
if (linksInCategory.size() >= numberOfLinksForCategory) {
break;
}
Random random = new Random();
//next random link index in this category
int nextLinkIndex = random.nextInt(numberOfLinksPerCategory) + (i * numberOfLinksPerCategory );
if (linksInCategory.contains(nextLinkIndex)) {
continue;
} else {
linksInCategory.add(nextLinkIndex);
String categoryIndex = new Integer(i).toString();
String linkIndexInCategory = new Integer(nextLinkIndex).toString();
String output = categoryIndex + "," + linkIndexInCategory;
long currentTime = System.currentTimeMillis() / 1000L;
long randomOffset = (long) (Math.random() * ((864000)));
long timestamp = currentTime - randomOffset;
output += "," + timestamp;
con.set("urls." + linkIndexInCategory + ".timestamp", new Long(timestamp).toString());
con.rpush("user."+ userID +".links",linkIndexInCategory);
context.write(new LongWritable(userID), new Text(output));
}
}
}
con.disconnect();
}
|
diff --git a/src/net/milkbowl/vault/permission/plugins/Permission_PermissionsEx.java b/src/net/milkbowl/vault/permission/plugins/Permission_PermissionsEx.java
index 52226ae..1e74413 100644
--- a/src/net/milkbowl/vault/permission/plugins/Permission_PermissionsEx.java
+++ b/src/net/milkbowl/vault/permission/plugins/Permission_PermissionsEx.java
@@ -1,288 +1,287 @@
/* This file is part of Vault.
Vault 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.
Vault 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 Vault. If not, see <http://www.gnu.org/licenses/>.
*/
package net.milkbowl.vault.permission.plugins;
import net.milkbowl.vault.permission.Permission;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.server.PluginDisableEvent;
import org.bukkit.event.server.PluginEnableEvent;
import org.bukkit.plugin.Plugin;
import ru.tehkode.permissions.PermissionGroup;
import ru.tehkode.permissions.PermissionUser;
import ru.tehkode.permissions.bukkit.PermissionsEx;
public class Permission_PermissionsEx extends Permission {
private final String name = "PermissionsEx";
private PermissionsEx permission = null;
public Permission_PermissionsEx(Plugin plugin) {
this.plugin = plugin;
Bukkit.getServer().getPluginManager().registerEvents(new PermissionServerListener(this), plugin);
// Load Plugin in case it was loaded before
if (permission == null) {
Plugin perms = plugin.getServer().getPluginManager().getPlugin("PermissionsEx");
if (perms != null) {
if (perms.isEnabled()) {
try {
if (Double.valueOf(perms.getDescription().getVersion()) < 1.16) {
log.info(String.format("[%s][Permission] %s below 1.16 is not compatible with Vault! Falling back to SuperPerms only mode. PLEASE UPDATE!", plugin.getDescription().getName(), name));
- return;
}
} catch (NumberFormatException e) {
// Do nothing
}
permission = (PermissionsEx) perms;
log.info(String.format("[%s][Permission] %s hooked.", plugin.getDescription().getName(), name));
}
}
}
}
@Override
public boolean isEnabled() {
if (permission == null) {
return false;
} else {
return permission.isEnabled();
}
}
@Override
public boolean playerInGroup(String worldName, String playerName, String groupName) {
return PermissionsEx.getPermissionManager().getUser(playerName).inGroup(groupName);
}
public class PermissionServerListener implements Listener {
Permission_PermissionsEx permission = null;
public PermissionServerListener(Permission_PermissionsEx permission) {
this.permission = permission;
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPluginEnable(PluginEnableEvent event) {
if (permission.permission == null) {
Plugin perms = plugin.getServer().getPluginManager().getPlugin("PermissionsEx");
if (perms != null) {
if (perms.isEnabled()) {
try {
if (Double.valueOf(perms.getDescription().getVersion()) < 1.16) {
log.info(String.format("[%s][Permission] %s below 1.16 is not compatible with Vault! Falling back to SuperPerms only mode. PLEASE UPDATE!", plugin.getDescription().getName(), name));
return;
}
} catch (NumberFormatException e) {
// Do nothing
}
permission.permission = (PermissionsEx) perms;
log.info(String.format("[%s][Permission] %s hooked.", plugin.getDescription().getName(), permission.name));
}
}
}
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPluginDisable(PluginDisableEvent event) {
if (permission.permission != null) {
if (event.getPlugin().getDescription().getName().equals("PermissionsEx")) {
permission.permission = null;
log.info(String.format("[%s][Permission] %s un-hooked.", plugin.getDescription().getName(), permission.name));
}
}
}
}
@Override
public String getName() {
return name;
}
@Override
public boolean playerAddGroup(String worldName, String playerName, String groupName) {
PermissionGroup group = PermissionsEx.getPermissionManager().getGroup(groupName);
PermissionUser user = PermissionsEx.getPermissionManager().getUser(playerName);
if (group == null || user == null) {
return false;
} else {
user.addGroup(group);
return true;
}
}
@Override
public boolean playerRemoveGroup(String worldName, String playerName, String groupName) {
PermissionsEx.getPermissionManager().getUser(playerName).removeGroup(groupName);
return true;
}
@Override
public boolean playerAdd(String worldName, String playerName, String permission) {
PermissionUser user = PermissionsEx.getPermissionManager().getUser(playerName);
if (user == null) {
return false;
} else {
user.addPermission(permission, worldName);
return true;
}
}
@Override
public boolean playerRemove(String worldName, String playerName, String permission) {
PermissionUser user = PermissionsEx.getPermissionManager().getUser(playerName);
if (user == null) {
return false;
} else {
user.removePermission(permission, worldName);
return true;
}
}
@Override
public boolean groupAdd(String worldName, String groupName, String permission) {
PermissionGroup group = PermissionsEx.getPermissionManager().getGroup(groupName);
if (group == null) {
return false;
} else {
group.addPermission(permission, worldName);
return true;
}
}
@Override
public boolean groupRemove(String worldName, String groupName, String permission) {
PermissionGroup group = PermissionsEx.getPermissionManager().getGroup(groupName);
if (group == null) {
return false;
} else {
group.removePermission(permission, worldName);
return true;
}
}
@Override
public boolean groupHas(String worldName, String groupName, String permission) {
PermissionGroup group = PermissionsEx.getPermissionManager().getGroup(groupName);
if (group == null) {
return false;
} else {
return group.has(permission, worldName);
}
}
@Override
public String[] getPlayerGroups(String world, String playerName) {
return PermissionsEx.getPermissionManager().getUser(playerName).getGroupsNames();
}
@Override
public String getPrimaryGroup(String world, String playerName) {
PermissionUser user = PermissionsEx.getPermissionManager().getUser(playerName);
if (user == null) {
return null;
} else if (user.getGroupsNames(world).length > 0) {
return user.getGroupsNames(world)[0];
} else {
return null;
}
}
@Override
public boolean playerHas(String worldName, String playerName, String permission) {
PermissionUser user = PermissionsEx.getPermissionManager().getUser(playerName);
if (user != null) {
return user.has(permission, worldName);
} else {
return false;
}
}
@Override
public boolean playerAddTransient(String worldName, String player, String permission) {
PermissionUser pPlayer = PermissionsEx.getPermissionManager().getUser(player);
if (pPlayer != null) {
pPlayer.addTimedPermission(permission, worldName, 0);
return true;
} else {
return false;
}
}
@Override
public boolean playerAddTransient(String worldName, Player player, String permission) {
return playerAddTransient(worldName, player.getName(), permission);
}
@Override
public boolean playerAddTransient(String player, String permission) {
return playerAddTransient(null, player, permission);
}
@Override
public boolean playerAddTransient(Player player, String permission) {
return playerAddTransient(null, player.getName(), permission);
}
@Override
public boolean playerRemoveTransient(String worldName, String player, String permission) {
PermissionUser pPlayer = PermissionsEx.getPermissionManager().getUser(player);
if (pPlayer != null) {
pPlayer.removeTimedPermission(permission, worldName);
return true;
} else {
return false;
}
}
@Override
public boolean playerRemoveTransient(Player player, String permission) {
return playerRemoveTransient(null, player.getName(), permission);
}
@Override
public boolean playerRemoveTransient(String worldName, Player player, String permission) {
return playerRemoveTransient(worldName, player.getName(), permission);
}
@Override
public boolean playerRemoveTransient(String player, String permission) {
return playerRemoveTransient(null, player, permission);
}
@Override
public String[] getGroups() {
PermissionGroup[] groups = PermissionsEx.getPermissionManager().getGroups();
if (groups == null || groups.length == 0)
return null;
String[] groupNames = new String[groups.length];
for (int i = 0; i < groups.length; i++) {
groupNames[i] = groups[i].getName();
}
return groupNames;
}
@Override
public boolean hasSuperPermsCompat() {
return true;
}
}
| true | true | public Permission_PermissionsEx(Plugin plugin) {
this.plugin = plugin;
Bukkit.getServer().getPluginManager().registerEvents(new PermissionServerListener(this), plugin);
// Load Plugin in case it was loaded before
if (permission == null) {
Plugin perms = plugin.getServer().getPluginManager().getPlugin("PermissionsEx");
if (perms != null) {
if (perms.isEnabled()) {
try {
if (Double.valueOf(perms.getDescription().getVersion()) < 1.16) {
log.info(String.format("[%s][Permission] %s below 1.16 is not compatible with Vault! Falling back to SuperPerms only mode. PLEASE UPDATE!", plugin.getDescription().getName(), name));
return;
}
} catch (NumberFormatException e) {
// Do nothing
}
permission = (PermissionsEx) perms;
log.info(String.format("[%s][Permission] %s hooked.", plugin.getDescription().getName(), name));
}
}
}
}
| public Permission_PermissionsEx(Plugin plugin) {
this.plugin = plugin;
Bukkit.getServer().getPluginManager().registerEvents(new PermissionServerListener(this), plugin);
// Load Plugin in case it was loaded before
if (permission == null) {
Plugin perms = plugin.getServer().getPluginManager().getPlugin("PermissionsEx");
if (perms != null) {
if (perms.isEnabled()) {
try {
if (Double.valueOf(perms.getDescription().getVersion()) < 1.16) {
log.info(String.format("[%s][Permission] %s below 1.16 is not compatible with Vault! Falling back to SuperPerms only mode. PLEASE UPDATE!", plugin.getDescription().getName(), name));
}
} catch (NumberFormatException e) {
// Do nothing
}
permission = (PermissionsEx) perms;
log.info(String.format("[%s][Permission] %s hooked.", plugin.getDescription().getName(), name));
}
}
}
}
|
diff --git a/GAE/src/org/waterforpeople/mapping/app/web/TaskServlet.java b/GAE/src/org/waterforpeople/mapping/app/web/TaskServlet.java
index 2b0d85578..3ffb76529 100644
--- a/GAE/src/org/waterforpeople/mapping/app/web/TaskServlet.java
+++ b/GAE/src/org/waterforpeople/mapping/app/web/TaskServlet.java
@@ -1,337 +1,341 @@
package org.waterforpeople.mapping.app.web;
import static com.google.appengine.api.labs.taskqueue.TaskOptions.Builder.url;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import javax.servlet.http.HttpServletRequest;
import org.waterforpeople.mapping.app.web.dto.TaskRequest;
import org.waterforpeople.mapping.dao.DeviceFilesDao;
import org.waterforpeople.mapping.dao.SurveyInstanceDAO;
import org.waterforpeople.mapping.domain.ProcessingAction;
import org.waterforpeople.mapping.domain.Status.StatusCode;
import org.waterforpeople.mapping.domain.SurveyInstance;
import org.waterforpeople.mapping.helper.AccessPointHelper;
import org.waterforpeople.mapping.helper.GeoRegionHelper;
import services.S3Driver;
import com.gallatinsystems.common.util.MailUtil;
import com.gallatinsystems.device.domain.DeviceFiles;
import com.gallatinsystems.framework.rest.AbstractRestApiServlet;
import com.gallatinsystems.framework.rest.RestRequest;
import com.gallatinsystems.framework.rest.RestResponse;
import com.gallatinsystems.image.GAEImageAdapter;
import com.google.appengine.api.labs.taskqueue.Queue;
import com.google.appengine.api.labs.taskqueue.QueueFactory;
import com.google.appengine.api.labs.taskqueue.TaskOptions;
public class TaskServlet extends AbstractRestApiServlet {
private static String DEVICE_FILE_PATH;
private static String FROM_ADDRESS;
private static final String REGION_FLAG = "regionFlag=true";
private static final long serialVersionUID = -2607990749512391457L;
private static final Logger log = Logger.getLogger(TaskServlet.class
.getName());
private AccessPointHelper aph;
private SurveyInstanceDAO siDao;
private final static String EMAIL_FROM_ADDRESS_KEY = "emailFromAddress";
private TreeMap<String, String> recepientList = null;
public TaskServlet() {
DEVICE_FILE_PATH = new com.gallatinsystems.common.util.PropertyUtil()
.getProperty("deviceZipPath");
FROM_ADDRESS = new com.gallatinsystems.common.util.PropertyUtil()
.getProperty(EMAIL_FROM_ADDRESS_KEY);
aph = new AccessPointHelper();
siDao = new SurveyInstanceDAO();
recepientList = MailUtil.loadRecipientList();
}
private ArrayList<SurveyInstance> processFile(String fileName,
String phoneNumber, String checksum, Integer offset) {
ArrayList<SurveyInstance> surveyInstances = new ArrayList<SurveyInstance>();
try {
DeviceFilesDao dfDao = new DeviceFilesDao();
URL url = new URL(DEVICE_FILE_PATH + fileName);
BufferedInputStream bis = new BufferedInputStream(url.openStream());
ZipInputStream zis = new ZipInputStream(bis);
List<DeviceFiles> dfList = null;
DeviceFiles deviceFile = null;
dfList = dfDao.listByUri(url.toString());
- deviceFile = dfList.get(0);
+ if (dfList != null)
+ deviceFile = dfList.get(0);
if (deviceFile == null) {
deviceFile = new DeviceFiles();
}
deviceFile.setProcessDate(getNowDateTimeFormatted());
deviceFile.setProcessedStatus(StatusCode.IN_PROGRESS);
deviceFile.setURI(url.toURI().toString());
if (phoneNumber == null || phoneNumber.equals("null"))
deviceFile.setPhoneNumber(null);
else
deviceFile.setPhoneNumber(phoneNumber);
if (checksum == null || checksum.equals("null"))
deviceFile.setChecksum(null);
else
deviceFile.setChecksum(checksum);
deviceFile.setUploadDateTime(new Date());
Date collectionDate = new Date();
ArrayList<String> unparsedLines = null;
try {
unparsedLines = extractDataFromZip(zis);
} catch (IOException iex) {
// Error unzipping the response file
deviceFile.setProcessedStatus(StatusCode.ERROR_INFLATING_ZIP);
String message = "Error inflating device zip: "
+ deviceFile.getURI() + " : " + iex.getMessage();
log.log(Level.SEVERE, message);
deviceFile.addProcessingMessage(message);
MailUtil.sendMail(FROM_ADDRESS, "FLOW", recepientList,
"Device File Processing Error: " + fileName, message);
}
if (unparsedLines != null && unparsedLines.size() > 0) {
if (REGION_FLAG.equals(unparsedLines.get(0))) {
unparsedLines.remove(0);
GeoRegionHelper grh = new GeoRegionHelper();
grh.processRegionsSurvey(unparsedLines);
} else {
int lineNum = offset;
String curId = null;
while (lineNum < unparsedLines.size()) {
String[] parts = unparsedLines.get(lineNum).split(",");
if (parts.length >= 2) {
if (curId == null) {
curId = parts[1];
} else {
// if this isn't the first time through and
// we are seeing a new id, break since we'll
// process that in another call
if (!curId.equals(parts[1])) {
break;
}
}
}
lineNum++;
}
Long userID = 1L;
dfDao.save(deviceFile);
SurveyInstance inst = siDao.save(collectionDate,
deviceFile, userID,
unparsedLines.subList(offset, lineNum));
surveyInstances.add(inst);
- //TODO: HACK because we were saving so many duplicate device files this way they all get the same status
- for (DeviceFiles dfitem : dfList) {
- dfitem.setProcessedStatus(inst.getDeviceFile()
- .getProcessedStatus());
+ // TODO: HACK because we were saving so many duplicate
+ // device files this way they all get the same status
+ if (dfList != null) {
+ for (DeviceFiles dfitem : dfList) {
+ dfitem.setProcessedStatus(inst.getDeviceFile()
+ .getProcessedStatus());
+ }
}
if (lineNum < unparsedLines.size()) {
StatusCode processingStatus = inst.getDeviceFile()
.getProcessedStatus();
if (processingStatus
.equals(StatusCode.PROCESSED_WITH_ERRORS)) {
String message = "Error in file during first processing step. Continuing to next part";
deviceFile.addProcessingMessage(message);
deviceFile
.setProcessedStatus(StatusCode.IN_PROGRESS);
} else {
deviceFile.addProcessingMessage("Processed "
+ lineNum + " lines spawning queue call");
deviceFile
.setProcessedStatus(StatusCode.IN_PROGRESS);
}
// if we haven't processed everything yet, invoke a
// new service
Queue queue = QueueFactory.getDefaultQueue();
queue.add(url("/app_worker/task")
.param("action", "processFile")
.param("fileName", fileName)
.param("offset", lineNum + ""));
}
}
} else {
deviceFile.setProcessedStatus(StatusCode.PROCESSED_WITH_ERRORS);
String message = "Error empty file: " + deviceFile.getURI();
log.log(Level.SEVERE, message);
deviceFile.addProcessingMessage(message);
MailUtil.sendMail(FROM_ADDRESS, "FLOW", recepientList,
"Device File Processing Error: " + fileName, message);
}
dfDao.save(dfList);
zis.close();
} catch (Exception e) {
log.log(Level.SEVERE, "Could not process data file", e);
MailUtil.sendMail(FROM_ADDRESS, "FLOW", recepientList,
"Device File Processing Error: " + fileName, e.getMessage());
}
return surveyInstances;
}
private ArrayList<String> extractDataFromZip(ZipInputStream zis)
throws IOException {
ArrayList<String> lines = new ArrayList<String>();
String line = null;
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
log.info("Unzipping: " + entry.getName());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[2048];
int size;
while ((size = zis.read(buffer, 0, buffer.length)) != -1) {
out.write(buffer, 0, size);
}
line = out.toString();
if (entry.getName().endsWith("txt")) {
if (entry.getName().equals("regions.txt")) {
lines.add("regionFlag=true");
}
String[] linesSplit = line.split("\n");
for (String s : linesSplit) {
if (s.contains("\u0000")) {
s = s.replaceAll("\u0000", "");
}
lines.add(s);
}
} else {
S3Driver s3 = new S3Driver();
String[] imageParts = entry.getName().split("/");
// comment out while testing locally
try {
// GAEImageAdapter gaeIA = new GAEImageAdapter();
// byte[] resizedImage =
// gaeIA.resizeImage(out.toByteArray(), 500, 500);
// s3.uploadFile("dru-test", imageParts[1], resizedImage);
GAEImageAdapter gaeImg = new GAEImageAdapter();
byte[] newImage = gaeImg.resizeImage(out.toByteArray(),
500, 500);
s3.uploadFile("dru-test", imageParts[1], newImage);
// add queue call to resize
Queue queue = QueueFactory.getDefaultQueue();
queue.add(url("imageprocessor").param("imageURL",
imageParts[1]));
log.info("submiting image resize for imageURL: "
+ imageParts[1]);
} catch (Exception ex) {
ex.printStackTrace();
}
out.close();
}
zis.closeEntry();
}
return lines;
}
private String getNowDateTimeFormatted() {
DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_HH:mm:ss");
java.util.Date date = new java.util.Date();
String dateTime = dateFormat.format(date);
return dateTime;
}
private ProcessingAction dispatch(String surveyKey) {
ProcessingAction pa = new ProcessingAction();
pa.setAction("addAccessPoint");
pa.setDispatchURL("/worker/task");
pa.addParam("surveyId", surveyKey);
return pa;
}
@Override
protected RestRequest convertRequest() throws Exception {
HttpServletRequest req = getRequest();
RestRequest restRequest = new TaskRequest();
restRequest.populateFromHttpRequest(req);
return restRequest;
}
@Override
protected RestResponse handleRequest(RestRequest request) throws Exception {
RestResponse response = new RestResponse();
TaskRequest taskReq = (TaskRequest) request;
if (TaskRequest.PROCESS_FILE_ACTION.equalsIgnoreCase(taskReq
.getAction())) {
ingestFile(taskReq);
} else if (TaskRequest.ADD_ACCESS_POINT_ACTION.equalsIgnoreCase(taskReq
.getAction())) {
addAccessPoint(taskReq);
}
return response;
}
@Override
protected void writeOkResponse(RestResponse resp) throws Exception {
// no-op
}
private void addAccessPoint(TaskRequest req) {
Long surveyInstanceId = req.getSurveyId();
log.info("Received Task Queue calls for surveyInstanceId: "
+ surveyInstanceId);
aph.processSurveyInstance(surveyInstanceId.toString());
}
/**
* handles the callback from the device indicating that a new data file is
* available. This method will call processFile to retrieve the file and
* persist the data to the data store it will then add access points for
* each water point in the survey responses.
*
* @param req
*/
@SuppressWarnings("unchecked")
private void ingestFile(TaskRequest req) {
if (req.getFileName() != null) {
log.info(" Task->processFile");
ArrayList<SurveyInstance> surveyInstances = processFile(
req.getFileName(), req.getPhoneNumber(), req.getChecksum(),
req.getOffset());
Queue summQueue = QueueFactory.getQueue("dataSummarization");
for (SurveyInstance instance : surveyInstances) {
ProcessingAction pa = dispatch(instance.getKey().getId() + "");
TaskOptions options = url(pa.getDispatchURL());
Iterator it = pa.getParams().keySet().iterator();
while (it.hasNext()) {
options.param("key", (String) it.next());
}
log.info("Received Task Queue calls for surveyInstanceKey: "
+ instance.getKey().getId() + "");
aph.processSurveyInstance(instance.getKey().getId() + "");
summQueue.add(url("/app_worker/datasummarization").param(
"objectKey", instance.getKey().getId() + "").param(
"type", "SurveyInstance"));
}
}
}
}
| false | true | private ArrayList<SurveyInstance> processFile(String fileName,
String phoneNumber, String checksum, Integer offset) {
ArrayList<SurveyInstance> surveyInstances = new ArrayList<SurveyInstance>();
try {
DeviceFilesDao dfDao = new DeviceFilesDao();
URL url = new URL(DEVICE_FILE_PATH + fileName);
BufferedInputStream bis = new BufferedInputStream(url.openStream());
ZipInputStream zis = new ZipInputStream(bis);
List<DeviceFiles> dfList = null;
DeviceFiles deviceFile = null;
dfList = dfDao.listByUri(url.toString());
deviceFile = dfList.get(0);
if (deviceFile == null) {
deviceFile = new DeviceFiles();
}
deviceFile.setProcessDate(getNowDateTimeFormatted());
deviceFile.setProcessedStatus(StatusCode.IN_PROGRESS);
deviceFile.setURI(url.toURI().toString());
if (phoneNumber == null || phoneNumber.equals("null"))
deviceFile.setPhoneNumber(null);
else
deviceFile.setPhoneNumber(phoneNumber);
if (checksum == null || checksum.equals("null"))
deviceFile.setChecksum(null);
else
deviceFile.setChecksum(checksum);
deviceFile.setUploadDateTime(new Date());
Date collectionDate = new Date();
ArrayList<String> unparsedLines = null;
try {
unparsedLines = extractDataFromZip(zis);
} catch (IOException iex) {
// Error unzipping the response file
deviceFile.setProcessedStatus(StatusCode.ERROR_INFLATING_ZIP);
String message = "Error inflating device zip: "
+ deviceFile.getURI() + " : " + iex.getMessage();
log.log(Level.SEVERE, message);
deviceFile.addProcessingMessage(message);
MailUtil.sendMail(FROM_ADDRESS, "FLOW", recepientList,
"Device File Processing Error: " + fileName, message);
}
if (unparsedLines != null && unparsedLines.size() > 0) {
if (REGION_FLAG.equals(unparsedLines.get(0))) {
unparsedLines.remove(0);
GeoRegionHelper grh = new GeoRegionHelper();
grh.processRegionsSurvey(unparsedLines);
} else {
int lineNum = offset;
String curId = null;
while (lineNum < unparsedLines.size()) {
String[] parts = unparsedLines.get(lineNum).split(",");
if (parts.length >= 2) {
if (curId == null) {
curId = parts[1];
} else {
// if this isn't the first time through and
// we are seeing a new id, break since we'll
// process that in another call
if (!curId.equals(parts[1])) {
break;
}
}
}
lineNum++;
}
Long userID = 1L;
dfDao.save(deviceFile);
SurveyInstance inst = siDao.save(collectionDate,
deviceFile, userID,
unparsedLines.subList(offset, lineNum));
surveyInstances.add(inst);
//TODO: HACK because we were saving so many duplicate device files this way they all get the same status
for (DeviceFiles dfitem : dfList) {
dfitem.setProcessedStatus(inst.getDeviceFile()
.getProcessedStatus());
}
if (lineNum < unparsedLines.size()) {
StatusCode processingStatus = inst.getDeviceFile()
.getProcessedStatus();
if (processingStatus
.equals(StatusCode.PROCESSED_WITH_ERRORS)) {
String message = "Error in file during first processing step. Continuing to next part";
deviceFile.addProcessingMessage(message);
deviceFile
.setProcessedStatus(StatusCode.IN_PROGRESS);
} else {
deviceFile.addProcessingMessage("Processed "
+ lineNum + " lines spawning queue call");
deviceFile
.setProcessedStatus(StatusCode.IN_PROGRESS);
}
// if we haven't processed everything yet, invoke a
// new service
Queue queue = QueueFactory.getDefaultQueue();
queue.add(url("/app_worker/task")
.param("action", "processFile")
.param("fileName", fileName)
.param("offset", lineNum + ""));
}
}
} else {
deviceFile.setProcessedStatus(StatusCode.PROCESSED_WITH_ERRORS);
String message = "Error empty file: " + deviceFile.getURI();
log.log(Level.SEVERE, message);
deviceFile.addProcessingMessage(message);
MailUtil.sendMail(FROM_ADDRESS, "FLOW", recepientList,
"Device File Processing Error: " + fileName, message);
}
dfDao.save(dfList);
zis.close();
} catch (Exception e) {
log.log(Level.SEVERE, "Could not process data file", e);
MailUtil.sendMail(FROM_ADDRESS, "FLOW", recepientList,
"Device File Processing Error: " + fileName, e.getMessage());
}
return surveyInstances;
}
| private ArrayList<SurveyInstance> processFile(String fileName,
String phoneNumber, String checksum, Integer offset) {
ArrayList<SurveyInstance> surveyInstances = new ArrayList<SurveyInstance>();
try {
DeviceFilesDao dfDao = new DeviceFilesDao();
URL url = new URL(DEVICE_FILE_PATH + fileName);
BufferedInputStream bis = new BufferedInputStream(url.openStream());
ZipInputStream zis = new ZipInputStream(bis);
List<DeviceFiles> dfList = null;
DeviceFiles deviceFile = null;
dfList = dfDao.listByUri(url.toString());
if (dfList != null)
deviceFile = dfList.get(0);
if (deviceFile == null) {
deviceFile = new DeviceFiles();
}
deviceFile.setProcessDate(getNowDateTimeFormatted());
deviceFile.setProcessedStatus(StatusCode.IN_PROGRESS);
deviceFile.setURI(url.toURI().toString());
if (phoneNumber == null || phoneNumber.equals("null"))
deviceFile.setPhoneNumber(null);
else
deviceFile.setPhoneNumber(phoneNumber);
if (checksum == null || checksum.equals("null"))
deviceFile.setChecksum(null);
else
deviceFile.setChecksum(checksum);
deviceFile.setUploadDateTime(new Date());
Date collectionDate = new Date();
ArrayList<String> unparsedLines = null;
try {
unparsedLines = extractDataFromZip(zis);
} catch (IOException iex) {
// Error unzipping the response file
deviceFile.setProcessedStatus(StatusCode.ERROR_INFLATING_ZIP);
String message = "Error inflating device zip: "
+ deviceFile.getURI() + " : " + iex.getMessage();
log.log(Level.SEVERE, message);
deviceFile.addProcessingMessage(message);
MailUtil.sendMail(FROM_ADDRESS, "FLOW", recepientList,
"Device File Processing Error: " + fileName, message);
}
if (unparsedLines != null && unparsedLines.size() > 0) {
if (REGION_FLAG.equals(unparsedLines.get(0))) {
unparsedLines.remove(0);
GeoRegionHelper grh = new GeoRegionHelper();
grh.processRegionsSurvey(unparsedLines);
} else {
int lineNum = offset;
String curId = null;
while (lineNum < unparsedLines.size()) {
String[] parts = unparsedLines.get(lineNum).split(",");
if (parts.length >= 2) {
if (curId == null) {
curId = parts[1];
} else {
// if this isn't the first time through and
// we are seeing a new id, break since we'll
// process that in another call
if (!curId.equals(parts[1])) {
break;
}
}
}
lineNum++;
}
Long userID = 1L;
dfDao.save(deviceFile);
SurveyInstance inst = siDao.save(collectionDate,
deviceFile, userID,
unparsedLines.subList(offset, lineNum));
surveyInstances.add(inst);
// TODO: HACK because we were saving so many duplicate
// device files this way they all get the same status
if (dfList != null) {
for (DeviceFiles dfitem : dfList) {
dfitem.setProcessedStatus(inst.getDeviceFile()
.getProcessedStatus());
}
}
if (lineNum < unparsedLines.size()) {
StatusCode processingStatus = inst.getDeviceFile()
.getProcessedStatus();
if (processingStatus
.equals(StatusCode.PROCESSED_WITH_ERRORS)) {
String message = "Error in file during first processing step. Continuing to next part";
deviceFile.addProcessingMessage(message);
deviceFile
.setProcessedStatus(StatusCode.IN_PROGRESS);
} else {
deviceFile.addProcessingMessage("Processed "
+ lineNum + " lines spawning queue call");
deviceFile
.setProcessedStatus(StatusCode.IN_PROGRESS);
}
// if we haven't processed everything yet, invoke a
// new service
Queue queue = QueueFactory.getDefaultQueue();
queue.add(url("/app_worker/task")
.param("action", "processFile")
.param("fileName", fileName)
.param("offset", lineNum + ""));
}
}
} else {
deviceFile.setProcessedStatus(StatusCode.PROCESSED_WITH_ERRORS);
String message = "Error empty file: " + deviceFile.getURI();
log.log(Level.SEVERE, message);
deviceFile.addProcessingMessage(message);
MailUtil.sendMail(FROM_ADDRESS, "FLOW", recepientList,
"Device File Processing Error: " + fileName, message);
}
dfDao.save(dfList);
zis.close();
} catch (Exception e) {
log.log(Level.SEVERE, "Could not process data file", e);
MailUtil.sendMail(FROM_ADDRESS, "FLOW", recepientList,
"Device File Processing Error: " + fileName, e.getMessage());
}
return surveyInstances;
}
|
diff --git a/src/nl/b3p/viewer/config/services/ArcGISService.java b/src/nl/b3p/viewer/config/services/ArcGISService.java
index e79b1033c..4ce6bab7a 100644
--- a/src/nl/b3p/viewer/config/services/ArcGISService.java
+++ b/src/nl/b3p/viewer/config/services/ArcGISService.java
@@ -1,202 +1,205 @@
/*
* Copyright (C) 2011 B3Partners B.V.
*
* 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 nl.b3p.viewer.config.services;
import java.net.URL;
import java.util.*;
import javax.persistence.*;
import nl.b3p.web.WaitPageStatus;
import org.apache.commons.io.IOUtils;
import org.geotools.data.ows.HTTPClient;
import org.geotools.data.ows.SimpleHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.stripesstuff.stripersist.Stripersist;
/**
*
* @author Matthijs Laan
*/
@Entity
@DiscriminatorValue(ArcGISService.PROTOCOL)
public class ArcGISService extends GeoService {
public static final String PROTOCOL = "arcgis";
public static final String PARAM_USERNAME = "username";
public static final String PARAM_PASSWORD = "password";
private static JSONObject issueRequest(String url, HTTPClient client) throws Exception {
return new JSONObject(IOUtils.toString(client.get(new URL(url)).getResponseStream(), "UTF-8"));
}
@Override
public ArcGISService loadFromUrl(String url, Map params, WaitPageStatus status) throws Exception {
try {
status.setCurrentAction("Ophalen informatie...");
if(!url.endsWith("/MapServer")) {
throw new IllegalArgumentException("URL moet eindigen in \"/MapServer\"");
}
if(url.indexOf("/rest/") == -1) {
throw new IllegalArgumentException("URL moet \"/rest/\" bevatten");
}
HTTPClient client = new SimpleHttpClient();
client.setUser((String)params.get(PARAM_USERNAME));
client.setPassword((String)params.get(PARAM_PASSWORD));
JSONObject info = issueRequest(url + "/layers?f=json", client);
ArcGISService s = new ArcGISService();
int i = url.lastIndexOf("/MapServer");
String temp = url.substring(0,i);
i = temp.lastIndexOf("/");
String name = temp.substring(i+1);
s.setUrl(url);
s.setName(name);
status.setProgress(50);
status.setCurrentAction("Inladen layers...");
/* Automatically create featuresource */
ArcGISFeatureSource fs = new ArcGISFeatureSource();
fs.setLinkedService(s);
fs.setUrl(url);
fs.setUsername(client.getUser());
fs.setPassword(client.getPassword());
Layer top = new Layer();
top.setVirtual(true);
top.setTitle("Layers");
top.setService(s);
JSONArray layers = info.getJSONArray("layers");
for(i = 0; i < layers.length(); i++) {
JSONObject layer = layers.getJSONObject(i);
top.getChildren().add(parseArcGISLayer(layer, s, fs, top));
}
s.setTopLayer(top);
if(!Boolean.FALSE.equals(params.get(PARAM_PERSIST_FEATURESOURCE)) && !fs.getFeatureTypes().isEmpty()) {
fs.setName(FeatureSource.findUniqueName(s.getName()));
Stripersist.getEntityManager().persist(fs);
}
return s;
} finally {
status.setProgress(100);
status.setCurrentAction("Service ingeladen");
status.setFinished(true);
}
}
private Layer parseArcGISLayer(JSONObject agsl, GeoService service, ArcGISFeatureSource fs, Layer parent) throws JSONException {
Layer l = new Layer();
l.setParent(parent);
l.setService(service);
l.setFilterable(true);
l.setQueryable(true); // Could check capabilities field for "Query", but don't bother
l.setName(agsl.getString("id"));
l.setTitle(agsl.getString("name"));
l.getDetails().put("arcgis_type", agsl.getString("type"));
- l.getDetails().put("arcgis_currentVersion", agsl.get("currentVersion").toString());
+ l.getDetails().put("arcgis_currentVersion", agsl.optString("currentVersion", null));
l.getDetails().put("arcgis_description", agsl.getString("description"));
l.getDetails().put("arcgis_geometryType", agsl.getString("geometryType"));
l.getDetails().put("arcgis_capabilities", agsl.getString("capabilities"));
try {
l.setMinScale(agsl.getDouble("minScale"));
l.setMaxScale(agsl.getDouble("maxScale"));
} catch(JSONException e) {
}
try {
JSONObject extent = agsl.getJSONObject("extent");
BoundingBox bbox = new BoundingBox();
bbox.setMinx(extent.getDouble("xmin"));
bbox.setMaxx(extent.getDouble("xmax"));
bbox.setMiny(extent.getDouble("ymin"));
bbox.setMaxy(extent.getDouble("ymax"));
bbox.setCrs(new CoordinateReferenceSystem("EPSG:" + extent.getJSONObject("spatialReference").getInt("wkid")));
l.getBoundingBoxes().put(bbox.getCrs(), bbox);
} catch(JSONException e) {
}
+ // XXX implemented in ArcGISDataStore
+ // XXX sometimes geometry field not in field list but layer has geometryType
JSONArray fields = agsl.getJSONArray("fields");
if(fields.length() > 0) {
SimpleFeatureType sft = new SimpleFeatureType();
sft.setFeatureSource(fs);
- sft.setTypeName(l.getTitle());
+ sft.setTypeName(l.getName());
+ sft.setDescription(l.getTitle());
sft.setWriteable(false);
for(int i = 0; i < fields.length(); i++) {
JSONObject field = fields.getJSONObject(i);
AttributeDescriptor att = new AttributeDescriptor();
sft.getAttributes().add(att);
att.setName(field.getString("name"));
att.setAlias(field.getString("alias"));
String et = field.getString("type");
String type = AttributeDescriptor.TYPE_STRING;
if("esriFieldTypeOID".equals(et)) {
type = AttributeDescriptor.TYPE_INTEGER;
} else if("esriFieldTypeGeometry".equals(et)) {
if(sft.getGeometryAttribute() == null) {
sft.setGeometryAttribute(att.getName());
}
String gtype = agsl.getString("geometryType");
if("esriGeometryPoint".equals(gtype)) {
type = AttributeDescriptor.TYPE_GEOMETRY_POINT;
} else if("esriGeometryMultipoint".equals(gtype)) {
type = AttributeDescriptor.TYPE_GEOMETRY_MPOINT;
} else if("esriGeometryLine".equals(gtype) || "esriGeometryPolyline".equals(gtype)) {
type = AttributeDescriptor.TYPE_GEOMETRY_LINESTRING;
} else if("esriGeometryPolygon".equals(gtype)) {
type = AttributeDescriptor.TYPE_GEOMETRY_POLYGON;
} else {
// don't bother
type = AttributeDescriptor.TYPE_GEOMETRY;
}
} else if("esriFieldTypeDouble".equals(et)) {
type = AttributeDescriptor.TYPE_DOUBLE;
} else if("esriFieldTypeInteger".equals(et)
||"esriFieldTypeSmallInteger".equals(et)) {
type = AttributeDescriptor.TYPE_INTEGER;
} else if("esriFieldTypeDate".equals(et)) {
type = AttributeDescriptor.TYPE_DATE;
}
att.setType(type);
}
fs.getFeatureTypes().add(sft);
l.setFeatureType(sft);
}
JSONArray children = agsl.getJSONArray("subLayers");
for(int i = 0; i < children.length(); i++) {
l.getChildren().add(parseArcGISLayer(children.getJSONObject(i), service, fs, l));
}
return l;
}
}
| false | true | private Layer parseArcGISLayer(JSONObject agsl, GeoService service, ArcGISFeatureSource fs, Layer parent) throws JSONException {
Layer l = new Layer();
l.setParent(parent);
l.setService(service);
l.setFilterable(true);
l.setQueryable(true); // Could check capabilities field for "Query", but don't bother
l.setName(agsl.getString("id"));
l.setTitle(agsl.getString("name"));
l.getDetails().put("arcgis_type", agsl.getString("type"));
l.getDetails().put("arcgis_currentVersion", agsl.get("currentVersion").toString());
l.getDetails().put("arcgis_description", agsl.getString("description"));
l.getDetails().put("arcgis_geometryType", agsl.getString("geometryType"));
l.getDetails().put("arcgis_capabilities", agsl.getString("capabilities"));
try {
l.setMinScale(agsl.getDouble("minScale"));
l.setMaxScale(agsl.getDouble("maxScale"));
} catch(JSONException e) {
}
try {
JSONObject extent = agsl.getJSONObject("extent");
BoundingBox bbox = new BoundingBox();
bbox.setMinx(extent.getDouble("xmin"));
bbox.setMaxx(extent.getDouble("xmax"));
bbox.setMiny(extent.getDouble("ymin"));
bbox.setMaxy(extent.getDouble("ymax"));
bbox.setCrs(new CoordinateReferenceSystem("EPSG:" + extent.getJSONObject("spatialReference").getInt("wkid")));
l.getBoundingBoxes().put(bbox.getCrs(), bbox);
} catch(JSONException e) {
}
JSONArray fields = agsl.getJSONArray("fields");
if(fields.length() > 0) {
SimpleFeatureType sft = new SimpleFeatureType();
sft.setFeatureSource(fs);
sft.setTypeName(l.getTitle());
sft.setWriteable(false);
for(int i = 0; i < fields.length(); i++) {
JSONObject field = fields.getJSONObject(i);
AttributeDescriptor att = new AttributeDescriptor();
sft.getAttributes().add(att);
att.setName(field.getString("name"));
att.setAlias(field.getString("alias"));
String et = field.getString("type");
String type = AttributeDescriptor.TYPE_STRING;
if("esriFieldTypeOID".equals(et)) {
type = AttributeDescriptor.TYPE_INTEGER;
} else if("esriFieldTypeGeometry".equals(et)) {
if(sft.getGeometryAttribute() == null) {
sft.setGeometryAttribute(att.getName());
}
String gtype = agsl.getString("geometryType");
if("esriGeometryPoint".equals(gtype)) {
type = AttributeDescriptor.TYPE_GEOMETRY_POINT;
} else if("esriGeometryMultipoint".equals(gtype)) {
type = AttributeDescriptor.TYPE_GEOMETRY_MPOINT;
} else if("esriGeometryLine".equals(gtype) || "esriGeometryPolyline".equals(gtype)) {
type = AttributeDescriptor.TYPE_GEOMETRY_LINESTRING;
} else if("esriGeometryPolygon".equals(gtype)) {
type = AttributeDescriptor.TYPE_GEOMETRY_POLYGON;
} else {
// don't bother
type = AttributeDescriptor.TYPE_GEOMETRY;
}
} else if("esriFieldTypeDouble".equals(et)) {
type = AttributeDescriptor.TYPE_DOUBLE;
} else if("esriFieldTypeInteger".equals(et)
||"esriFieldTypeSmallInteger".equals(et)) {
type = AttributeDescriptor.TYPE_INTEGER;
} else if("esriFieldTypeDate".equals(et)) {
type = AttributeDescriptor.TYPE_DATE;
}
att.setType(type);
}
fs.getFeatureTypes().add(sft);
l.setFeatureType(sft);
}
JSONArray children = agsl.getJSONArray("subLayers");
for(int i = 0; i < children.length(); i++) {
l.getChildren().add(parseArcGISLayer(children.getJSONObject(i), service, fs, l));
}
return l;
}
| private Layer parseArcGISLayer(JSONObject agsl, GeoService service, ArcGISFeatureSource fs, Layer parent) throws JSONException {
Layer l = new Layer();
l.setParent(parent);
l.setService(service);
l.setFilterable(true);
l.setQueryable(true); // Could check capabilities field for "Query", but don't bother
l.setName(agsl.getString("id"));
l.setTitle(agsl.getString("name"));
l.getDetails().put("arcgis_type", agsl.getString("type"));
l.getDetails().put("arcgis_currentVersion", agsl.optString("currentVersion", null));
l.getDetails().put("arcgis_description", agsl.getString("description"));
l.getDetails().put("arcgis_geometryType", agsl.getString("geometryType"));
l.getDetails().put("arcgis_capabilities", agsl.getString("capabilities"));
try {
l.setMinScale(agsl.getDouble("minScale"));
l.setMaxScale(agsl.getDouble("maxScale"));
} catch(JSONException e) {
}
try {
JSONObject extent = agsl.getJSONObject("extent");
BoundingBox bbox = new BoundingBox();
bbox.setMinx(extent.getDouble("xmin"));
bbox.setMaxx(extent.getDouble("xmax"));
bbox.setMiny(extent.getDouble("ymin"));
bbox.setMaxy(extent.getDouble("ymax"));
bbox.setCrs(new CoordinateReferenceSystem("EPSG:" + extent.getJSONObject("spatialReference").getInt("wkid")));
l.getBoundingBoxes().put(bbox.getCrs(), bbox);
} catch(JSONException e) {
}
// XXX implemented in ArcGISDataStore
// XXX sometimes geometry field not in field list but layer has geometryType
JSONArray fields = agsl.getJSONArray("fields");
if(fields.length() > 0) {
SimpleFeatureType sft = new SimpleFeatureType();
sft.setFeatureSource(fs);
sft.setTypeName(l.getName());
sft.setDescription(l.getTitle());
sft.setWriteable(false);
for(int i = 0; i < fields.length(); i++) {
JSONObject field = fields.getJSONObject(i);
AttributeDescriptor att = new AttributeDescriptor();
sft.getAttributes().add(att);
att.setName(field.getString("name"));
att.setAlias(field.getString("alias"));
String et = field.getString("type");
String type = AttributeDescriptor.TYPE_STRING;
if("esriFieldTypeOID".equals(et)) {
type = AttributeDescriptor.TYPE_INTEGER;
} else if("esriFieldTypeGeometry".equals(et)) {
if(sft.getGeometryAttribute() == null) {
sft.setGeometryAttribute(att.getName());
}
String gtype = agsl.getString("geometryType");
if("esriGeometryPoint".equals(gtype)) {
type = AttributeDescriptor.TYPE_GEOMETRY_POINT;
} else if("esriGeometryMultipoint".equals(gtype)) {
type = AttributeDescriptor.TYPE_GEOMETRY_MPOINT;
} else if("esriGeometryLine".equals(gtype) || "esriGeometryPolyline".equals(gtype)) {
type = AttributeDescriptor.TYPE_GEOMETRY_LINESTRING;
} else if("esriGeometryPolygon".equals(gtype)) {
type = AttributeDescriptor.TYPE_GEOMETRY_POLYGON;
} else {
// don't bother
type = AttributeDescriptor.TYPE_GEOMETRY;
}
} else if("esriFieldTypeDouble".equals(et)) {
type = AttributeDescriptor.TYPE_DOUBLE;
} else if("esriFieldTypeInteger".equals(et)
||"esriFieldTypeSmallInteger".equals(et)) {
type = AttributeDescriptor.TYPE_INTEGER;
} else if("esriFieldTypeDate".equals(et)) {
type = AttributeDescriptor.TYPE_DATE;
}
att.setType(type);
}
fs.getFeatureTypes().add(sft);
l.setFeatureType(sft);
}
JSONArray children = agsl.getJSONArray("subLayers");
for(int i = 0; i < children.length(); i++) {
l.getChildren().add(parseArcGISLayer(children.getJSONObject(i), service, fs, l));
}
return l;
}
|
diff --git a/src/com/bukkit/mg/plantspreader/PlantSpreaderPlayerListener.java b/src/com/bukkit/mg/plantspreader/PlantSpreaderPlayerListener.java
index 65a2f78..c2a156c 100644
--- a/src/com/bukkit/mg/plantspreader/PlantSpreaderPlayerListener.java
+++ b/src/com/bukkit/mg/plantspreader/PlantSpreaderPlayerListener.java
@@ -1,140 +1,143 @@
package com.bukkit.mg.plantspreader;
import java.util.HashMap;
import java.util.Random;
import org.bukkit.event.player.PlayerListener;
import org.bukkit.event.player.PlayerMoveEvent;
/**
* Handle events for all Player related events
* @author Master-Guy
*/
public class PlantSpreaderPlayerListener extends PlayerListener {
private final PlantSpreader plugin;
private Integer I, X, Y, Z, T, minY, minZ, maxX, maxY, maxZ, foundBlock, rn, rn2, patchCount, pmxX, pmxY, pmxZ, pmnX, pmnY, pmnZ, possibleSpreads;
public HashMap<String, Integer> speadOptions = new HashMap<String, Integer>();
public PlantSpreaderPlayerListener(PlantSpreader instance) {
plugin = instance;
}
public void onPlayerMove(PlayerMoveEvent event) {
Random generator = new Random();
if(event.getPlayer().getLocation().getBlockX() == Math.round(event.getPlayer().getLocation().getBlockX())
|| event.getPlayer().getLocation().getBlockZ() == Math.round(event.getPlayer().getLocation().getBlockZ())) {
rn = generator.nextInt(300);
if(rn == 50) {
possibleSpreads = 0;
I = 0;
while (I < this.plugin.getServer().getOnlinePlayers().length) {
X = this.plugin.getServer().getOnlinePlayers()[I].getLocation().getBlockX()-25;
Y = this.plugin.getServer().getOnlinePlayers()[I].getLocation().getBlockY()-5;
Z = this.plugin.getServer().getOnlinePlayers()[I].getLocation().getBlockZ()-25;
minY = Y;
minZ = Z;
maxX = this.plugin.getServer().getOnlinePlayers()[I].getLocation().getBlockX()+25;
maxY = this.plugin.getServer().getOnlinePlayers()[I].getLocation().getBlockY()+5;
maxZ = this.plugin.getServer().getOnlinePlayers()[I].getLocation().getBlockZ()+25;
while(X < maxX) {
Y = minY;
while(Y < maxY) {
Z = minZ;
while(Z < maxZ) {
foundBlock = this.plugin.getServer().getWorlds()[0].getBlockTypeIdAt(X, Y, Z);
if(foundBlock == 37 || foundBlock == 38 || foundBlock == 39 || foundBlock == 40 || foundBlock == 86) {
patchCount = 0;
pmnX = X-9;
pmxX = X+9;
while(pmnX < pmxX) {
pmnY = Y-2;
pmxY = Y+2;
while(pmnY < pmxY) {
pmnZ = Z-9;
pmxZ = Z+9;
while(pmnZ < pmxZ) {
if(this.plugin.getServer().getWorlds()[0].getBlockTypeIdAt(pmnX, pmnY, pmnZ) == foundBlock) {
patchCount = patchCount + 1;
}
pmnZ = pmnZ + 1;
}
pmnY = pmnY + 1;
}
pmnX = pmnX + 1;
}
if(patchCount < 10) {
if (
(this.plugin.getServer().getWorlds()[0].getBlockTypeIdAt(X-1, Y, Z) == 0) ||
(this.plugin.getServer().getWorlds()[0].getBlockTypeIdAt(X+1, Y, Z) == 0) ||
(this.plugin.getServer().getWorlds()[0].getBlockTypeIdAt(X, Y, Z-1) == 0) ||
(this.plugin.getServer().getWorlds()[0].getBlockTypeIdAt(X, Y, Z+1) == 0)
) {
if(this.plugin.getServer().getWorlds()[0].getBlockTypeIdAt(X-1, Y, Z) == 0) {
if(this.plugin.getServer().getWorlds()[0].getBlockTypeIdAt(X-1, Y-1, Z) == this.plugin.getServer().getWorlds()[0].getBlockTypeIdAt(X, Y-1, Z)) {
possibleSpreads = possibleSpreads + 1;
speadOptions.put(possibleSpreads+"X", X-1);
speadOptions.put(possibleSpreads+"Y", Y);
speadOptions.put(possibleSpreads+"Z", Z);
speadOptions.put(possibleSpreads+"T", foundBlock);
} else {
}
}
if(this.plugin.getServer().getWorlds()[0].getBlockTypeIdAt(X+1, Y, Z) == 0) {
if(this.plugin.getServer().getWorlds()[0].getBlockTypeIdAt(X+1, Y-1, Z) == this.plugin.getServer().getWorlds()[0].getBlockTypeIdAt(X, Y-1, Z)) {
possibleSpreads = possibleSpreads + 1;
speadOptions.put(possibleSpreads+"X", X+1);
speadOptions.put(possibleSpreads+"Y", Y);
speadOptions.put(possibleSpreads+"Z", Z);
speadOptions.put(possibleSpreads+"T", foundBlock);
}
}
if(this.plugin.getServer().getWorlds()[0].getBlockTypeIdAt(X, Y, Z-1) == 0) {
if(this.plugin.getServer().getWorlds()[0].getBlockTypeIdAt(X, Y-1, Z-1) == this.plugin.getServer().getWorlds()[0].getBlockTypeIdAt(X, Y-1, Z)) {
possibleSpreads = possibleSpreads + 1;
speadOptions.put(possibleSpreads+"X", X);
speadOptions.put(possibleSpreads+"Y", Y);
speadOptions.put(possibleSpreads+"Z", Z-1);
speadOptions.put(possibleSpreads+"T", foundBlock);
}
}
if(this.plugin.getServer().getWorlds()[0].getBlockTypeIdAt(X, Y, Z+1) == 0) {
if(this.plugin.getServer().getWorlds()[0].getBlockTypeIdAt(X, Y-1, Z+1) == this.plugin.getServer().getWorlds()[0].getBlockTypeIdAt(X, Y-1, Z)) {
possibleSpreads = possibleSpreads + 1;
speadOptions.put(possibleSpreads+"X", X);
speadOptions.put(possibleSpreads+"Y", Y);
speadOptions.put(possibleSpreads+"Z", Z+1);
speadOptions.put(possibleSpreads+"T", foundBlock);
}
}
}
}
}
Z = Z + 1;
}
Y = Y + 1;
}
X = X + 1;
}
I = I + 1;
}
if(possibleSpreads > 0) {
rn2 = generator.nextInt(possibleSpreads);
X = speadOptions.get(rn2+"X");
Y = speadOptions.get(rn2+"Y");
Z = speadOptions.get(rn2+"Z");
T = speadOptions.get(rn2+"T");
try{
this.plugin.getServer().getWorlds()[0].getBlockAt(X, Y, Z).setTypeId(T);
- } finally {
+ } catch (Exception e) {
+ log("Fail at "+X+"/"+Y+"/"+T+"("+T+")!");
+ return;
+ } finally {
+ speadOptions.clear();
}
- speadOptions.clear();
}
}
}
}
public void log(String logText) {
System.out.println(logText);
}
}
| false | true | public void onPlayerMove(PlayerMoveEvent event) {
Random generator = new Random();
if(event.getPlayer().getLocation().getBlockX() == Math.round(event.getPlayer().getLocation().getBlockX())
|| event.getPlayer().getLocation().getBlockZ() == Math.round(event.getPlayer().getLocation().getBlockZ())) {
rn = generator.nextInt(300);
if(rn == 50) {
possibleSpreads = 0;
I = 0;
while (I < this.plugin.getServer().getOnlinePlayers().length) {
X = this.plugin.getServer().getOnlinePlayers()[I].getLocation().getBlockX()-25;
Y = this.plugin.getServer().getOnlinePlayers()[I].getLocation().getBlockY()-5;
Z = this.plugin.getServer().getOnlinePlayers()[I].getLocation().getBlockZ()-25;
minY = Y;
minZ = Z;
maxX = this.plugin.getServer().getOnlinePlayers()[I].getLocation().getBlockX()+25;
maxY = this.plugin.getServer().getOnlinePlayers()[I].getLocation().getBlockY()+5;
maxZ = this.plugin.getServer().getOnlinePlayers()[I].getLocation().getBlockZ()+25;
while(X < maxX) {
Y = minY;
while(Y < maxY) {
Z = minZ;
while(Z < maxZ) {
foundBlock = this.plugin.getServer().getWorlds()[0].getBlockTypeIdAt(X, Y, Z);
if(foundBlock == 37 || foundBlock == 38 || foundBlock == 39 || foundBlock == 40 || foundBlock == 86) {
patchCount = 0;
pmnX = X-9;
pmxX = X+9;
while(pmnX < pmxX) {
pmnY = Y-2;
pmxY = Y+2;
while(pmnY < pmxY) {
pmnZ = Z-9;
pmxZ = Z+9;
while(pmnZ < pmxZ) {
if(this.plugin.getServer().getWorlds()[0].getBlockTypeIdAt(pmnX, pmnY, pmnZ) == foundBlock) {
patchCount = patchCount + 1;
}
pmnZ = pmnZ + 1;
}
pmnY = pmnY + 1;
}
pmnX = pmnX + 1;
}
if(patchCount < 10) {
if (
(this.plugin.getServer().getWorlds()[0].getBlockTypeIdAt(X-1, Y, Z) == 0) ||
(this.plugin.getServer().getWorlds()[0].getBlockTypeIdAt(X+1, Y, Z) == 0) ||
(this.plugin.getServer().getWorlds()[0].getBlockTypeIdAt(X, Y, Z-1) == 0) ||
(this.plugin.getServer().getWorlds()[0].getBlockTypeIdAt(X, Y, Z+1) == 0)
) {
if(this.plugin.getServer().getWorlds()[0].getBlockTypeIdAt(X-1, Y, Z) == 0) {
if(this.plugin.getServer().getWorlds()[0].getBlockTypeIdAt(X-1, Y-1, Z) == this.plugin.getServer().getWorlds()[0].getBlockTypeIdAt(X, Y-1, Z)) {
possibleSpreads = possibleSpreads + 1;
speadOptions.put(possibleSpreads+"X", X-1);
speadOptions.put(possibleSpreads+"Y", Y);
speadOptions.put(possibleSpreads+"Z", Z);
speadOptions.put(possibleSpreads+"T", foundBlock);
} else {
}
}
if(this.plugin.getServer().getWorlds()[0].getBlockTypeIdAt(X+1, Y, Z) == 0) {
if(this.plugin.getServer().getWorlds()[0].getBlockTypeIdAt(X+1, Y-1, Z) == this.plugin.getServer().getWorlds()[0].getBlockTypeIdAt(X, Y-1, Z)) {
possibleSpreads = possibleSpreads + 1;
speadOptions.put(possibleSpreads+"X", X+1);
speadOptions.put(possibleSpreads+"Y", Y);
speadOptions.put(possibleSpreads+"Z", Z);
speadOptions.put(possibleSpreads+"T", foundBlock);
}
}
if(this.plugin.getServer().getWorlds()[0].getBlockTypeIdAt(X, Y, Z-1) == 0) {
if(this.plugin.getServer().getWorlds()[0].getBlockTypeIdAt(X, Y-1, Z-1) == this.plugin.getServer().getWorlds()[0].getBlockTypeIdAt(X, Y-1, Z)) {
possibleSpreads = possibleSpreads + 1;
speadOptions.put(possibleSpreads+"X", X);
speadOptions.put(possibleSpreads+"Y", Y);
speadOptions.put(possibleSpreads+"Z", Z-1);
speadOptions.put(possibleSpreads+"T", foundBlock);
}
}
if(this.plugin.getServer().getWorlds()[0].getBlockTypeIdAt(X, Y, Z+1) == 0) {
if(this.plugin.getServer().getWorlds()[0].getBlockTypeIdAt(X, Y-1, Z+1) == this.plugin.getServer().getWorlds()[0].getBlockTypeIdAt(X, Y-1, Z)) {
possibleSpreads = possibleSpreads + 1;
speadOptions.put(possibleSpreads+"X", X);
speadOptions.put(possibleSpreads+"Y", Y);
speadOptions.put(possibleSpreads+"Z", Z+1);
speadOptions.put(possibleSpreads+"T", foundBlock);
}
}
}
}
}
Z = Z + 1;
}
Y = Y + 1;
}
X = X + 1;
}
I = I + 1;
}
if(possibleSpreads > 0) {
rn2 = generator.nextInt(possibleSpreads);
X = speadOptions.get(rn2+"X");
Y = speadOptions.get(rn2+"Y");
Z = speadOptions.get(rn2+"Z");
T = speadOptions.get(rn2+"T");
try{
this.plugin.getServer().getWorlds()[0].getBlockAt(X, Y, Z).setTypeId(T);
} finally {
}
speadOptions.clear();
}
}
}
}
| public void onPlayerMove(PlayerMoveEvent event) {
Random generator = new Random();
if(event.getPlayer().getLocation().getBlockX() == Math.round(event.getPlayer().getLocation().getBlockX())
|| event.getPlayer().getLocation().getBlockZ() == Math.round(event.getPlayer().getLocation().getBlockZ())) {
rn = generator.nextInt(300);
if(rn == 50) {
possibleSpreads = 0;
I = 0;
while (I < this.plugin.getServer().getOnlinePlayers().length) {
X = this.plugin.getServer().getOnlinePlayers()[I].getLocation().getBlockX()-25;
Y = this.plugin.getServer().getOnlinePlayers()[I].getLocation().getBlockY()-5;
Z = this.plugin.getServer().getOnlinePlayers()[I].getLocation().getBlockZ()-25;
minY = Y;
minZ = Z;
maxX = this.plugin.getServer().getOnlinePlayers()[I].getLocation().getBlockX()+25;
maxY = this.plugin.getServer().getOnlinePlayers()[I].getLocation().getBlockY()+5;
maxZ = this.plugin.getServer().getOnlinePlayers()[I].getLocation().getBlockZ()+25;
while(X < maxX) {
Y = minY;
while(Y < maxY) {
Z = minZ;
while(Z < maxZ) {
foundBlock = this.plugin.getServer().getWorlds()[0].getBlockTypeIdAt(X, Y, Z);
if(foundBlock == 37 || foundBlock == 38 || foundBlock == 39 || foundBlock == 40 || foundBlock == 86) {
patchCount = 0;
pmnX = X-9;
pmxX = X+9;
while(pmnX < pmxX) {
pmnY = Y-2;
pmxY = Y+2;
while(pmnY < pmxY) {
pmnZ = Z-9;
pmxZ = Z+9;
while(pmnZ < pmxZ) {
if(this.plugin.getServer().getWorlds()[0].getBlockTypeIdAt(pmnX, pmnY, pmnZ) == foundBlock) {
patchCount = patchCount + 1;
}
pmnZ = pmnZ + 1;
}
pmnY = pmnY + 1;
}
pmnX = pmnX + 1;
}
if(patchCount < 10) {
if (
(this.plugin.getServer().getWorlds()[0].getBlockTypeIdAt(X-1, Y, Z) == 0) ||
(this.plugin.getServer().getWorlds()[0].getBlockTypeIdAt(X+1, Y, Z) == 0) ||
(this.plugin.getServer().getWorlds()[0].getBlockTypeIdAt(X, Y, Z-1) == 0) ||
(this.plugin.getServer().getWorlds()[0].getBlockTypeIdAt(X, Y, Z+1) == 0)
) {
if(this.plugin.getServer().getWorlds()[0].getBlockTypeIdAt(X-1, Y, Z) == 0) {
if(this.plugin.getServer().getWorlds()[0].getBlockTypeIdAt(X-1, Y-1, Z) == this.plugin.getServer().getWorlds()[0].getBlockTypeIdAt(X, Y-1, Z)) {
possibleSpreads = possibleSpreads + 1;
speadOptions.put(possibleSpreads+"X", X-1);
speadOptions.put(possibleSpreads+"Y", Y);
speadOptions.put(possibleSpreads+"Z", Z);
speadOptions.put(possibleSpreads+"T", foundBlock);
} else {
}
}
if(this.plugin.getServer().getWorlds()[0].getBlockTypeIdAt(X+1, Y, Z) == 0) {
if(this.plugin.getServer().getWorlds()[0].getBlockTypeIdAt(X+1, Y-1, Z) == this.plugin.getServer().getWorlds()[0].getBlockTypeIdAt(X, Y-1, Z)) {
possibleSpreads = possibleSpreads + 1;
speadOptions.put(possibleSpreads+"X", X+1);
speadOptions.put(possibleSpreads+"Y", Y);
speadOptions.put(possibleSpreads+"Z", Z);
speadOptions.put(possibleSpreads+"T", foundBlock);
}
}
if(this.plugin.getServer().getWorlds()[0].getBlockTypeIdAt(X, Y, Z-1) == 0) {
if(this.plugin.getServer().getWorlds()[0].getBlockTypeIdAt(X, Y-1, Z-1) == this.plugin.getServer().getWorlds()[0].getBlockTypeIdAt(X, Y-1, Z)) {
possibleSpreads = possibleSpreads + 1;
speadOptions.put(possibleSpreads+"X", X);
speadOptions.put(possibleSpreads+"Y", Y);
speadOptions.put(possibleSpreads+"Z", Z-1);
speadOptions.put(possibleSpreads+"T", foundBlock);
}
}
if(this.plugin.getServer().getWorlds()[0].getBlockTypeIdAt(X, Y, Z+1) == 0) {
if(this.plugin.getServer().getWorlds()[0].getBlockTypeIdAt(X, Y-1, Z+1) == this.plugin.getServer().getWorlds()[0].getBlockTypeIdAt(X, Y-1, Z)) {
possibleSpreads = possibleSpreads + 1;
speadOptions.put(possibleSpreads+"X", X);
speadOptions.put(possibleSpreads+"Y", Y);
speadOptions.put(possibleSpreads+"Z", Z+1);
speadOptions.put(possibleSpreads+"T", foundBlock);
}
}
}
}
}
Z = Z + 1;
}
Y = Y + 1;
}
X = X + 1;
}
I = I + 1;
}
if(possibleSpreads > 0) {
rn2 = generator.nextInt(possibleSpreads);
X = speadOptions.get(rn2+"X");
Y = speadOptions.get(rn2+"Y");
Z = speadOptions.get(rn2+"Z");
T = speadOptions.get(rn2+"T");
try{
this.plugin.getServer().getWorlds()[0].getBlockAt(X, Y, Z).setTypeId(T);
} catch (Exception e) {
log("Fail at "+X+"/"+Y+"/"+T+"("+T+")!");
return;
} finally {
speadOptions.clear();
}
}
}
}
}
|
diff --git a/sphinx4/edu/cmu/sphinx/research/parallel/ParallelAcousticScorer.java b/sphinx4/edu/cmu/sphinx/research/parallel/ParallelAcousticScorer.java
index 217c5b0b3..91223708d 100644
--- a/sphinx4/edu/cmu/sphinx/research/parallel/ParallelAcousticScorer.java
+++ b/sphinx4/edu/cmu/sphinx/research/parallel/ParallelAcousticScorer.java
@@ -1,173 +1,173 @@
/*
* Copyright 1999-2002 Carnegie Mellon University.
* Portions Copyright 2002 Sun Microsystems, Inc.
* Portions Copyright 2002 Mitsubishi Electronic Research Laboratories.
* All Rights Reserved. Use is subject to license terms.
*
* See the file "license.terms" for information on usage and
* redistribution of this file, and for a DISCLAIMER OF ALL
* WARRANTIES.
*
*/
package edu.cmu.sphinx.research.parallel;
import edu.cmu.sphinx.frontend.Data;
import edu.cmu.sphinx.frontend.DataEndSignal;
import edu.cmu.sphinx.frontend.DataStartSignal;
import edu.cmu.sphinx.frontend.DataProcessingException;
import edu.cmu.sphinx.frontend.FrontEnd;
import edu.cmu.sphinx.frontend.Signal;
import edu.cmu.sphinx.decoder.scorer.AcousticScorer;
import edu.cmu.sphinx.decoder.scorer.Scoreable;
import edu.cmu.sphinx.decoder.search.Token;
import edu.cmu.sphinx.util.props.Configurable;
import edu.cmu.sphinx.util.props.PropertyException;
import edu.cmu.sphinx.util.props.PropertySheet;
import edu.cmu.sphinx.util.props.PropertyType;
import edu.cmu.sphinx.util.props.Registry;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.io.IOException;
/**
* A parallel acoustic scorer that is capable of scoring multiple
* feature streams.
*/
public class ParallelAcousticScorer implements AcousticScorer {
private String name;
/* (non-Javadoc)
* @see edu.cmu.sphinx.util.props.Configurable#register(java.lang.String, edu.cmu.sphinx.util.props.Registry)
*/
public void register(String name, Registry registry)
throws PropertyException {
this.name = name;
}
/* (non-Javadoc)
* @see edu.cmu.sphinx.util.props.Configurable#newProperties(edu.cmu.sphinx.util.props.PropertySheet)
*/
public void newProperties(PropertySheet ps) throws PropertyException {
}
/**
* Scores the given set of Tokens. All Tokens in the given
* list are assumed to belong to the same acoustic model.
*
* @param scoreableList a list containing StateToken objects to
* be scored
*
* @return the best scoring scorable, or null if there are
* no more frames to score
*/
public Scoreable calculateScores(List scoreableList) {
assert scoreableList.size() > 0;
try {
FrontEnd frontEnd = getFrontEnd(scoreableList);
Data data = frontEnd.getData();
if (data == null) {
return null;
}
if (data instanceof DataStartSignal) {
data = frontEnd.getData();
if (data == null) {
return null;
}
}
if (data instanceof DataEndSignal) {
return null;
}
if (data instanceof Signal) {
throw new Error("trying to score non-content feature");
}
float logMaxScore = -Float.MAX_VALUE;
Scoreable bestScoreable = null;
for (Iterator i = scoreableList.iterator(); i.hasNext(); ) {
Scoreable scoreable = (Scoreable) i.next();
- float logScore = scoreable.calculateScore(data, false);
+ float logScore = scoreable.calculateScore(data, false, 1.0f);
if (logScore > logMaxScore) {
logMaxScore = logScore;
bestScoreable = scoreable;
}
}
return bestScoreable;
} catch (DataProcessingException dpe) {
dpe.printStackTrace();
return null;
}
}
/**
* Returns the acoustic model name of the Tokens in the given
* list .
*
* @return the acoustic model name of the Tokens
*/
private FrontEnd getFrontEnd(List activeList) {
if (activeList.size() > 0) {
Iterator i = activeList.iterator();
if (i.hasNext()) {
ParallelToken token = (ParallelToken) i.next();
return token.getFeatureStream().getFrontEnd();
}
}
return null;
}
/*
* (non-Javadoc)
*
* @see edu.cmu.sphinx.util.props.Configurable#getName()
*/
public String getName() {
return name;
}
/**
* Allocates resources for this scorer
*
*/
public void allocate() throws IOException {}
/**
* Deallocates resouces for this scorer
*
*/
public void deallocate() {}
/**
* starts the scorer
*/
public void startRecognition() {}
/**
* stops the scorer
*/
public void stopRecognition() {}
}
| true | true | public Scoreable calculateScores(List scoreableList) {
assert scoreableList.size() > 0;
try {
FrontEnd frontEnd = getFrontEnd(scoreableList);
Data data = frontEnd.getData();
if (data == null) {
return null;
}
if (data instanceof DataStartSignal) {
data = frontEnd.getData();
if (data == null) {
return null;
}
}
if (data instanceof DataEndSignal) {
return null;
}
if (data instanceof Signal) {
throw new Error("trying to score non-content feature");
}
float logMaxScore = -Float.MAX_VALUE;
Scoreable bestScoreable = null;
for (Iterator i = scoreableList.iterator(); i.hasNext(); ) {
Scoreable scoreable = (Scoreable) i.next();
float logScore = scoreable.calculateScore(data, false);
if (logScore > logMaxScore) {
logMaxScore = logScore;
bestScoreable = scoreable;
}
}
return bestScoreable;
} catch (DataProcessingException dpe) {
dpe.printStackTrace();
return null;
}
}
| public Scoreable calculateScores(List scoreableList) {
assert scoreableList.size() > 0;
try {
FrontEnd frontEnd = getFrontEnd(scoreableList);
Data data = frontEnd.getData();
if (data == null) {
return null;
}
if (data instanceof DataStartSignal) {
data = frontEnd.getData();
if (data == null) {
return null;
}
}
if (data instanceof DataEndSignal) {
return null;
}
if (data instanceof Signal) {
throw new Error("trying to score non-content feature");
}
float logMaxScore = -Float.MAX_VALUE;
Scoreable bestScoreable = null;
for (Iterator i = scoreableList.iterator(); i.hasNext(); ) {
Scoreable scoreable = (Scoreable) i.next();
float logScore = scoreable.calculateScore(data, false, 1.0f);
if (logScore > logMaxScore) {
logMaxScore = logScore;
bestScoreable = scoreable;
}
}
return bestScoreable;
} catch (DataProcessingException dpe) {
dpe.printStackTrace();
return null;
}
}
|
diff --git a/src/org/splitbrain/simpleical/SimpleIcalParser.java b/src/org/splitbrain/simpleical/SimpleIcalParser.java
index 7a3e4ee..86c9af4 100644
--- a/src/org/splitbrain/simpleical/SimpleIcalParser.java
+++ b/src/org/splitbrain/simpleical/SimpleIcalParser.java
@@ -1,135 +1,135 @@
package org.splitbrain.simpleical;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
/**
* A simple, optimistic approach to parsing iCal data
*
* This parser doesn't handle most of the specialities of RFC2445 but is able
* to find at least simpler values . If you need completeness use ical4j, if
* you need something simple with a very low footprint this might be the right
* thing for you.
*
* @author Andreas Gohr <[email protected]>
*/
public class SimpleIcalParser {
private String line = null;
private String nextline = null;
private BufferedReader reader = null;
/**
* Initializes the parser on the given input stream
*
* @param is Stream to the iCal formatted data to parse
*/
public SimpleIcalParser(InputStream is){
reader = new BufferedReader(new InputStreamReader(is));
}
/**
* Read the next VEvent from the stream
*
* @return The Event or null if no more events can be found.
* @throws IOException when reading from the stream fails
*/
public SimpleIcalEvent nextEvent() throws IOException {
SimpleIcalEvent event = null;
String lineup = null;
if(line == null) line = reader.readLine();
while (line != null){
nextline = reader.readLine();
lineup = line.toUpperCase();
// look into the future for unfolding
- if(nextline != null && nextline.matches("^\\s+")){
- line = line + nextline.replaceAll("^\\s+", "");
+ if((nextline != null) && nextline.matches("^\\s.*")){
+ line = line + nextline.replaceAll("^\\s", "");
continue;
}
if (lineup.startsWith("BEGIN:VEVENT")) {
event = new SimpleIcalEvent();
}else if(event == null){
// we're not in a event yet. do nothing
}else if (lineup.startsWith("END:VEVENT")) {
// we're done
line = nextline;
return event;
}else{
String frst = ""; // remembers first encountered parameter as possible value for convenience
String key = "";
String val = "";
String[] params = null;
String[] opts = null;
String[] alt = null;
int col = line.indexOf(":");
if(col != -1){
// split into key/value pair
key = line.substring(0, col);
val = line.substring(col+1);
// key might contain parameters
params = key.split("(?<!\\\\);");
key = params[0]; // first part is the real key name
for(int i=1; i<params.length; i++){
opts = params[i].split("(?<!\\\\)=",2);
// add all parameters as extra
if(opts.length == 2){
event.set(key,unslash(opts[0]),unslash(opts[1]));
if(opts[0].equals("CN")){
val = opts[1]+';'+val; // always use CN as value if not yet set
}else if(frst.length() == 0){
frst = opts[0]; // copy 1st one to value if not yet set
}
}else{
event.set(key,unslash(opts[0]),""); // add as empty parameter
if(frst.length() == 0) frst = opts[0]; // copy 1st one to value if not yet set
}
}
// value might contain parameters
params = val.split("(?<!\\\\)[;]");
val = "";
for (String param : params) {
opts = param.split("(?<!\\\\)[=]",2);
if(opts.length == 2){
// add parameter as extra
event.set(key,unslash(opts[0]),unslash(opts[1]));
}else{
// seems not to be a parameter, set as value if not yet set
if(val.length() == 0){
val = opts[0];
}else{
// we have a value already, maybe it's an inline parameter like MAILTO:
alt = opts[0].split("(?<!\\\\)[=]",2);
if(alt.length == 2){
event.set(key,unslash(alt[0]),unslash(alt[1]));
}else{
event.set(key,unslash(opts[0]),""); // add as empty parameter
}
}
}
}
// set value to event
if(val.length() == 0) val = frst;
event.set(key, unslash(val));
}
}
line = nextline;
}
return null; //Shouldn't be reached except for EOF
}
private String unslash(String str){
str = str.replaceAll("\\\\n", "\n");
str = str.replaceAll("\\\\(.)", "$1");
return str.trim();
}
}
| true | true | public SimpleIcalEvent nextEvent() throws IOException {
SimpleIcalEvent event = null;
String lineup = null;
if(line == null) line = reader.readLine();
while (line != null){
nextline = reader.readLine();
lineup = line.toUpperCase();
// look into the future for unfolding
if(nextline != null && nextline.matches("^\\s+")){
line = line + nextline.replaceAll("^\\s+", "");
continue;
}
if (lineup.startsWith("BEGIN:VEVENT")) {
event = new SimpleIcalEvent();
}else if(event == null){
// we're not in a event yet. do nothing
}else if (lineup.startsWith("END:VEVENT")) {
// we're done
line = nextline;
return event;
}else{
String frst = ""; // remembers first encountered parameter as possible value for convenience
String key = "";
String val = "";
String[] params = null;
String[] opts = null;
String[] alt = null;
int col = line.indexOf(":");
if(col != -1){
// split into key/value pair
key = line.substring(0, col);
val = line.substring(col+1);
// key might contain parameters
params = key.split("(?<!\\\\);");
key = params[0]; // first part is the real key name
for(int i=1; i<params.length; i++){
opts = params[i].split("(?<!\\\\)=",2);
// add all parameters as extra
if(opts.length == 2){
event.set(key,unslash(opts[0]),unslash(opts[1]));
if(opts[0].equals("CN")){
val = opts[1]+';'+val; // always use CN as value if not yet set
}else if(frst.length() == 0){
frst = opts[0]; // copy 1st one to value if not yet set
}
}else{
event.set(key,unslash(opts[0]),""); // add as empty parameter
if(frst.length() == 0) frst = opts[0]; // copy 1st one to value if not yet set
}
}
// value might contain parameters
params = val.split("(?<!\\\\)[;]");
val = "";
for (String param : params) {
opts = param.split("(?<!\\\\)[=]",2);
if(opts.length == 2){
// add parameter as extra
event.set(key,unslash(opts[0]),unslash(opts[1]));
}else{
// seems not to be a parameter, set as value if not yet set
if(val.length() == 0){
val = opts[0];
}else{
// we have a value already, maybe it's an inline parameter like MAILTO:
alt = opts[0].split("(?<!\\\\)[=]",2);
if(alt.length == 2){
event.set(key,unslash(alt[0]),unslash(alt[1]));
}else{
event.set(key,unslash(opts[0]),""); // add as empty parameter
}
}
}
}
// set value to event
if(val.length() == 0) val = frst;
event.set(key, unslash(val));
}
}
line = nextline;
}
return null; //Shouldn't be reached except for EOF
}
| public SimpleIcalEvent nextEvent() throws IOException {
SimpleIcalEvent event = null;
String lineup = null;
if(line == null) line = reader.readLine();
while (line != null){
nextline = reader.readLine();
lineup = line.toUpperCase();
// look into the future for unfolding
if((nextline != null) && nextline.matches("^\\s.*")){
line = line + nextline.replaceAll("^\\s", "");
continue;
}
if (lineup.startsWith("BEGIN:VEVENT")) {
event = new SimpleIcalEvent();
}else if(event == null){
// we're not in a event yet. do nothing
}else if (lineup.startsWith("END:VEVENT")) {
// we're done
line = nextline;
return event;
}else{
String frst = ""; // remembers first encountered parameter as possible value for convenience
String key = "";
String val = "";
String[] params = null;
String[] opts = null;
String[] alt = null;
int col = line.indexOf(":");
if(col != -1){
// split into key/value pair
key = line.substring(0, col);
val = line.substring(col+1);
// key might contain parameters
params = key.split("(?<!\\\\);");
key = params[0]; // first part is the real key name
for(int i=1; i<params.length; i++){
opts = params[i].split("(?<!\\\\)=",2);
// add all parameters as extra
if(opts.length == 2){
event.set(key,unslash(opts[0]),unslash(opts[1]));
if(opts[0].equals("CN")){
val = opts[1]+';'+val; // always use CN as value if not yet set
}else if(frst.length() == 0){
frst = opts[0]; // copy 1st one to value if not yet set
}
}else{
event.set(key,unslash(opts[0]),""); // add as empty parameter
if(frst.length() == 0) frst = opts[0]; // copy 1st one to value if not yet set
}
}
// value might contain parameters
params = val.split("(?<!\\\\)[;]");
val = "";
for (String param : params) {
opts = param.split("(?<!\\\\)[=]",2);
if(opts.length == 2){
// add parameter as extra
event.set(key,unslash(opts[0]),unslash(opts[1]));
}else{
// seems not to be a parameter, set as value if not yet set
if(val.length() == 0){
val = opts[0];
}else{
// we have a value already, maybe it's an inline parameter like MAILTO:
alt = opts[0].split("(?<!\\\\)[=]",2);
if(alt.length == 2){
event.set(key,unslash(alt[0]),unslash(alt[1]));
}else{
event.set(key,unslash(opts[0]),""); // add as empty parameter
}
}
}
}
// set value to event
if(val.length() == 0) val = frst;
event.set(key, unslash(val));
}
}
line = nextline;
}
return null; //Shouldn't be reached except for EOF
}
|
diff --git a/classes/com/sapienter/jbilling/client/user/MaintainAction.java b/classes/com/sapienter/jbilling/client/user/MaintainAction.java
index 0528feb2..947adab4 100644
--- a/classes/com/sapienter/jbilling/client/user/MaintainAction.java
+++ b/classes/com/sapienter/jbilling/client/user/MaintainAction.java
@@ -1,290 +1,290 @@
/*
The contents of this file are subject to the Jbilling 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.jbilling.com/JPL/
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 jbilling.
The Initial Developer of the Original Code is Emiliano Conde.
Portions created by Sapienter Billing Software Corp. are Copyright
(C) Sapienter Billing Software Corp. All Rights Reserved.
Contributor(s): ______________________________________.
*/
package com.sapienter.jbilling.client.user;
import java.io.IOException;
import javax.ejb.FinderException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.validator.DynaValidatorForm;
import com.sapienter.jbilling.client.util.Constants;
import com.sapienter.jbilling.common.JNDILookup;
import com.sapienter.jbilling.interfaces.InvoiceSession;
import com.sapienter.jbilling.interfaces.InvoiceSessionHome;
import com.sapienter.jbilling.interfaces.UserSession;
import com.sapienter.jbilling.interfaces.UserSessionHome;
import com.sapienter.jbilling.server.order.NewOrderDTO;
import com.sapienter.jbilling.server.user.CustomerDTOEx;
import com.sapienter.jbilling.server.user.UserDTOEx;
import com.sapienter.jbilling.server.entity.UserDTO;
public class MaintainAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
ActionErrors errors = new ActionErrors();
ActionMessages messages = new ActionMessages();
Logger log = Logger.getLogger(MaintainAction.class);
HttpSession session = request.getSession(false);
String action = request.getParameter("action");
if (action == null) {
log.error("action is required in maintain action");
throw new ServletException("action is required");
}
// this page requires a forward from, but not a forward to, as it
// always reders itself back with the result of the sumbision
String forward = (String) session.getAttribute(
Constants.SESSION_FORWARD_FROM);
Integer userId = (Integer) session.getAttribute(
Constants.SESSION_USER_ID);
Integer executorId = (Integer) session.getAttribute(
Constants.SESSION_LOGGED_USER_ID);
UserDTOEx userDto = (UserDTOEx) session.getAttribute(
Constants.SESSION_USER_DTO);
try {
JNDILookup EJBFactory = JNDILookup.getFactory(false);
UserSessionHome userHome =
(UserSessionHome) EJBFactory.lookUpHome(
UserSessionHome.class,
UserSessionHome.JNDI_NAME);
UserSession userSession = userHome.create();
if (action.equals("setup")) {
String id = request.getParameter("id");
if (id != null) {
// called from anywhere to see a customer
userId = Integer.valueOf(id);
} else {
// called from the list when selectin a customer
userId = (Integer) session.getAttribute(
Constants.SESSION_LIST_ID_SELECTED);
}
userDto = userSession.getUserDTOEx(userId);
session.setAttribute(Constants.SESSION_CUSTOMER_DTO,
userDto);
session.setAttribute(Constants.SESSION_USER_ID,
userId);
session.setAttribute(Constants.SESSION_CUSTOMER_CONTACT_DTO,
userSession.getPrimaryContactDTO(userId));
// add the last invoice dto
InvoiceSessionHome invoiceHome =
(InvoiceSessionHome) EJBFactory.lookUpHome(
InvoiceSessionHome.class,
InvoiceSessionHome.JNDI_NAME);
InvoiceSession invoiceSession = invoiceHome.create();
if (userDto.getLastInvoiceId() != null) {
log.debug("adding the latest inovoice: " +
userDto.getLastInvoiceId());
Integer languageId = (Integer) session.getAttribute(
Constants.SESSION_LANGUAGE);
session.setAttribute(Constants.SESSION_INVOICE_DTO,
invoiceSession.getInvoiceEx(userDto.getLastInvoiceId(),
languageId));
} else {
log.debug("there is no invoices.");
session.removeAttribute(Constants.SESSION_INVOICE_DTO);
}
return mapping.findForward("view");
}
if (forward == null) {
log.error("forward is required in the session");
throw new ServletException("forward is required in the session");
}
if (userId == null) {
log.error("userId is required in the session");
throw new ServletException("userId is required in the session");
}
if (action.equals("delete")) {
userSession.delete(executorId, userId);
// after deleting, it goes to the maintain page, showing the
// list of users
forward = Constants.FORWARD_USER_MAINTAIN;
messages.add(ActionMessages.GLOBAL_MESSAGE,
new ActionMessage("user.delete.done", userId));
// get rid of the cached list of users
session.removeAttribute(Constants.SESSION_LIST_KEY +
Constants.LIST_TYPE_CUSTOMER);
session.removeAttribute(Constants.SESSION_LIST_KEY +
Constants.LIST_TYPE_CUSTOMER_SIMPLE);
} else if (action.equals("update")) {
DynaValidatorForm userForm = (DynaValidatorForm) form;
// get the info in its current status
UserDTOEx orgUser = (UserDTOEx) session.getAttribute(
Constants.SESSION_CUSTOMER_DTO);
log.debug("Updating user: ");
// general validation first
errors = userForm.validate(mapping, request);
// verify that the password and the verification password
// are the same, but only if the verify password has been
// entered, otherwise will consider that the password is not
// being changed
String vPassword = (String) userForm.get("verifyPassword");
String password = (String) userForm.get("password");
boolean updatePassword = false;
if ((vPassword != null && vPassword.trim().length() > 0) ||
(password != null && password.trim().length() > 0)) {
updatePassword = true;
}
if (updatePassword && (password == null ||
password.trim().length() == 0 || vPassword == null ||
vPassword.trim().length() == 0 ||
!password.equals(vPassword))) {
errors.add(ActionErrors.GLOBAL_ERROR,
new ActionError("user.create.error.password_match"));
}
// test that the old password is correct if this is a self-update
if (updatePassword && userId.equals(executorId) &&
!userDto.getPassword().equals((String) userForm.get(
"oldPassword"))) {
errors.add(ActionErrors.GLOBAL_ERROR,
new ActionError("user.edit.error.invalidOldPassword"));
}
String partnerId = (String) userForm.get("partnerId");
// validate the partnerId if present
- if (partnerId != null && partnerId.length() > 0) {
+ if (errors.isEmpty() && partnerId != null && partnerId.length() > 0) {
try {
userSession.getPartnerDTO(Integer.valueOf(partnerId));
} catch (FinderException e) {
errors.add(ActionErrors.GLOBAL_ERROR,
new ActionError("user.create.error.badPartner"));
}
}
// the login name has to be unique across entities
// test only if it has changed
if (orgUser != null && !orgUser.getUserName().equals((String)
userForm.get("username"))) {
UserDTO testUser = userSession.getUserDTO(
(String) userForm.get("username"),
(Integer) userForm.get("entity"));
if (testUser != null) {
errors.add(ActionErrors.GLOBAL_ERROR,
new ActionError("user.create.error.taken",
(String) userForm.get("username")));
}
}
if (errors.isEmpty()) {
// create a dto with the info from the form
UserDTOEx dto = new UserDTOEx();
dto.setUserId(userId);
dto.setEntityId((Integer) userForm.get("entity"));
dto.setMainRoleId((Integer) userForm.get("type"));
dto.setUserName((String) userForm.get("username"));
if (updatePassword) {
dto.setPassword((String) userForm.get("password"));
} else {
dto.setPassword(null);
}
dto.setLanguageId((Integer) userForm.get("language"));
dto.setStatusId((Integer) userForm.get("status"));
dto.setCurrencyId((Integer) userForm.get("currencyId"));
if (dto.getMainRoleId().equals(Constants.TYPE_CUSTOMER)) {
dto.setCustomerDto(new CustomerDTOEx());
dto.getCustomerDto().setInvoiceDeliveryMethodId(
(Integer) userForm.get("deliveryMethodId"));
dto.getCustomerDto().setDueDateUnitId(
(Integer) userForm.get("due_date_unit_id"));
String value = (String) userForm.get("due_date_value");
if (value != null && value.length() > 0) {
dto.getCustomerDto().setDueDateValue(
Integer.valueOf(value));
} else {
dto.getCustomerDto().setDueDateValue(null);
}
dto.getCustomerDto().setDfFm(new Integer(((Boolean)
userForm.get("chbx_df_fm")).booleanValue()
? 1 : 0));
dto.getCustomerDto().setExcludeAging(new Integer(((Boolean)
userForm.get("chbx_excludeAging")).booleanValue()
? 1 : 0));
if (partnerId != null && partnerId.length() > 0) {
dto.getCustomerDto().setPartnerId(Integer.valueOf(
partnerId));
} else {
dto.getCustomerDto().setPartnerId(null);
}
}
// I pass who am I and the info to update
userSession.update(executorId, dto);
messages.add(ActionMessages.GLOBAL_MESSAGE,
new ActionMessage("user.edit.done"));
}
} else if (action.equals("order")) {
NewOrderDTO summary = new NewOrderDTO();
session.setAttribute(Constants.SESSION_ORDER_SUMMARY,
summary);
session.setAttribute(Constants.SESSION_CUSTOMER_CONTACT_DTO,
userSession.getPrimaryContactDTO(userId));
forward = "order";
} else {
log.error("action not supported" + action);
throw new ServletException("action is not supported :" + action);
}
saveMessages(request, messages);
} catch (Exception e) {
errors.add(ActionErrors.GLOBAL_ERROR,
new ActionError("all.internal"));
log.debug("Exception:", e);
}
if (!errors.isEmpty()) {
saveErrors(request, errors);
}
return mapping.findForward(forward);
}
}
| true | true | public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
ActionErrors errors = new ActionErrors();
ActionMessages messages = new ActionMessages();
Logger log = Logger.getLogger(MaintainAction.class);
HttpSession session = request.getSession(false);
String action = request.getParameter("action");
if (action == null) {
log.error("action is required in maintain action");
throw new ServletException("action is required");
}
// this page requires a forward from, but not a forward to, as it
// always reders itself back with the result of the sumbision
String forward = (String) session.getAttribute(
Constants.SESSION_FORWARD_FROM);
Integer userId = (Integer) session.getAttribute(
Constants.SESSION_USER_ID);
Integer executorId = (Integer) session.getAttribute(
Constants.SESSION_LOGGED_USER_ID);
UserDTOEx userDto = (UserDTOEx) session.getAttribute(
Constants.SESSION_USER_DTO);
try {
JNDILookup EJBFactory = JNDILookup.getFactory(false);
UserSessionHome userHome =
(UserSessionHome) EJBFactory.lookUpHome(
UserSessionHome.class,
UserSessionHome.JNDI_NAME);
UserSession userSession = userHome.create();
if (action.equals("setup")) {
String id = request.getParameter("id");
if (id != null) {
// called from anywhere to see a customer
userId = Integer.valueOf(id);
} else {
// called from the list when selectin a customer
userId = (Integer) session.getAttribute(
Constants.SESSION_LIST_ID_SELECTED);
}
userDto = userSession.getUserDTOEx(userId);
session.setAttribute(Constants.SESSION_CUSTOMER_DTO,
userDto);
session.setAttribute(Constants.SESSION_USER_ID,
userId);
session.setAttribute(Constants.SESSION_CUSTOMER_CONTACT_DTO,
userSession.getPrimaryContactDTO(userId));
// add the last invoice dto
InvoiceSessionHome invoiceHome =
(InvoiceSessionHome) EJBFactory.lookUpHome(
InvoiceSessionHome.class,
InvoiceSessionHome.JNDI_NAME);
InvoiceSession invoiceSession = invoiceHome.create();
if (userDto.getLastInvoiceId() != null) {
log.debug("adding the latest inovoice: " +
userDto.getLastInvoiceId());
Integer languageId = (Integer) session.getAttribute(
Constants.SESSION_LANGUAGE);
session.setAttribute(Constants.SESSION_INVOICE_DTO,
invoiceSession.getInvoiceEx(userDto.getLastInvoiceId(),
languageId));
} else {
log.debug("there is no invoices.");
session.removeAttribute(Constants.SESSION_INVOICE_DTO);
}
return mapping.findForward("view");
}
if (forward == null) {
log.error("forward is required in the session");
throw new ServletException("forward is required in the session");
}
if (userId == null) {
log.error("userId is required in the session");
throw new ServletException("userId is required in the session");
}
if (action.equals("delete")) {
userSession.delete(executorId, userId);
// after deleting, it goes to the maintain page, showing the
// list of users
forward = Constants.FORWARD_USER_MAINTAIN;
messages.add(ActionMessages.GLOBAL_MESSAGE,
new ActionMessage("user.delete.done", userId));
// get rid of the cached list of users
session.removeAttribute(Constants.SESSION_LIST_KEY +
Constants.LIST_TYPE_CUSTOMER);
session.removeAttribute(Constants.SESSION_LIST_KEY +
Constants.LIST_TYPE_CUSTOMER_SIMPLE);
} else if (action.equals("update")) {
DynaValidatorForm userForm = (DynaValidatorForm) form;
// get the info in its current status
UserDTOEx orgUser = (UserDTOEx) session.getAttribute(
Constants.SESSION_CUSTOMER_DTO);
log.debug("Updating user: ");
// general validation first
errors = userForm.validate(mapping, request);
// verify that the password and the verification password
// are the same, but only if the verify password has been
// entered, otherwise will consider that the password is not
// being changed
String vPassword = (String) userForm.get("verifyPassword");
String password = (String) userForm.get("password");
boolean updatePassword = false;
if ((vPassword != null && vPassword.trim().length() > 0) ||
(password != null && password.trim().length() > 0)) {
updatePassword = true;
}
if (updatePassword && (password == null ||
password.trim().length() == 0 || vPassword == null ||
vPassword.trim().length() == 0 ||
!password.equals(vPassword))) {
errors.add(ActionErrors.GLOBAL_ERROR,
new ActionError("user.create.error.password_match"));
}
// test that the old password is correct if this is a self-update
if (updatePassword && userId.equals(executorId) &&
!userDto.getPassword().equals((String) userForm.get(
"oldPassword"))) {
errors.add(ActionErrors.GLOBAL_ERROR,
new ActionError("user.edit.error.invalidOldPassword"));
}
String partnerId = (String) userForm.get("partnerId");
// validate the partnerId if present
if (partnerId != null && partnerId.length() > 0) {
try {
userSession.getPartnerDTO(Integer.valueOf(partnerId));
} catch (FinderException e) {
errors.add(ActionErrors.GLOBAL_ERROR,
new ActionError("user.create.error.badPartner"));
}
}
// the login name has to be unique across entities
// test only if it has changed
if (orgUser != null && !orgUser.getUserName().equals((String)
userForm.get("username"))) {
UserDTO testUser = userSession.getUserDTO(
(String) userForm.get("username"),
(Integer) userForm.get("entity"));
if (testUser != null) {
errors.add(ActionErrors.GLOBAL_ERROR,
new ActionError("user.create.error.taken",
(String) userForm.get("username")));
}
}
if (errors.isEmpty()) {
// create a dto with the info from the form
UserDTOEx dto = new UserDTOEx();
dto.setUserId(userId);
dto.setEntityId((Integer) userForm.get("entity"));
dto.setMainRoleId((Integer) userForm.get("type"));
dto.setUserName((String) userForm.get("username"));
if (updatePassword) {
dto.setPassword((String) userForm.get("password"));
} else {
dto.setPassword(null);
}
dto.setLanguageId((Integer) userForm.get("language"));
dto.setStatusId((Integer) userForm.get("status"));
dto.setCurrencyId((Integer) userForm.get("currencyId"));
if (dto.getMainRoleId().equals(Constants.TYPE_CUSTOMER)) {
dto.setCustomerDto(new CustomerDTOEx());
dto.getCustomerDto().setInvoiceDeliveryMethodId(
(Integer) userForm.get("deliveryMethodId"));
dto.getCustomerDto().setDueDateUnitId(
(Integer) userForm.get("due_date_unit_id"));
String value = (String) userForm.get("due_date_value");
if (value != null && value.length() > 0) {
dto.getCustomerDto().setDueDateValue(
Integer.valueOf(value));
} else {
dto.getCustomerDto().setDueDateValue(null);
}
dto.getCustomerDto().setDfFm(new Integer(((Boolean)
userForm.get("chbx_df_fm")).booleanValue()
? 1 : 0));
dto.getCustomerDto().setExcludeAging(new Integer(((Boolean)
userForm.get("chbx_excludeAging")).booleanValue()
? 1 : 0));
if (partnerId != null && partnerId.length() > 0) {
dto.getCustomerDto().setPartnerId(Integer.valueOf(
partnerId));
} else {
dto.getCustomerDto().setPartnerId(null);
}
}
// I pass who am I and the info to update
userSession.update(executorId, dto);
messages.add(ActionMessages.GLOBAL_MESSAGE,
new ActionMessage("user.edit.done"));
}
} else if (action.equals("order")) {
NewOrderDTO summary = new NewOrderDTO();
session.setAttribute(Constants.SESSION_ORDER_SUMMARY,
summary);
session.setAttribute(Constants.SESSION_CUSTOMER_CONTACT_DTO,
userSession.getPrimaryContactDTO(userId));
forward = "order";
} else {
log.error("action not supported" + action);
throw new ServletException("action is not supported :" + action);
}
saveMessages(request, messages);
} catch (Exception e) {
errors.add(ActionErrors.GLOBAL_ERROR,
new ActionError("all.internal"));
log.debug("Exception:", e);
}
if (!errors.isEmpty()) {
saveErrors(request, errors);
}
return mapping.findForward(forward);
}
| public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
ActionErrors errors = new ActionErrors();
ActionMessages messages = new ActionMessages();
Logger log = Logger.getLogger(MaintainAction.class);
HttpSession session = request.getSession(false);
String action = request.getParameter("action");
if (action == null) {
log.error("action is required in maintain action");
throw new ServletException("action is required");
}
// this page requires a forward from, but not a forward to, as it
// always reders itself back with the result of the sumbision
String forward = (String) session.getAttribute(
Constants.SESSION_FORWARD_FROM);
Integer userId = (Integer) session.getAttribute(
Constants.SESSION_USER_ID);
Integer executorId = (Integer) session.getAttribute(
Constants.SESSION_LOGGED_USER_ID);
UserDTOEx userDto = (UserDTOEx) session.getAttribute(
Constants.SESSION_USER_DTO);
try {
JNDILookup EJBFactory = JNDILookup.getFactory(false);
UserSessionHome userHome =
(UserSessionHome) EJBFactory.lookUpHome(
UserSessionHome.class,
UserSessionHome.JNDI_NAME);
UserSession userSession = userHome.create();
if (action.equals("setup")) {
String id = request.getParameter("id");
if (id != null) {
// called from anywhere to see a customer
userId = Integer.valueOf(id);
} else {
// called from the list when selectin a customer
userId = (Integer) session.getAttribute(
Constants.SESSION_LIST_ID_SELECTED);
}
userDto = userSession.getUserDTOEx(userId);
session.setAttribute(Constants.SESSION_CUSTOMER_DTO,
userDto);
session.setAttribute(Constants.SESSION_USER_ID,
userId);
session.setAttribute(Constants.SESSION_CUSTOMER_CONTACT_DTO,
userSession.getPrimaryContactDTO(userId));
// add the last invoice dto
InvoiceSessionHome invoiceHome =
(InvoiceSessionHome) EJBFactory.lookUpHome(
InvoiceSessionHome.class,
InvoiceSessionHome.JNDI_NAME);
InvoiceSession invoiceSession = invoiceHome.create();
if (userDto.getLastInvoiceId() != null) {
log.debug("adding the latest inovoice: " +
userDto.getLastInvoiceId());
Integer languageId = (Integer) session.getAttribute(
Constants.SESSION_LANGUAGE);
session.setAttribute(Constants.SESSION_INVOICE_DTO,
invoiceSession.getInvoiceEx(userDto.getLastInvoiceId(),
languageId));
} else {
log.debug("there is no invoices.");
session.removeAttribute(Constants.SESSION_INVOICE_DTO);
}
return mapping.findForward("view");
}
if (forward == null) {
log.error("forward is required in the session");
throw new ServletException("forward is required in the session");
}
if (userId == null) {
log.error("userId is required in the session");
throw new ServletException("userId is required in the session");
}
if (action.equals("delete")) {
userSession.delete(executorId, userId);
// after deleting, it goes to the maintain page, showing the
// list of users
forward = Constants.FORWARD_USER_MAINTAIN;
messages.add(ActionMessages.GLOBAL_MESSAGE,
new ActionMessage("user.delete.done", userId));
// get rid of the cached list of users
session.removeAttribute(Constants.SESSION_LIST_KEY +
Constants.LIST_TYPE_CUSTOMER);
session.removeAttribute(Constants.SESSION_LIST_KEY +
Constants.LIST_TYPE_CUSTOMER_SIMPLE);
} else if (action.equals("update")) {
DynaValidatorForm userForm = (DynaValidatorForm) form;
// get the info in its current status
UserDTOEx orgUser = (UserDTOEx) session.getAttribute(
Constants.SESSION_CUSTOMER_DTO);
log.debug("Updating user: ");
// general validation first
errors = userForm.validate(mapping, request);
// verify that the password and the verification password
// are the same, but only if the verify password has been
// entered, otherwise will consider that the password is not
// being changed
String vPassword = (String) userForm.get("verifyPassword");
String password = (String) userForm.get("password");
boolean updatePassword = false;
if ((vPassword != null && vPassword.trim().length() > 0) ||
(password != null && password.trim().length() > 0)) {
updatePassword = true;
}
if (updatePassword && (password == null ||
password.trim().length() == 0 || vPassword == null ||
vPassword.trim().length() == 0 ||
!password.equals(vPassword))) {
errors.add(ActionErrors.GLOBAL_ERROR,
new ActionError("user.create.error.password_match"));
}
// test that the old password is correct if this is a self-update
if (updatePassword && userId.equals(executorId) &&
!userDto.getPassword().equals((String) userForm.get(
"oldPassword"))) {
errors.add(ActionErrors.GLOBAL_ERROR,
new ActionError("user.edit.error.invalidOldPassword"));
}
String partnerId = (String) userForm.get("partnerId");
// validate the partnerId if present
if (errors.isEmpty() && partnerId != null && partnerId.length() > 0) {
try {
userSession.getPartnerDTO(Integer.valueOf(partnerId));
} catch (FinderException e) {
errors.add(ActionErrors.GLOBAL_ERROR,
new ActionError("user.create.error.badPartner"));
}
}
// the login name has to be unique across entities
// test only if it has changed
if (orgUser != null && !orgUser.getUserName().equals((String)
userForm.get("username"))) {
UserDTO testUser = userSession.getUserDTO(
(String) userForm.get("username"),
(Integer) userForm.get("entity"));
if (testUser != null) {
errors.add(ActionErrors.GLOBAL_ERROR,
new ActionError("user.create.error.taken",
(String) userForm.get("username")));
}
}
if (errors.isEmpty()) {
// create a dto with the info from the form
UserDTOEx dto = new UserDTOEx();
dto.setUserId(userId);
dto.setEntityId((Integer) userForm.get("entity"));
dto.setMainRoleId((Integer) userForm.get("type"));
dto.setUserName((String) userForm.get("username"));
if (updatePassword) {
dto.setPassword((String) userForm.get("password"));
} else {
dto.setPassword(null);
}
dto.setLanguageId((Integer) userForm.get("language"));
dto.setStatusId((Integer) userForm.get("status"));
dto.setCurrencyId((Integer) userForm.get("currencyId"));
if (dto.getMainRoleId().equals(Constants.TYPE_CUSTOMER)) {
dto.setCustomerDto(new CustomerDTOEx());
dto.getCustomerDto().setInvoiceDeliveryMethodId(
(Integer) userForm.get("deliveryMethodId"));
dto.getCustomerDto().setDueDateUnitId(
(Integer) userForm.get("due_date_unit_id"));
String value = (String) userForm.get("due_date_value");
if (value != null && value.length() > 0) {
dto.getCustomerDto().setDueDateValue(
Integer.valueOf(value));
} else {
dto.getCustomerDto().setDueDateValue(null);
}
dto.getCustomerDto().setDfFm(new Integer(((Boolean)
userForm.get("chbx_df_fm")).booleanValue()
? 1 : 0));
dto.getCustomerDto().setExcludeAging(new Integer(((Boolean)
userForm.get("chbx_excludeAging")).booleanValue()
? 1 : 0));
if (partnerId != null && partnerId.length() > 0) {
dto.getCustomerDto().setPartnerId(Integer.valueOf(
partnerId));
} else {
dto.getCustomerDto().setPartnerId(null);
}
}
// I pass who am I and the info to update
userSession.update(executorId, dto);
messages.add(ActionMessages.GLOBAL_MESSAGE,
new ActionMessage("user.edit.done"));
}
} else if (action.equals("order")) {
NewOrderDTO summary = new NewOrderDTO();
session.setAttribute(Constants.SESSION_ORDER_SUMMARY,
summary);
session.setAttribute(Constants.SESSION_CUSTOMER_CONTACT_DTO,
userSession.getPrimaryContactDTO(userId));
forward = "order";
} else {
log.error("action not supported" + action);
throw new ServletException("action is not supported :" + action);
}
saveMessages(request, messages);
} catch (Exception e) {
errors.add(ActionErrors.GLOBAL_ERROR,
new ActionError("all.internal"));
log.debug("Exception:", e);
}
if (!errors.isEmpty()) {
saveErrors(request, errors);
}
return mapping.findForward(forward);
}
|
diff --git a/src/au/org/intersect/samifier/parser/GenomeParserImpl.java b/src/au/org/intersect/samifier/parser/GenomeParserImpl.java
index 591028d..c47e3d8 100644
--- a/src/au/org/intersect/samifier/parser/GenomeParserImpl.java
+++ b/src/au/org/intersect/samifier/parser/GenomeParserImpl.java
@@ -1,205 +1,205 @@
package au.org.intersect.samifier.parser;
import au.org.intersect.samifier.domain.GeneInfo;
import au.org.intersect.samifier.domain.GeneSequence;
import au.org.intersect.samifier.domain.Genome;
import au.org.intersect.samifier.domain.VirtualProtein;
import org.apache.log4j.Logger;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GenomeParserImpl implements GenomeParser {
private static Logger LOG = Logger.getLogger(GenomeParserImpl.class);
public static final Pattern GENE_RE = Pattern.compile("^(gene|gene_cassette|pseudogene|transposable_element_gene)$");
private static final String STRAND_FORWARD = "+";
private static final Pattern STRAND_RE = Pattern.compile("^([" + STRAND_FORWARD + "]|[-])$");
public static final String CODING_SEQUENCE = "CDS";
public static final String INTRON = "intron";
public static final Pattern SEQUENCE_RE = Pattern.compile("(" + CODING_SEQUENCE + "|" + INTRON + ")");
//private static final Pattern ID_ATTRIBUTE_RE = Pattern.compile(".*Name=([^_;]+).*");
private static final Pattern ID_ATTRIBUTE_RE = Pattern.compile(".*Name=([^;]+).*");
private static final Pattern PARENT_ATTRIBUTE_RE = Pattern.compile(".*Parent=([^;]+).*");
//private static final Pattern PARENT_ATTRIBUTE_RE = Pattern.compile(".*Parent=([^_;]+).*");
private static final Pattern VIRTUAL_PROTEIN_ATTRIBUTE_RE = Pattern.compile(".*Virtual_protein=([^;]+).*");
private static final Pattern BRACKETS = Pattern.compile("\\((.*?)\\)");
private String genomeFileName;
private int lineNumber = 0;
private String line;
public GenomeParserImpl() {
}
public Genome parseGenomeFile(File genomeFile)
throws GenomeFileParsingException {
try {
genomeFileName = genomeFile.getAbsolutePath();
return doParsing(genomeFile);
} catch (IOException e) {
throw new GenomeFileParsingException(e.getMessage());
}
}
private Genome doParsing(File genomeFile) throws IOException,
GenomeFileParsingException {
Genome genome = new Genome();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(genomeFile));
while ((line = reader.readLine()) != null) {
lineNumber++;
- if (line.matches("^\\s*#")) {
+ if (line.startsWith("##")){
continue;
}
// chromosome, source, type, start, stop, score, strand, phase,
// attributes
String[] parts = line.split("\\t", 9);
if (parts.length < 9) {
// throw new
// GenomeFileParsingException("Line "+lineNumber+": not in expected format");
LOG.warn("Line " + lineNumber + ": not in expected format");
continue;
}
String type = parts[2];
if (type == null) {
continue;
}
if (GENE_RE.matcher(type).matches()) {
GeneInfo gene = parseGene(parts);
processGene(genome, gene);
} else if (SEQUENCE_RE.matcher(type).find()) {
GeneSequence sequence = parseSequence(parts);
processSequence(genome, parts[CHROMOSOME_PART], sequence);
}
}
} finally {
if (reader != null) {
reader.close();
}
}
genome.verify();
return genome;
}
private void throwParsingException(String message)
throws GenomeFileParsingException {
throw new GenomeFileParsingException("Error in " + genomeFileName + ":"
+ lineNumber + " " + line + "\n > " + message);
}
private int parseStrand(String direction) throws GenomeFileParsingException {
if (!STRAND_RE.matcher(direction).matches()) {
throwParsingException("Invalid strand " + direction);
}
return STRAND_FORWARD.equals(direction) ? 1 : -1;
}
private boolean parseSequenceType(String type)
throws GenomeFileParsingException {
return CODING_SEQUENCE.equals(type);
}
protected GeneInfo parseGene(String[] parts)
throws GenomeFileParsingException {
String chromosome = parts[CHROMOSOME_PART];
int start = Integer.parseInt(parts[START_PART]);
int stop = Integer.parseInt(parts[STOP_PART]);
String direction = parts[STRAND_PART];
if (start > stop) {
throwParsingException("Start-stop invalid");
}
//parse virtual genes
return new GeneInfo(chromosome, extractId(parts[ATTRIBUTES_PART]), start, stop, parseStrand(direction), parseVirtualProteins(parts[ATTRIBUTES_PART]));
}
private List<VirtualProtein> parseVirtualProteins(String attributes) {
List<VirtualProtein> virtualProteins = new ArrayList<VirtualProtein>();
Matcher m = VIRTUAL_PROTEIN_ATTRIBUTE_RE.matcher(attributes);
if (!(m.matches())) {
return virtualProteins;
}
String vProteinsString = m.group(1);
String[] vProteinArray = vProteinsString.split(",");
for (String vp : vProteinArray) {
Matcher matcher = BRACKETS.matcher(vp);
if (matcher.find()) {
String[] offsets = matcher.group(1).split("-");
int startOffset = Integer.parseInt(offsets[0]);
int endOffset = Integer.parseInt(offsets[1]);
String name = vp.replaceAll(BRACKETS.pattern(), "");
virtualProteins.add(new VirtualProtein(name, startOffset, endOffset));
}
}
return virtualProteins;
}
protected GeneSequence parseSequence(String[] parts)
throws GenomeFileParsingException {
String type = parts[TYPE_PART];
int start = Integer.parseInt(parts[START_PART]);
int stop = Integer.parseInt(parts[STOP_PART]);
String direction = parts[STRAND_PART];
if (start > stop) {
throwParsingException("Start-stop invalid");
}
return new GeneSequence(extractParent(parts[ATTRIBUTES_PART]), parseSequenceType(type), start, stop, parseStrand(direction), parseVirtualProteins(parts[ATTRIBUTES_PART]));
}
private void processGene(Genome genome, GeneInfo gene) {
genome.addGene(gene);
}
private void processSequence(Genome genome, String chromosome,
GeneSequence sequence) throws GenomeFileParsingException {
if (!genome.hasGene(sequence.getParentId())) {
GeneInfo gene = new GeneInfo(chromosome, sequence.getParentId(),
sequence.getStart(), sequence.getStop(),
sequence.getDirection(), sequence.getVirtualProteins());
genome.addGene(gene);
}
GeneInfo gene = genome.getGene(sequence.getParentId());
if (gene.getDirection() != sequence.getDirection()) {
throwParsingException("A sequence in gene " + gene.getId() + " has inconsistent direction");
}
if (gene.getStart() > sequence.getStart()) {
throwParsingException("Start of sequence in gene " + gene.getId() + " overflows gene");
}
if (gene.getStop() < sequence.getStop()) {
throwParsingException("Stop of sequence in gene " + gene.getId() + " overflows gene");
}
genome.getGene(sequence.getParentId()).addLocation(sequence);
}
private String extractId(String attributes)
throws GenomeFileParsingException {
Matcher m = ID_ATTRIBUTE_RE.matcher(attributes);
if (m.matches()) {
return m.group(1);
}
throwParsingException("Attribute ID not found");
return null; // make compiler happy
}
private String extractParent(String attributes)
throws GenomeFileParsingException {
Matcher m = PARENT_ATTRIBUTE_RE.matcher(attributes);
if (m.matches()) {
return m.group(1).replace("_mRNA", "");
}
throwParsingException("Attribute Parent not found");
return null; // make compiler happy
}
}
| true | true | private Genome doParsing(File genomeFile) throws IOException,
GenomeFileParsingException {
Genome genome = new Genome();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(genomeFile));
while ((line = reader.readLine()) != null) {
lineNumber++;
if (line.matches("^\\s*#")) {
continue;
}
// chromosome, source, type, start, stop, score, strand, phase,
// attributes
String[] parts = line.split("\\t", 9);
if (parts.length < 9) {
// throw new
// GenomeFileParsingException("Line "+lineNumber+": not in expected format");
LOG.warn("Line " + lineNumber + ": not in expected format");
continue;
}
String type = parts[2];
if (type == null) {
continue;
}
if (GENE_RE.matcher(type).matches()) {
GeneInfo gene = parseGene(parts);
processGene(genome, gene);
} else if (SEQUENCE_RE.matcher(type).find()) {
GeneSequence sequence = parseSequence(parts);
processSequence(genome, parts[CHROMOSOME_PART], sequence);
}
}
} finally {
if (reader != null) {
reader.close();
}
}
genome.verify();
return genome;
}
| private Genome doParsing(File genomeFile) throws IOException,
GenomeFileParsingException {
Genome genome = new Genome();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(genomeFile));
while ((line = reader.readLine()) != null) {
lineNumber++;
if (line.startsWith("##")){
continue;
}
// chromosome, source, type, start, stop, score, strand, phase,
// attributes
String[] parts = line.split("\\t", 9);
if (parts.length < 9) {
// throw new
// GenomeFileParsingException("Line "+lineNumber+": not in expected format");
LOG.warn("Line " + lineNumber + ": not in expected format");
continue;
}
String type = parts[2];
if (type == null) {
continue;
}
if (GENE_RE.matcher(type).matches()) {
GeneInfo gene = parseGene(parts);
processGene(genome, gene);
} else if (SEQUENCE_RE.matcher(type).find()) {
GeneSequence sequence = parseSequence(parts);
processSequence(genome, parts[CHROMOSOME_PART], sequence);
}
}
} finally {
if (reader != null) {
reader.close();
}
}
genome.verify();
return genome;
}
|
diff --git a/src/TandemTree.java b/src/TandemTree.java
index df09646..f5ac5a2 100644
--- a/src/TandemTree.java
+++ b/src/TandemTree.java
@@ -1,22 +1,23 @@
import org.antlr.runtime.ANTLRStringStream;
import org.antlr.runtime.CommonTokenStream;
import org.antlr.runtime.RecognitionException;
import org.antlr.runtime.TokenStream;
import org.antlr.runtime.tree.CommonTree;
import java.io.*;
import org.antlr.runtime.*;
public class TandemTree{
public static void main(String args[]){
try{
TanGLexer lex = new TanGLexer(new ANTLRInputStream(new FileInputStream(args[0])));
TokenStream ts = new CommonTokenStream(lex);
+ lex.reset();
TanGParser parse = new TanGParser(ts);
parse.tanG();
} catch(Exception e) {
System.err.println("exception: "+e);
}
}
}
| true | true | public static void main(String args[]){
try{
TanGLexer lex = new TanGLexer(new ANTLRInputStream(new FileInputStream(args[0])));
TokenStream ts = new CommonTokenStream(lex);
TanGParser parse = new TanGParser(ts);
parse.tanG();
} catch(Exception e) {
System.err.println("exception: "+e);
}
}
| public static void main(String args[]){
try{
TanGLexer lex = new TanGLexer(new ANTLRInputStream(new FileInputStream(args[0])));
TokenStream ts = new CommonTokenStream(lex);
lex.reset();
TanGParser parse = new TanGParser(ts);
parse.tanG();
} catch(Exception e) {
System.err.println("exception: "+e);
}
}
|
diff --git a/src/com/wickedspiral/jacss/parser/Parser.java b/src/com/wickedspiral/jacss/parser/Parser.java
index 537cd32..4540fd4 100644
--- a/src/com/wickedspiral/jacss/parser/Parser.java
+++ b/src/com/wickedspiral/jacss/parser/Parser.java
@@ -1,619 +1,620 @@
package com.wickedspiral.jacss.parser;
import com.google.common.base.Joiner;
import com.wickedspiral.jacss.Options;
import com.wickedspiral.jacss.lexer.Token;
import com.wickedspiral.jacss.lexer.TokenListener;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedList;
import static com.wickedspiral.jacss.lexer.Token.*;
/**
* @author wasche
* @since 2011.08.04
*/
public class Parser implements TokenListener
{
private static final Joiner NULL_JOINER = Joiner.on( "" );
private static final String MS_ALPHA = "progid:dximagetransform.microsoft.alpha(opacity=";
private static final String MS_SHADOW = "progid:dximagetransform.microsoft.shadow";
private static final Collection<String> UNITS = new HashSet<>(
Arrays.asList( "px", "em", "pt", "in", "cm", "mm", "pc", "ex", "%" )
);
private final Collection<String> KEYWORDS = new HashSet<>(
Arrays.asList( "normal", "bold", "italic", "serif", "sans-serif", "fixed" )
);
private static final Collection<String> BOUNDARY_OPS = new HashSet<>(
Arrays.asList( "{", "}", "(", ")", ">", ";", ":", "," )
); // or comment
private static final Collection<String> DUAL_ZERO_PROPERTIES = new HashSet<>(
Arrays.asList( "background-position", "-webkit-transform-origin", "-moz-transform-origin" )
);
private static final Collection<String> NONE_PROPERTIES = new HashSet<>();
static
{
NONE_PROPERTIES.add( "outline" );
for ( String property : new String[]{ "border", "margin", "padding" } )
{
NONE_PROPERTIES.add( property );
for ( String edge : new String[]{ "top", "left", "bottom", "right" } )
{
NONE_PROPERTIES.add( property + "-" + edge );
}
}
}
// buffers
private LinkedList<String> ruleBuffer;
private LinkedList<String> valueBuffer;
private LinkedList<String> rgbBuffer;
private String pending;
// flags
private boolean inRule;
private boolean space;
private boolean charset;
private boolean at;
private boolean ie5mac;
private boolean rgb;
private boolean rgba;
private boolean colorStop;
private int checkSpace;
// other state
private String property;
private Token lastToken;
private String lastValue;
private final PrintStream out;
private final Options options;
public Parser( PrintStream outputStream, Options options )
{
out = outputStream;
ruleBuffer = new LinkedList<>();
valueBuffer = new LinkedList<>();
rgbBuffer = new LinkedList<>();
inRule = false;
space = false;
charset = false;
at = false;
ie5mac = false;
rgb = false;
checkSpace = -1;
this.options = options;
if (! options.shouldLowercasifyKeywords())
{
KEYWORDS.remove("sans-serif"); // Fix #25
}
}
// ++ Output functions
private void output( Collection<String> strings )
{
for ( String s : strings )
{
output( s );
}
}
private void output( String str )
{
out.print( str );
}
private void dump( String str )
{
ruleBuffer.add( pending );
ruleBuffer.add( str );
output( ruleBuffer );
ruleBuffer.clear();
pending = null;
}
private void write( String str )
{
if ( str == null || str.length() == 0 ) return;
if ( str.startsWith( "/*!" ) && ruleBuffer.isEmpty() )
{
output( str );
return;
}
ruleBuffer.add( str );
if ( "}".equals( str ) )
{
// check for empty rule
if ( ruleBuffer.size() < 2 || (ruleBuffer.size() >= 2 && !"{".equals( ruleBuffer.get( ruleBuffer.size() - 2 ) )) )
{
output( ruleBuffer );
}
ruleBuffer.clear();
}
}
private void buffer( String str )
{
if ( str == null || str.length() == 0 ) return;
if ( pending == null )
{
pending = str;
}
else
{
write( pending );
pending = str;
}
}
private void queue( String str )
{
if ( str == null || str.length() == 0 ) return;
if ( property != null )
{
valueBuffer.add( str );
}
else
{
buffer( str );
}
}
private void collapseValue()
{
String value = NULL_JOINER.join( valueBuffer );
valueBuffer.clear();
if ( "0 0".equals( value ) || "0 0 0 0".equals( value ) || "0 0 0".equals( value ) )
{
if ( DUAL_ZERO_PROPERTIES.contains( property ) )
{
buffer( "0 0" );
}
else
{
buffer("0");
}
}
else if ("none".equals(value) && (NONE_PROPERTIES.contains(property) || "background".equals(property)) && options.shouldCollapseNone())
{
buffer("0");
}
else
{
buffer(value);
}
}
private void space(boolean emit, String reason)
{
if (emit)
{
queue(" ");
if (options.isDebug()) System.err.println("Emit space because: " + reason);
}
else
{
if (options.isDebug()) System.err.println("Hide space because: " + reason);
}
}
// ++ TokenListener
public void token(Token token, String value)
{
if (options.isDebug()) System.err.printf("Token: %s, value: %s, space? %b, in rule? %b\n", token, value, space, inRule);
if (rgb)
{
if (NUMBER == token)
{
String h = Integer.toHexString(Integer.parseInt(value)).toLowerCase();
if (h.length() < 2)
{
h = "0" + h;
}
rgbBuffer.add(h);
}
else if (LPAREN == token)
{
if (NUMBER == lastToken)
{
space(true, "RGB value separator");
}
queue("#");
rgbBuffer.clear();
}
else if (RPAREN == token)
{
if (rgbBuffer.size() == 3)
{
String a = rgbBuffer.get(0);
String b = rgbBuffer.get(1);
String c = rgbBuffer.get(2);
if (a.charAt(0) == a.charAt(1) &&
b.charAt(0) == b.charAt(1) &&
c.charAt(0) == c.charAt(1))
{
queue(a.substring(0, 1));
queue(b.substring(0, 1));
queue(c.substring(0, 1));
rgb = false;
return;
}
}
for (String s : rgbBuffer)
{
queue(s);
}
rgb = false;
}
return;
}
if (token == WHITESPACE)
{
space = true;
return; // most of these are unneeded
}
if (token == COMMENT)
{
// comments are only needed in a few places:
// 1) special comments /*! ... */
if ('!' == value.charAt(2))
{
queue(value);
lastToken = token;
lastValue = value;
}
// 2) IE5/Mac hack
else if ('\\' == value.charAt(value.length()-3))
{
queue("/*\\*/");
lastToken = token;
lastValue = value;
ie5mac = true;
}
else if (ie5mac)
{
queue("/**/");
lastToken = token;
lastValue = value;
ie5mac = false;
}
// 3) After a child selector
else if (GT == lastToken)
{
queue("/**/");
lastToken = token;
lastValue = value;
}
return;
}
// make sure we have space between values for multi-value properties
// margin: 5px 5px
if ( inRule && (
(
NUMBER == lastToken &&
(HASH == token || NUMBER == token)
) ||
(
(IDENTIFIER == lastToken || PERCENT == lastToken || RPAREN == lastToken) &&
(NUMBER == token || IDENTIFIER == token || HASH == token)
)
))
{
space(true, "multi-value property separator");
space = false;
}
// rgb()
if (IDENTIFIER == token && "rgb".equals(value))
{
rgb = true;
space = false;
return;
}
if (IDENTIFIER == token && "rgba".equals(value))
{
rgba = true;
}
else if (RPAREN == token && rgba)
{
rgba = false;
}
// Fix #24, YUI color-stop() weirdness
if (LPAREN == token && "color-stop".equals(lastValue))
{
colorStop = true;
}
else if (RPAREN == token && colorStop)
{
colorStop = false;
}
if (AT == token)
{
queue(value);
at = true;
}
else if (inRule && COLON == token && property == null)
{
queue(value);
property = lastValue.toLowerCase();
valueBuffer.clear();
}
// first-letter and first-line must be followed by a space
else if (!inRule && COLON == lastToken && ("first-letter".equals(value) || "first-line".equals(value)))
{
queue(value);
space(true, "first-letter or first-line");
}
else if (SEMICOLON == token)
{
if (at)
{
at = false;
if ("charset".equals(ruleBuffer.get(1)))
{
if (charset)
{
ruleBuffer.clear();
pending = null;
}
else
{
charset = true;
dump(value);
}
}
else
{
dump(value);
}
}
else if (SEMICOLON == lastToken)
{
return; // skip duplicate semicolons
}
else
{
collapseValue();
valueBuffer.clear();
property = null;
queue(value);
}
}
else if (LBRACE == token)
{
if (checkSpace != -1)
{
// start of a rule, the space was correct
checkSpace = -1;
}
if (at)
{
at = false;
dump(value);
}
else
{
inRule = true;
queue(value);
}
}
else if (RBRACE == token)
{
if (checkSpace != -1)
{
// didn't start a rule, space was wrong
ruleBuffer.remove(checkSpace);
checkSpace = -1;
}
if (!valueBuffer.isEmpty())
{
collapseValue();
}
if (";".equals(pending))
{
if (options.keepTailingSemicolons())
{
buffer(";");
}
pending = value;
}
else if (options.addTrailingSemicolons()) // Fix #19
{
buffer(";" + value);
}
else
{
buffer(value);
}
property = null;
inRule = false;
}
else if (!inRule)
{
if (!space || GT == token || lastToken == null || BOUNDARY_OPS.contains( lastValue ))
{
queue(value);
}
else
{
if (COLON == token)
{
checkSpace = ruleBuffer.size() + 1; // include pending value
}
- if ( COMMENT != lastToken && !BOUNDARY_OPS.contains( lastValue ) )
+ if (COMMENT != lastToken &&
+ !BOUNDARY_OPS.contains( lastValue ) && !BOUNDARY_OPS.contains(value))
{
space(true, "needs comment");
}
queue(value);
space = false;
}
}
else if (NUMBER == token && value.startsWith("0."))
{
if ( options.shouldCollapseZeroes() || !rgba )
{
queue(value.substring(1));
}
else
{
queue( value );
}
}
else if (STRING == token && "-ms-filter".equals(property))
{
String v = value.toLowerCase();
if (v.startsWith(MS_ALPHA, 1))
{
String c = value.substring(0, 1);
String o = value.substring(MS_ALPHA.length()+1, value.length()-2);
queue(c);
queue("alpha(opacity=");
queue(o);
queue(")");
queue(c);
}
else if (v.startsWith(MS_SHADOW, 1))
{
queue(value.replaceAll(", +", ","));
}
else
{
queue(value);
}
}
else if (EQUALS == token)
{
queue(value);
StringBuilder sb = new StringBuilder();
for (String s : valueBuffer)
{
sb.append(s);
}
if (MS_ALPHA.equals(sb.toString().toLowerCase()))
{
buffer("alpha(opacity=");
valueBuffer.clear();
}
}
else
{
String v = value.toLowerCase();
// values of 0 don't need a unit
if (NUMBER == lastToken && "0".equals(lastValue) && (PERCENT == token || IDENTIFIER == token))
{
if (PERCENT == token && colorStop && options.keepUnitsInColorStop())
{
queue("%");
}
else if (!UNITS.contains(value))
{
space(true, "0 unknown units");
queue(value);
}
}
// use 0 instead of none
else if (COLON == lastToken && "none".equals(value) && NONE_PROPERTIES.contains(property) && options.shouldCollapseNone())
{
queue("0");
}
// force properties to lower case for better gzip compression
else if (COLON != lastToken && IDENTIFIER == token)
{
// #aabbcc
if (HASH == lastToken)
{
boolean eq = value.length() == 6 &&
v.charAt(0) == v.charAt(1) &&
v.charAt(2) == v.charAt(3) &&
v.charAt(4) == v.charAt(5);
if (!options.shouldLowercasifyRgb())
{
v = value;
}
if (eq)
{
queue(v.substring(0, 1));
queue(v.substring(2, 3));
queue(v.substring(4, 5));
}
else
{
queue(v);
}
}
else
{
if ( space && !BOUNDARY_OPS.contains( lastValue ) && BANG != token )
{
space(true, "need comment");
}
if (property == null || KEYWORDS.contains(v))
{
queue(v);
}
else
{
queue(value);
}
}
}
// nothing special, just send it along
else
{
if ( space && BANG != token &&
!BOUNDARY_OPS.contains(value) && !BOUNDARY_OPS.contains(lastValue))
{
space(true, "between token and non-boundary op");
}
if (KEYWORDS.contains(v))
{
queue(v);
}
else
{
queue(value);
}
}
}
lastToken = token;
lastValue = value;
space = false;
}
public void end()
{
write(pending);
if (!ruleBuffer.isEmpty())
{
output(ruleBuffer);
}
}
}
| true | true | public void token(Token token, String value)
{
if (options.isDebug()) System.err.printf("Token: %s, value: %s, space? %b, in rule? %b\n", token, value, space, inRule);
if (rgb)
{
if (NUMBER == token)
{
String h = Integer.toHexString(Integer.parseInt(value)).toLowerCase();
if (h.length() < 2)
{
h = "0" + h;
}
rgbBuffer.add(h);
}
else if (LPAREN == token)
{
if (NUMBER == lastToken)
{
space(true, "RGB value separator");
}
queue("#");
rgbBuffer.clear();
}
else if (RPAREN == token)
{
if (rgbBuffer.size() == 3)
{
String a = rgbBuffer.get(0);
String b = rgbBuffer.get(1);
String c = rgbBuffer.get(2);
if (a.charAt(0) == a.charAt(1) &&
b.charAt(0) == b.charAt(1) &&
c.charAt(0) == c.charAt(1))
{
queue(a.substring(0, 1));
queue(b.substring(0, 1));
queue(c.substring(0, 1));
rgb = false;
return;
}
}
for (String s : rgbBuffer)
{
queue(s);
}
rgb = false;
}
return;
}
if (token == WHITESPACE)
{
space = true;
return; // most of these are unneeded
}
if (token == COMMENT)
{
// comments are only needed in a few places:
// 1) special comments /*! ... */
if ('!' == value.charAt(2))
{
queue(value);
lastToken = token;
lastValue = value;
}
// 2) IE5/Mac hack
else if ('\\' == value.charAt(value.length()-3))
{
queue("/*\\*/");
lastToken = token;
lastValue = value;
ie5mac = true;
}
else if (ie5mac)
{
queue("/**/");
lastToken = token;
lastValue = value;
ie5mac = false;
}
// 3) After a child selector
else if (GT == lastToken)
{
queue("/**/");
lastToken = token;
lastValue = value;
}
return;
}
// make sure we have space between values for multi-value properties
// margin: 5px 5px
if ( inRule && (
(
NUMBER == lastToken &&
(HASH == token || NUMBER == token)
) ||
(
(IDENTIFIER == lastToken || PERCENT == lastToken || RPAREN == lastToken) &&
(NUMBER == token || IDENTIFIER == token || HASH == token)
)
))
{
space(true, "multi-value property separator");
space = false;
}
// rgb()
if (IDENTIFIER == token && "rgb".equals(value))
{
rgb = true;
space = false;
return;
}
if (IDENTIFIER == token && "rgba".equals(value))
{
rgba = true;
}
else if (RPAREN == token && rgba)
{
rgba = false;
}
// Fix #24, YUI color-stop() weirdness
if (LPAREN == token && "color-stop".equals(lastValue))
{
colorStop = true;
}
else if (RPAREN == token && colorStop)
{
colorStop = false;
}
if (AT == token)
{
queue(value);
at = true;
}
else if (inRule && COLON == token && property == null)
{
queue(value);
property = lastValue.toLowerCase();
valueBuffer.clear();
}
// first-letter and first-line must be followed by a space
else if (!inRule && COLON == lastToken && ("first-letter".equals(value) || "first-line".equals(value)))
{
queue(value);
space(true, "first-letter or first-line");
}
else if (SEMICOLON == token)
{
if (at)
{
at = false;
if ("charset".equals(ruleBuffer.get(1)))
{
if (charset)
{
ruleBuffer.clear();
pending = null;
}
else
{
charset = true;
dump(value);
}
}
else
{
dump(value);
}
}
else if (SEMICOLON == lastToken)
{
return; // skip duplicate semicolons
}
else
{
collapseValue();
valueBuffer.clear();
property = null;
queue(value);
}
}
else if (LBRACE == token)
{
if (checkSpace != -1)
{
// start of a rule, the space was correct
checkSpace = -1;
}
if (at)
{
at = false;
dump(value);
}
else
{
inRule = true;
queue(value);
}
}
else if (RBRACE == token)
{
if (checkSpace != -1)
{
// didn't start a rule, space was wrong
ruleBuffer.remove(checkSpace);
checkSpace = -1;
}
if (!valueBuffer.isEmpty())
{
collapseValue();
}
if (";".equals(pending))
{
if (options.keepTailingSemicolons())
{
buffer(";");
}
pending = value;
}
else if (options.addTrailingSemicolons()) // Fix #19
{
buffer(";" + value);
}
else
{
buffer(value);
}
property = null;
inRule = false;
}
else if (!inRule)
{
if (!space || GT == token || lastToken == null || BOUNDARY_OPS.contains( lastValue ))
{
queue(value);
}
else
{
if (COLON == token)
{
checkSpace = ruleBuffer.size() + 1; // include pending value
}
if ( COMMENT != lastToken && !BOUNDARY_OPS.contains( lastValue ) )
{
space(true, "needs comment");
}
queue(value);
space = false;
}
}
else if (NUMBER == token && value.startsWith("0."))
{
if ( options.shouldCollapseZeroes() || !rgba )
{
queue(value.substring(1));
}
else
{
queue( value );
}
}
else if (STRING == token && "-ms-filter".equals(property))
{
String v = value.toLowerCase();
if (v.startsWith(MS_ALPHA, 1))
{
String c = value.substring(0, 1);
String o = value.substring(MS_ALPHA.length()+1, value.length()-2);
queue(c);
queue("alpha(opacity=");
queue(o);
queue(")");
queue(c);
}
else if (v.startsWith(MS_SHADOW, 1))
{
queue(value.replaceAll(", +", ","));
}
else
{
queue(value);
}
}
else if (EQUALS == token)
{
queue(value);
StringBuilder sb = new StringBuilder();
for (String s : valueBuffer)
{
sb.append(s);
}
if (MS_ALPHA.equals(sb.toString().toLowerCase()))
{
buffer("alpha(opacity=");
valueBuffer.clear();
}
}
else
{
String v = value.toLowerCase();
// values of 0 don't need a unit
if (NUMBER == lastToken && "0".equals(lastValue) && (PERCENT == token || IDENTIFIER == token))
{
if (PERCENT == token && colorStop && options.keepUnitsInColorStop())
{
queue("%");
}
else if (!UNITS.contains(value))
{
space(true, "0 unknown units");
queue(value);
}
}
// use 0 instead of none
else if (COLON == lastToken && "none".equals(value) && NONE_PROPERTIES.contains(property) && options.shouldCollapseNone())
{
queue("0");
}
// force properties to lower case for better gzip compression
else if (COLON != lastToken && IDENTIFIER == token)
{
// #aabbcc
if (HASH == lastToken)
{
boolean eq = value.length() == 6 &&
v.charAt(0) == v.charAt(1) &&
v.charAt(2) == v.charAt(3) &&
v.charAt(4) == v.charAt(5);
if (!options.shouldLowercasifyRgb())
{
v = value;
}
if (eq)
{
queue(v.substring(0, 1));
queue(v.substring(2, 3));
queue(v.substring(4, 5));
}
else
{
queue(v);
}
}
else
{
if ( space && !BOUNDARY_OPS.contains( lastValue ) && BANG != token )
{
space(true, "need comment");
}
if (property == null || KEYWORDS.contains(v))
{
queue(v);
}
else
{
queue(value);
}
}
}
// nothing special, just send it along
else
{
if ( space && BANG != token &&
!BOUNDARY_OPS.contains(value) && !BOUNDARY_OPS.contains(lastValue))
{
space(true, "between token and non-boundary op");
}
if (KEYWORDS.contains(v))
{
queue(v);
}
else
{
queue(value);
}
}
}
lastToken = token;
lastValue = value;
space = false;
}
| public void token(Token token, String value)
{
if (options.isDebug()) System.err.printf("Token: %s, value: %s, space? %b, in rule? %b\n", token, value, space, inRule);
if (rgb)
{
if (NUMBER == token)
{
String h = Integer.toHexString(Integer.parseInt(value)).toLowerCase();
if (h.length() < 2)
{
h = "0" + h;
}
rgbBuffer.add(h);
}
else if (LPAREN == token)
{
if (NUMBER == lastToken)
{
space(true, "RGB value separator");
}
queue("#");
rgbBuffer.clear();
}
else if (RPAREN == token)
{
if (rgbBuffer.size() == 3)
{
String a = rgbBuffer.get(0);
String b = rgbBuffer.get(1);
String c = rgbBuffer.get(2);
if (a.charAt(0) == a.charAt(1) &&
b.charAt(0) == b.charAt(1) &&
c.charAt(0) == c.charAt(1))
{
queue(a.substring(0, 1));
queue(b.substring(0, 1));
queue(c.substring(0, 1));
rgb = false;
return;
}
}
for (String s : rgbBuffer)
{
queue(s);
}
rgb = false;
}
return;
}
if (token == WHITESPACE)
{
space = true;
return; // most of these are unneeded
}
if (token == COMMENT)
{
// comments are only needed in a few places:
// 1) special comments /*! ... */
if ('!' == value.charAt(2))
{
queue(value);
lastToken = token;
lastValue = value;
}
// 2) IE5/Mac hack
else if ('\\' == value.charAt(value.length()-3))
{
queue("/*\\*/");
lastToken = token;
lastValue = value;
ie5mac = true;
}
else if (ie5mac)
{
queue("/**/");
lastToken = token;
lastValue = value;
ie5mac = false;
}
// 3) After a child selector
else if (GT == lastToken)
{
queue("/**/");
lastToken = token;
lastValue = value;
}
return;
}
// make sure we have space between values for multi-value properties
// margin: 5px 5px
if ( inRule && (
(
NUMBER == lastToken &&
(HASH == token || NUMBER == token)
) ||
(
(IDENTIFIER == lastToken || PERCENT == lastToken || RPAREN == lastToken) &&
(NUMBER == token || IDENTIFIER == token || HASH == token)
)
))
{
space(true, "multi-value property separator");
space = false;
}
// rgb()
if (IDENTIFIER == token && "rgb".equals(value))
{
rgb = true;
space = false;
return;
}
if (IDENTIFIER == token && "rgba".equals(value))
{
rgba = true;
}
else if (RPAREN == token && rgba)
{
rgba = false;
}
// Fix #24, YUI color-stop() weirdness
if (LPAREN == token && "color-stop".equals(lastValue))
{
colorStop = true;
}
else if (RPAREN == token && colorStop)
{
colorStop = false;
}
if (AT == token)
{
queue(value);
at = true;
}
else if (inRule && COLON == token && property == null)
{
queue(value);
property = lastValue.toLowerCase();
valueBuffer.clear();
}
// first-letter and first-line must be followed by a space
else if (!inRule && COLON == lastToken && ("first-letter".equals(value) || "first-line".equals(value)))
{
queue(value);
space(true, "first-letter or first-line");
}
else if (SEMICOLON == token)
{
if (at)
{
at = false;
if ("charset".equals(ruleBuffer.get(1)))
{
if (charset)
{
ruleBuffer.clear();
pending = null;
}
else
{
charset = true;
dump(value);
}
}
else
{
dump(value);
}
}
else if (SEMICOLON == lastToken)
{
return; // skip duplicate semicolons
}
else
{
collapseValue();
valueBuffer.clear();
property = null;
queue(value);
}
}
else if (LBRACE == token)
{
if (checkSpace != -1)
{
// start of a rule, the space was correct
checkSpace = -1;
}
if (at)
{
at = false;
dump(value);
}
else
{
inRule = true;
queue(value);
}
}
else if (RBRACE == token)
{
if (checkSpace != -1)
{
// didn't start a rule, space was wrong
ruleBuffer.remove(checkSpace);
checkSpace = -1;
}
if (!valueBuffer.isEmpty())
{
collapseValue();
}
if (";".equals(pending))
{
if (options.keepTailingSemicolons())
{
buffer(";");
}
pending = value;
}
else if (options.addTrailingSemicolons()) // Fix #19
{
buffer(";" + value);
}
else
{
buffer(value);
}
property = null;
inRule = false;
}
else if (!inRule)
{
if (!space || GT == token || lastToken == null || BOUNDARY_OPS.contains( lastValue ))
{
queue(value);
}
else
{
if (COLON == token)
{
checkSpace = ruleBuffer.size() + 1; // include pending value
}
if (COMMENT != lastToken &&
!BOUNDARY_OPS.contains( lastValue ) && !BOUNDARY_OPS.contains(value))
{
space(true, "needs comment");
}
queue(value);
space = false;
}
}
else if (NUMBER == token && value.startsWith("0."))
{
if ( options.shouldCollapseZeroes() || !rgba )
{
queue(value.substring(1));
}
else
{
queue( value );
}
}
else if (STRING == token && "-ms-filter".equals(property))
{
String v = value.toLowerCase();
if (v.startsWith(MS_ALPHA, 1))
{
String c = value.substring(0, 1);
String o = value.substring(MS_ALPHA.length()+1, value.length()-2);
queue(c);
queue("alpha(opacity=");
queue(o);
queue(")");
queue(c);
}
else if (v.startsWith(MS_SHADOW, 1))
{
queue(value.replaceAll(", +", ","));
}
else
{
queue(value);
}
}
else if (EQUALS == token)
{
queue(value);
StringBuilder sb = new StringBuilder();
for (String s : valueBuffer)
{
sb.append(s);
}
if (MS_ALPHA.equals(sb.toString().toLowerCase()))
{
buffer("alpha(opacity=");
valueBuffer.clear();
}
}
else
{
String v = value.toLowerCase();
// values of 0 don't need a unit
if (NUMBER == lastToken && "0".equals(lastValue) && (PERCENT == token || IDENTIFIER == token))
{
if (PERCENT == token && colorStop && options.keepUnitsInColorStop())
{
queue("%");
}
else if (!UNITS.contains(value))
{
space(true, "0 unknown units");
queue(value);
}
}
// use 0 instead of none
else if (COLON == lastToken && "none".equals(value) && NONE_PROPERTIES.contains(property) && options.shouldCollapseNone())
{
queue("0");
}
// force properties to lower case for better gzip compression
else if (COLON != lastToken && IDENTIFIER == token)
{
// #aabbcc
if (HASH == lastToken)
{
boolean eq = value.length() == 6 &&
v.charAt(0) == v.charAt(1) &&
v.charAt(2) == v.charAt(3) &&
v.charAt(4) == v.charAt(5);
if (!options.shouldLowercasifyRgb())
{
v = value;
}
if (eq)
{
queue(v.substring(0, 1));
queue(v.substring(2, 3));
queue(v.substring(4, 5));
}
else
{
queue(v);
}
}
else
{
if ( space && !BOUNDARY_OPS.contains( lastValue ) && BANG != token )
{
space(true, "need comment");
}
if (property == null || KEYWORDS.contains(v))
{
queue(v);
}
else
{
queue(value);
}
}
}
// nothing special, just send it along
else
{
if ( space && BANG != token &&
!BOUNDARY_OPS.contains(value) && !BOUNDARY_OPS.contains(lastValue))
{
space(true, "between token and non-boundary op");
}
if (KEYWORDS.contains(v))
{
queue(v);
}
else
{
queue(value);
}
}
}
lastToken = token;
lastValue = value;
space = false;
}
|
diff --git a/integration/src/test/java/org/slf4j/MultiBindingTest.java b/integration/src/test/java/org/slf4j/MultiBindingTest.java
index f17bd257..7e1b1838 100644
--- a/integration/src/test/java/org/slf4j/MultiBindingTest.java
+++ b/integration/src/test/java/org/slf4j/MultiBindingTest.java
@@ -1,62 +1,62 @@
/*
* Copyright (c) 2004-2009 QOS.ch
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.slf4j;
import java.io.PrintStream;
import java.util.Random;
import junit.framework.TestCase;
public class MultiBindingTest extends TestCase {
StringPrintStream sps = new StringPrintStream(System.err);
PrintStream old = System.err;
int diff = 1024 + new Random().nextInt(10000);
public MultiBindingTest(String name) {
super(name);
}
protected void setUp() throws Exception {
super.setUp();
System.setErr(sps);
}
protected void tearDown() throws Exception {
super.tearDown();
System.setErr(old);
}
public void test() throws Exception {
Logger logger = LoggerFactory.getLogger(this.getClass());
String msg = "hello world " + diff;
logger.info(msg);
assertTrue("number of lines should be greater than 4", sps.stringList
.size() > 4);
String s0 = (String) sps.stringList.get(0);
assertTrue(s0
- .contains("SLF4J: Class path contains multiple SLF4J bindins."));
+ .contains("SLF4J: Class path contains multiple SLF4J bindings."));
}
}
| true | true | public void test() throws Exception {
Logger logger = LoggerFactory.getLogger(this.getClass());
String msg = "hello world " + diff;
logger.info(msg);
assertTrue("number of lines should be greater than 4", sps.stringList
.size() > 4);
String s0 = (String) sps.stringList.get(0);
assertTrue(s0
.contains("SLF4J: Class path contains multiple SLF4J bindins."));
}
| public void test() throws Exception {
Logger logger = LoggerFactory.getLogger(this.getClass());
String msg = "hello world " + diff;
logger.info(msg);
assertTrue("number of lines should be greater than 4", sps.stringList
.size() > 4);
String s0 = (String) sps.stringList.get(0);
assertTrue(s0
.contains("SLF4J: Class path contains multiple SLF4J bindings."));
}
|
diff --git a/src/ru/regenix/jphp/compiler/jvm/stetament/MethodStmtCompiler.java b/src/ru/regenix/jphp/compiler/jvm/stetament/MethodStmtCompiler.java
index ff56e0eb..252c1246 100644
--- a/src/ru/regenix/jphp/compiler/jvm/stetament/MethodStmtCompiler.java
+++ b/src/ru/regenix/jphp/compiler/jvm/stetament/MethodStmtCompiler.java
@@ -1,384 +1,386 @@
package ru.regenix.jphp.compiler.jvm.stetament;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.LabelNode;
import org.objectweb.asm.tree.LocalVariableNode;
import org.objectweb.asm.tree.MethodNode;
import ru.regenix.jphp.common.Messages;
import ru.regenix.jphp.compiler.common.misc.StackItem;
import ru.regenix.jphp.compiler.jvm.misc.JumpItem;
import ru.regenix.jphp.compiler.jvm.misc.LocalVariable;
import ru.regenix.jphp.compiler.jvm.node.MethodNodeImpl;
import ru.regenix.jphp.exceptions.CompileException;
import ru.regenix.jphp.runtime.env.Environment;
import ru.regenix.jphp.runtime.memory.ArrayMemory;
import ru.regenix.jphp.runtime.memory.support.Memory;
import ru.regenix.jphp.runtime.reflection.MethodEntity;
import ru.regenix.jphp.runtime.reflection.ParameterEntity;
import ru.regenix.jphp.tokenizer.TokenMeta;
import ru.regenix.jphp.tokenizer.token.Token;
import ru.regenix.jphp.tokenizer.token.stmt.ArgumentStmtToken;
import ru.regenix.jphp.tokenizer.token.stmt.ExprStmtToken;
import ru.regenix.jphp.tokenizer.token.stmt.MethodStmtToken;
import ru.regenix.jphp.tokenizer.token.stmt.ReturnStmtToken;
import java.util.*;
public class MethodStmtCompiler extends StmtCompiler<MethodEntity> {
public final ClassStmtCompiler clazz;
public final MethodStmtToken statement;
public final MethodNode node;
protected int statementIndex = 0;
private Stack<StackItem> stack = new Stack<StackItem>();
private final List<JumpItem> jumpStack = new ArrayList<JumpItem>();
private int stackLevel = 0;
private int stackSize = 0;
private int stackMaxSize = 0;
private Map<String, LocalVariable> localVariables;
protected String realName;
private boolean external = false;
private long methodId;
public MethodStmtCompiler(ClassStmtCompiler clazz, MethodNode node){
super(clazz.getCompiler());
this.clazz = clazz;
this.statement = null;
this.node = node;
this.localVariables = new LinkedHashMap<String, LocalVariable>();
entity = new MethodEntity(getCompiler().getContext());
entity.setClazz(clazz.entity);
entity.setName(node.name);
realName = entity.getName();
methodId = compiler.getScope().nextMethodIndex();
}
public MethodStmtCompiler(ClassStmtCompiler clazz, MethodStmtToken statement) {
super(clazz.getCompiler());
this.clazz = clazz;
this.statement = statement;
this.node = new MethodNodeImpl();
this.localVariables = new LinkedHashMap<String, LocalVariable>();
entity = new MethodEntity(getCompiler().getContext());
entity.setClazz(clazz.entity);
if (statement != null)
entity.setName(statement.getName().getName());
realName = entity.getName();
methodId = compiler.getScope().nextMethodIndex();
}
public long getMethodId() {
return methodId;
}
public long getClassId(){
return clazz.entity.getId();
}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
public boolean isExternal() {
return external;
}
public void setExternal(boolean external) {
this.external = external;
}
public Map<String, LocalVariable> getLocalVariables() {
return localVariables;
}
int nextStatementIndex(){
return statementIndex++;
}
void pushJump(LabelNode breakLabel, LabelNode continueLabel, int stackSize){
jumpStack.add(new JumpItem(breakLabel, continueLabel, stackSize));
}
void pushJump(LabelNode breakLabel, LabelNode continueLabel){
pushJump(breakLabel, continueLabel, 0);
}
JumpItem getJump(int level){
if (jumpStack.size() - level < 0)
return null;
if (jumpStack.size() - level >= jumpStack.size())
return null;
return jumpStack.get(jumpStack.size() - level);
}
int getJumpStackSize(int level){
int size = 0;
for(int i = jumpStack.size(); i >= 0 && jumpStack.size() - i < level; i--){
JumpItem item = getJump(i);
size += item.stackSize;
}
return size;
}
void popJump(){
jumpStack.remove(jumpStack.size() - 1);
}
void push(StackItem item) {
if (item.getLevel() == -1)
item.setLevel(stackLevel++);
stack.push(item);
stackSize += item.size;
if (stackMaxSize < stackSize)
stackMaxSize = stackSize;
}
int getStackSize(){
return stackSize;
}
int getStackCount(){
return stack.size();
}
StackItem pop(){
StackItem item = stack.pop();
stackSize -= item.size;
return item;
}
void popAll(){
stackSize = 0;
stack.clear();
}
StackItem peek(){
return stack.peek();
}
LocalVariable addLocalVariable(String variable, LabelNode label, Class clazz){
LocalVariable result;
localVariables.put(
variable,
result = new LocalVariable(variable, localVariables.size(), label, clazz)
);
return result;
}
LocalVariable addLocalVariable(String variable, LabelNode label){
return addLocalVariable(variable, label, Memory.class);
}
LocalVariable getLocalVariable(String variable){
return localVariables.get(variable);
}
void writeHeader(){
int access = 0;
if (statement != null){
switch (statement.getModifier()){
case PRIVATE: access += Opcodes.ACC_PRIVATE; break;
case PROTECTED: access += Opcodes.ACC_PROTECTED; break;
case PUBLIC: access += Opcodes.ACC_PUBLIC; break;
}
if (statement.isStatic()) access += Opcodes.ACC_STATIC;
if (statement.isAbstract()) access += Opcodes.ACC_ABSTRACT;
if (statement.isFinal()) access += Opcodes.ACC_FINAL;
node.access = access;
node.name = clazz.isSystem() || entity == null ? statement.getName().getName() : entity.getInternalName();
node.desc = Type.getMethodDescriptor(
Type.getType(Memory.class),
Type.getType(Environment.class),
Type.getType(Memory[].class)
);
if (external){
node.desc = Type.getMethodDescriptor(
Type.getType(Memory.class),
Type.getType(Environment.class),
Type.getType(Memory[].class),
Type.getType(ArrayMemory.class)
);
}
}
if (statement != null){
LabelNode label = writeLabel(node, statement.getMeta().getStartLine());
if (!statement.isStatic())
addLocalVariable("~this", label, Object.class);
addLocalVariable("~env", label, Environment.class); // Environment env
LocalVariable args = addLocalVariable("~args", label, Memory[].class); // Memory[] arguments
if (statement.isDynamicLocal()){
if (external)
addLocalVariable("~passedLocal", label, ArrayMemory.class);
LocalVariable local = addLocalVariable("~local", label, ArrayMemory.class);
ExpressionStmtCompiler expressionCompiler = new ExpressionStmtCompiler(this, null);
if (external){
expressionCompiler.writeVarLoad("~passedLocal");
expressionCompiler.writeSysStaticCall(ArrayMemory.class, "valueOfRef", ArrayMemory.class, ArrayMemory.class);
expressionCompiler.setStackPeekAsImmutable();
expressionCompiler.writeVarStore(local, false, true);
} else {
- expressionCompiler.writePushNewObject(ArrayMemory.class);
+ expressionCompiler.writePushConstNull();
+ expressionCompiler.writeSysStaticCall(ArrayMemory.class, "valueOfRef", ArrayMemory.class, ArrayMemory.class);
+ expressionCompiler.setStackPeekAsImmutable();
expressionCompiler.writeVarStore(local, false, true);
}
}
if (statement.getUses() != null && !statement.getUses().isEmpty()){
int i = 0;
ExpressionStmtCompiler expressionCompiler = new ExpressionStmtCompiler(this, null);
expressionCompiler.writeVarLoad("~this");
expressionCompiler.writeGetDynamic("uses", Memory[].class);
for (ArgumentStmtToken argument : statement.getUses()){
LocalVariable local = addLocalVariable(argument.getName().getName(), label, Memory.class);
if (argument.isReference()){
local.setReference(true);
statement.getUnstableLocal().add(argument.getName());
}
expressionCompiler.writePushDup();
expressionCompiler.writePushGetFromArray(i, Memory.class);
expressionCompiler.writeVarStore(local, false, false);
local.pushLevel();
i++;
}
expressionCompiler.writePopAll(1);
}
int i = 0;
for(ArgumentStmtToken argument : statement.getArguments()){
LocalVariable local = addLocalVariable(argument.getName().getName(), label, Memory.class);
if (argument.isReference()){
local.setReference(true);
statement.getUnstableLocal().add(argument.getName());
}
ExpressionStmtCompiler expressionCompiler = new ExpressionStmtCompiler(this, null);
expressionCompiler.writeVarLoad(args);
expressionCompiler.writePushGetFromArray(i, Memory.class);
expressionCompiler.writeVarStore(local, false, false);
local.pushLevel();
i++;
}
} else {
LabelNode label = writeLabel(node, clazz.statement.getMeta().getStartLine());
}
}
@SuppressWarnings("unchecked")
void writeFooter(){
LabelNode endL = new LabelNode();
node.instructions.add(endL);
for(LocalVariable variable : localVariables.values()){
String description = Type.getDescriptor(variable.getClazz() == null ? Object.class : variable.getClazz());
if (variable.name.equals("~this"))
description = "L" + clazz.statement.getFulledName('/') + ";";
node.localVariables.add(new LocalVariableNode(
variable.name,
description,
null,
variable.label,
endL,
variable.index
));
}
//node.maxStack = this.stackMaxSize; !!! we don't need this, see: ClassWriter.COMPUTE_FRAMES
//node.maxLocals = this.localVariables.size();
}
@Override
public MethodEntity compile() {
if (statement != null){
if (external)
statement.setDynamicLocal(true);
entity.setAbstract(statement.isAbstract());
entity.setFinal(statement.isFinal());
entity.setStatic(statement.isStatic());
entity.setModifier(statement.getModifier());
entity.setReturnReference(statement.isReturnReference());
if (clazz.isSystem())
entity.setInternalName(entity.getName());
else
entity.setInternalName(entity.getName() + "$" + clazz.entity.nextMethodIndex());
ParameterEntity[] parameters = new ParameterEntity[statement.getArguments().size()];
int i = 0;
for(ArgumentStmtToken argument : statement.getArguments()){
parameters[i] = new ParameterEntity(compiler.getContext());
parameters[i].setMethod(entity);
parameters[i].setReference(argument.isReference());
parameters[i].setName(argument.getName().getName());
ExpressionStmtCompiler expressionStmtCompiler = new ExpressionStmtCompiler(compiler);
if (argument.getValue() != null){
Memory defaultValue = expressionStmtCompiler.writeExpression(argument.getValue(), true, true, false);
if (defaultValue == null){
throw new CompileException(
Messages.ERR_COMPILE_EXPECTED_CONST_VALUE.fetch(argument.getName()),
argument.toTraceInfo(compiler.getContext())
);
}
parameters[i].setDefaultValue(defaultValue);
}
if (argument.getValue() != null){
ExpressionStmtCompiler expressionCompiler = new ExpressionStmtCompiler(this, null);
Memory result = expressionCompiler.writeExpression(argument.getValue(), true, true);
if (result == null){
unexpectedToken(argument.getValue().getTokens().get(0));
}
parameters[i].setDefaultValue( result );
}
i++;
}
entity.setParameters(parameters);
}
writeHeader();
if (statement != null && statement.getBody() != null){
for(ExprStmtToken instruction : statement.getBody().getInstructions()){
compiler.compileExpression(this, instruction);
}
}
ReturnStmtToken token = new ReturnStmtToken(new TokenMeta("", 0, 0, 0, 0));
token.setValue(new ExprStmtToken(Token.of("null")));
compiler.compileExpression(this, new ExprStmtToken(token));
writeFooter();
return entity;
}
}
| true | true | void writeHeader(){
int access = 0;
if (statement != null){
switch (statement.getModifier()){
case PRIVATE: access += Opcodes.ACC_PRIVATE; break;
case PROTECTED: access += Opcodes.ACC_PROTECTED; break;
case PUBLIC: access += Opcodes.ACC_PUBLIC; break;
}
if (statement.isStatic()) access += Opcodes.ACC_STATIC;
if (statement.isAbstract()) access += Opcodes.ACC_ABSTRACT;
if (statement.isFinal()) access += Opcodes.ACC_FINAL;
node.access = access;
node.name = clazz.isSystem() || entity == null ? statement.getName().getName() : entity.getInternalName();
node.desc = Type.getMethodDescriptor(
Type.getType(Memory.class),
Type.getType(Environment.class),
Type.getType(Memory[].class)
);
if (external){
node.desc = Type.getMethodDescriptor(
Type.getType(Memory.class),
Type.getType(Environment.class),
Type.getType(Memory[].class),
Type.getType(ArrayMemory.class)
);
}
}
if (statement != null){
LabelNode label = writeLabel(node, statement.getMeta().getStartLine());
if (!statement.isStatic())
addLocalVariable("~this", label, Object.class);
addLocalVariable("~env", label, Environment.class); // Environment env
LocalVariable args = addLocalVariable("~args", label, Memory[].class); // Memory[] arguments
if (statement.isDynamicLocal()){
if (external)
addLocalVariable("~passedLocal", label, ArrayMemory.class);
LocalVariable local = addLocalVariable("~local", label, ArrayMemory.class);
ExpressionStmtCompiler expressionCompiler = new ExpressionStmtCompiler(this, null);
if (external){
expressionCompiler.writeVarLoad("~passedLocal");
expressionCompiler.writeSysStaticCall(ArrayMemory.class, "valueOfRef", ArrayMemory.class, ArrayMemory.class);
expressionCompiler.setStackPeekAsImmutable();
expressionCompiler.writeVarStore(local, false, true);
} else {
expressionCompiler.writePushNewObject(ArrayMemory.class);
expressionCompiler.writeVarStore(local, false, true);
}
}
if (statement.getUses() != null && !statement.getUses().isEmpty()){
int i = 0;
ExpressionStmtCompiler expressionCompiler = new ExpressionStmtCompiler(this, null);
expressionCompiler.writeVarLoad("~this");
expressionCompiler.writeGetDynamic("uses", Memory[].class);
for (ArgumentStmtToken argument : statement.getUses()){
LocalVariable local = addLocalVariable(argument.getName().getName(), label, Memory.class);
if (argument.isReference()){
local.setReference(true);
statement.getUnstableLocal().add(argument.getName());
}
expressionCompiler.writePushDup();
expressionCompiler.writePushGetFromArray(i, Memory.class);
expressionCompiler.writeVarStore(local, false, false);
local.pushLevel();
i++;
}
expressionCompiler.writePopAll(1);
}
int i = 0;
for(ArgumentStmtToken argument : statement.getArguments()){
LocalVariable local = addLocalVariable(argument.getName().getName(), label, Memory.class);
if (argument.isReference()){
local.setReference(true);
statement.getUnstableLocal().add(argument.getName());
}
ExpressionStmtCompiler expressionCompiler = new ExpressionStmtCompiler(this, null);
expressionCompiler.writeVarLoad(args);
expressionCompiler.writePushGetFromArray(i, Memory.class);
expressionCompiler.writeVarStore(local, false, false);
local.pushLevel();
i++;
}
} else {
LabelNode label = writeLabel(node, clazz.statement.getMeta().getStartLine());
}
}
| void writeHeader(){
int access = 0;
if (statement != null){
switch (statement.getModifier()){
case PRIVATE: access += Opcodes.ACC_PRIVATE; break;
case PROTECTED: access += Opcodes.ACC_PROTECTED; break;
case PUBLIC: access += Opcodes.ACC_PUBLIC; break;
}
if (statement.isStatic()) access += Opcodes.ACC_STATIC;
if (statement.isAbstract()) access += Opcodes.ACC_ABSTRACT;
if (statement.isFinal()) access += Opcodes.ACC_FINAL;
node.access = access;
node.name = clazz.isSystem() || entity == null ? statement.getName().getName() : entity.getInternalName();
node.desc = Type.getMethodDescriptor(
Type.getType(Memory.class),
Type.getType(Environment.class),
Type.getType(Memory[].class)
);
if (external){
node.desc = Type.getMethodDescriptor(
Type.getType(Memory.class),
Type.getType(Environment.class),
Type.getType(Memory[].class),
Type.getType(ArrayMemory.class)
);
}
}
if (statement != null){
LabelNode label = writeLabel(node, statement.getMeta().getStartLine());
if (!statement.isStatic())
addLocalVariable("~this", label, Object.class);
addLocalVariable("~env", label, Environment.class); // Environment env
LocalVariable args = addLocalVariable("~args", label, Memory[].class); // Memory[] arguments
if (statement.isDynamicLocal()){
if (external)
addLocalVariable("~passedLocal", label, ArrayMemory.class);
LocalVariable local = addLocalVariable("~local", label, ArrayMemory.class);
ExpressionStmtCompiler expressionCompiler = new ExpressionStmtCompiler(this, null);
if (external){
expressionCompiler.writeVarLoad("~passedLocal");
expressionCompiler.writeSysStaticCall(ArrayMemory.class, "valueOfRef", ArrayMemory.class, ArrayMemory.class);
expressionCompiler.setStackPeekAsImmutable();
expressionCompiler.writeVarStore(local, false, true);
} else {
expressionCompiler.writePushConstNull();
expressionCompiler.writeSysStaticCall(ArrayMemory.class, "valueOfRef", ArrayMemory.class, ArrayMemory.class);
expressionCompiler.setStackPeekAsImmutable();
expressionCompiler.writeVarStore(local, false, true);
}
}
if (statement.getUses() != null && !statement.getUses().isEmpty()){
int i = 0;
ExpressionStmtCompiler expressionCompiler = new ExpressionStmtCompiler(this, null);
expressionCompiler.writeVarLoad("~this");
expressionCompiler.writeGetDynamic("uses", Memory[].class);
for (ArgumentStmtToken argument : statement.getUses()){
LocalVariable local = addLocalVariable(argument.getName().getName(), label, Memory.class);
if (argument.isReference()){
local.setReference(true);
statement.getUnstableLocal().add(argument.getName());
}
expressionCompiler.writePushDup();
expressionCompiler.writePushGetFromArray(i, Memory.class);
expressionCompiler.writeVarStore(local, false, false);
local.pushLevel();
i++;
}
expressionCompiler.writePopAll(1);
}
int i = 0;
for(ArgumentStmtToken argument : statement.getArguments()){
LocalVariable local = addLocalVariable(argument.getName().getName(), label, Memory.class);
if (argument.isReference()){
local.setReference(true);
statement.getUnstableLocal().add(argument.getName());
}
ExpressionStmtCompiler expressionCompiler = new ExpressionStmtCompiler(this, null);
expressionCompiler.writeVarLoad(args);
expressionCompiler.writePushGetFromArray(i, Memory.class);
expressionCompiler.writeVarStore(local, false, false);
local.pushLevel();
i++;
}
} else {
LabelNode label = writeLabel(node, clazz.statement.getMeta().getStartLine());
}
}
|
diff --git a/atlas-web/src/main/java/ae3/service/AtlasBitIndexQueryService.java b/atlas-web/src/main/java/ae3/service/AtlasBitIndexQueryService.java
index 9178e31e9..31c134f52 100644
--- a/atlas-web/src/main/java/ae3/service/AtlasBitIndexQueryService.java
+++ b/atlas-web/src/main/java/ae3/service/AtlasBitIndexQueryService.java
@@ -1,485 +1,483 @@
package ae3.service;
import com.google.common.base.Function;
import com.google.common.collect.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import uk.ac.ebi.gxa.efo.Efo;
import uk.ac.ebi.gxa.index.StatisticsStorageFactory;
import uk.ac.ebi.gxa.index.builder.IndexBuilder;
import uk.ac.ebi.gxa.statistics.*;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.File;
import java.io.IOException;
import java.util.*;
import static uk.ac.ebi.gxa.exceptions.LogUtil.logUnexpected;
/**
* This class provides gene expression statistics query service:
* - manages the index storage management and interaction with IndexBuider service
* - delegates statistics queries to StatisticsQueryUtils
*/
public class AtlasBitIndexQueryService implements AtlasStatisticsQueryService {
final private Logger log = LoggerFactory.getLogger(getClass());
// Handler for the BitIndex builder
private IndexBuilder indexBuilder;
// Bitindex Object which is de-serialized from indexFileName in atlasIndexDir
private StatisticsStorage<Long> statisticsStorage;
private File atlasIndexDir;
private String indexFileName;
// Used for finding children for query efo's
private Efo efo;
public AtlasBitIndexQueryService(String indexFileName) {
this.indexFileName = indexFileName;
}
public void setAtlasIndex(File atlasIndexDir) {
this.atlasIndexDir = atlasIndexDir;
}
public void setIndexBuilder(IndexBuilder indexBuilder) {
this.indexBuilder = indexBuilder;
indexBuilder.registerIndexBuildEventHandler(this);
}
public void setStatisticsStorage(StatisticsStorage<Long> statisticsStorage) {
this.statisticsStorage = statisticsStorage;
}
public void setEfo(Efo efo) {
this.efo = efo;
}
/**
* Index rebuild notification handler - after bit index is re-built, de-serialize it into statisticsStorage and re-populate statTypeToEfoToScores cache
*/
public void onIndexBuildFinish() {
StatisticsStorageFactory statisticsStorageFactory = new StatisticsStorageFactory(indexFileName);
statisticsStorageFactory.setAtlasIndex(atlasIndexDir);
try {
statisticsStorage = statisticsStorageFactory.createStatisticsStorage();
} catch (IOException ioe) {
String errMsg = "Failed to create statisticsStorage from " + new File(atlasIndexDir.getAbsolutePath(), indexFileName);
log.error(errMsg, ioe);
throw logUnexpected(errMsg, ioe);
}
}
public void onIndexBuildStart() {
// Nothing to do here
}
/**
* Destructor called by Spring
*
* @throws Exception
*/
public void destroy() throws Exception {
if (indexBuilder != null)
indexBuilder.unregisterIndexBuildEventHandler(this);
}
/**
* @param attribute
* @param geneId
* @return Experiment count for statisticsType, attributes and geneId
*/
public Integer getExperimentCountsForGene(Attribute attribute, Long geneId) {
return getExperimentCountsForGene(attribute, geneId, null, null);
}
/**
* @param attribute
* @param geneId
* @return Experiment count for statisticsType, attributes and geneId
*/
public Integer getExperimentCountsForGene(
Attribute attribute,
Long geneId,
Set<Long> geneRestrictionSet,
HashMap<String, Multiset<Integer>> scoresCacheForStatType) {
if (geneRestrictionSet == null) { // By default restrict the experiment count query to geneId
geneRestrictionSet = Collections.singleton(geneId);
}
StatisticsQueryCondition statsQuery = new StatisticsQueryCondition(geneRestrictionSet);
statsQuery.and(getStatisticsOrQuery(Collections.singletonList(attribute)));
Multiset<Integer> scores = StatisticsQueryUtils.getExperimentCounts(statsQuery, statisticsStorage, null);
// Cache geneRestrictionSet's scores for efvOrEfo - this cache will be re-used in heatmaps for rows other than the first one
if (scoresCacheForStatType != null) {
scoresCacheForStatType.put(attribute.getValue(), scores);
}
Integer geneIndex = statisticsStorage.getIndexForGeneId(geneId);
if (scores != null) {
long time = System.currentTimeMillis();
int expCountForGene = scores.count(geneIndex);
if (expCountForGene > 0) {
log.debug(attribute.getStatType() + " " + attribute.getValue() + " expCountForGene: " + geneId + " (" + geneIndex + ") = " + expCountForGene + " got in: " + (System.currentTimeMillis() - time) + " ms");
}
return expCountForGene;
}
return 0;
}
/**
* @param orAttributes
* @return StatisticsQueryOrConditions, including children of all efo's in orAttributes
*/
public StatisticsQueryOrConditions<StatisticsQueryCondition> getStatisticsOrQuery(List<Attribute> orAttributes) {
List<Attribute> efoPlusChildren = includeEfoChildren(orAttributes);
return StatisticsQueryUtils.getStatisticsOrQuery(efoPlusChildren, statisticsStorage);
}
/**
* @param orAttributes
* @return List containing all (afv and efo) attributes in orAttributes, plus the children of all efo's in orAttributes
*/
private List<Attribute> includeEfoChildren(List<Attribute> orAttributes) {
// LinkedHashSet for maintaining order of entry - order of processing attributes may be important
// in multi-Attribute queries for sorted lists of experiments for the gene page
Set<Attribute> attrsPlusChildren = new LinkedHashSet<Attribute>();
for (Attribute attr : orAttributes)
attrsPlusChildren.addAll(attr.getAttributeAndChildren(efo));
return new ArrayList<Attribute>(attrsPlusChildren);
}
public Integer getIndexForGene(Long geneId) {
return statisticsStorage.getIndexForGeneId(geneId);
}
/**
* @param attribute
* @return Index of Attribute within bit index
*/
public Integer getIndexForAttribute(EfvAttribute attribute) {
return statisticsStorage.getIndexForAttribute(attribute);
}
/**
* @param attributeIndex
* @return Attribute corresponding to attributeIndex bit index
*/
public EfvAttribute getAttributeForIndex(Integer attributeIndex) {
return statisticsStorage.getAttributeForIndex(attributeIndex);
}
/**
* http://stackoverflow.com/questions/3029151/find-top-n-elements-in-a-multiset-from-google-collections
*
* @param multiset
* @param <T>
* @return
*/
private static <T> ImmutableList<Multiset.Entry<T>> sortedByCount(Multiset<T> multiset) {
Ordering<Multiset.Entry<T>> countComp = new Ordering<Multiset.Entry<T>>() {
public int compare(Multiset.Entry<T> e1, Multiset.Entry<T> e2) {
return e2.getCount() - e1.getCount();
}
};
return countComp.immutableSortedCopy(multiset.entrySet());
}
/**
* http://stackoverflow.com/questions/3029151/find-top-n-elements-in-a-multiset-from-google-collections
*
* @param multiset
* @param min
* @param max
* @param <T>
* @return
*/
private static <T> ImmutableList<Multiset.Entry<T>> getEntriesBetweenMinMaxFromListSortedByCount(Multiset<T> multiset,
int min, int max) {
ImmutableList<Multiset.Entry<T>> sortedByCount = sortedByCount(multiset);
if (min < 0)
min = 0;
if (sortedByCount.size() > max) {
return sortedByCount.subList(min, max);
}
return sortedByCount.subList(min, sortedByCount.size());
}
/**
* @param statsQuery
* @param minPos
* @param rows
* @param sortedGenesChunk - a chunk of the overall sorted (by experiment counts - in desc order) list of genes,
* starting from 'minPos' and containing maximums 'rows' genes
* @return The overall number of genes for which counts exist in statsQuery
*/
public Integer getSortedGenes(final StatisticsQueryCondition statsQuery, final int minPos, final int rows, List<Long> sortedGenesChunk) {
long timeStart = System.currentTimeMillis();
Multiset<Integer> countsForConditions = StatisticsQueryUtils.getExperimentCounts(statsQuery, statisticsStorage, null);
log.debug("getSortedGenes() bit index query: " + statsQuery.prettyPrint());
log.debug("getSortedGenes() query returned " + countsForConditions.elementSet().size() +
" genes with counts present in : " + (System.currentTimeMillis() - timeStart) + " ms");
List<Multiset.Entry<Integer>> sortedCounts = getEntriesBetweenMinMaxFromListSortedByCount(countsForConditions, minPos, minPos + rows);
for (Multiset.Entry<Integer> entry : sortedCounts) {
Long geneId = statisticsStorage.getGeneIdForIndex(entry.getElement());
if (geneId != null) {
sortedGenesChunk.add(geneId);
} else {
log.error("Failed to retrieve gene id for index: " + entry.getElement());
}
}
return countsForConditions.elementSet().size();
}
/**
* @param efoTerm
* @return Set of EfvAttributes corresponding to efoTerm. Note that efo's map to ef-efv-experiment triples. However, this method
* is used in AtlasStructuredQueryService for populating list view, which for efo queries shows ef-efvs those efos map to and
* _all_ experiments in which these ef-efvs have expressions. In other words, we don't restrict experiments shown in the list view
* to just those in query efo->ef-efv-experiment mapping.
*/
public Set<EfvAttribute> getAttributesForEfo(String efoTerm) {
Set<EfvAttribute> attrsForEfo = new HashSet<EfvAttribute>();
Map<Experiment, Set<EfvAttribute>> expToAttrsForEfo = statisticsStorage.getMappingsForEfo(efoTerm);
for (Collection<EfvAttribute> expToAttrIndexes : expToAttrsForEfo.values()) {
attrsForEfo.addAll(expToAttrIndexes);
}
return attrsForEfo;
}
/**
* @param geneId Gene of interest
* @param attribute Attribute
* @param fromRow Used for paginating of experiment plots on gene page
* @param toRow ditto
* @return List of Experiments sorted by pVal/tStat ranks from best to worst
*/
public List<Experiment> getExperimentsSortedByPvalueTRank(
final Long geneId,
final Attribute attribute,
int fromRow,
int toRow) {
List<Attribute> attrs;
if (attribute.getValue() == null) { // Empty attribute
List<String> efs = getScoringEfsForGene(geneId, StatisticsType.UP_DOWN, null);
attrs = new ArrayList<Attribute>();
for (String expFactor : efs) {
EfvAttribute attr = new EfvAttribute(expFactor, attribute.getStatType());
attrs.add(attr);
}
} else {
attrs = Collections.singletonList(attribute);
}
// Assemble stats query that will be used to extract sorted experiments
StatisticsQueryCondition statsQuery = new StatisticsQueryCondition(Collections.singleton(geneId));
statsQuery.and(getStatisticsOrQuery(attrs));
// retrieve experiments sorted by pValue/tRank for statsQuery
List<Experiment> bestExperiments = new ArrayList<Experiment>();
StatisticsQueryUtils.getBestExperiments(statsQuery, statisticsStorage, bestExperiments);
// Sort bestExperiments by best pVal/tStat ranks first
Collections.sort(bestExperiments, new Comparator<Experiment>() {
public int compare(Experiment e1, Experiment e2) {
return e1.getpValTStatRank().compareTo(e2.getpValTStatRank());
}
});
// Extract the correct chunk (Note that if toRow == fromRow == -1, the whole of bestExperiments is returned)
int maxSize = bestExperiments.size();
if (fromRow == -1)
fromRow = 0;
- if (toRow == -1 || toRow >= maxSize)
+ if (toRow == -1 || toRow > maxSize)
toRow = maxSize;
- else
- toRow++; // Increment because the sublist is exclusive of the upper bound
List<Experiment> exps = bestExperiments.subList(fromRow, toRow);
log.debug("Sorted experiments: ");
for (Experiment exp : exps) {
log.debug(exp.getAccession() + ": pval=" + exp.getpValTStatRank().getPValue() +
"; tStat rank: " + exp.getpValTStatRank().getTStatRank() + "; highest ranking ef: " + exp.getHighestRankAttribute());
}
return exps;
}
/**
* @param geneId
* @param statType
* @param ef
* @return list all efs for which geneId has statType expression in at least one experiment
*/
public List<String> getScoringEfsForGene(final Long geneId,
final StatisticsType statType,
@Nullable final String ef) {
long timeStart = System.currentTimeMillis();
List<String> scoringEfs = new ArrayList<String>();
Integer geneIdx = statisticsStorage.getIndexForGeneId(geneId);
if (geneIdx != null) {
Set<Integer> scoringEfIndexes = statisticsStorage.getScoringEfAttributesForGene(geneIdx, statType);
for (Integer attrIdx : scoringEfIndexes) {
EfvAttribute attr = statisticsStorage.getAttributeForIndex(attrIdx);
if (attr != null && (ef == null || "".equals(ef) || ef.equals(attr.getEf()))) {
scoringEfs.add(attr.getEf());
}
}
}
log.debug("getScoringEfsForGene() returned " + scoringEfs.size() + " efs for geneId: " + geneId + " in: " + (System.currentTimeMillis() - timeStart) + " ms");
return scoringEfs;
}
/**
* @param geneId
* @param statType
* @return list all efs for which geneId has statType expression in at least one experiment
*/
public List<EfvAttribute> getScoringEfvsForGene(final Long geneId,
final StatisticsType statType) {
long timeStart = System.currentTimeMillis();
List<EfvAttribute> scoringEfvs = new ArrayList<EfvAttribute>();
Integer geneIdx = statisticsStorage.getIndexForGeneId(geneId);
if (geneIdx != null) {
Set<Integer> scoringEfvIndexes = statisticsStorage.getScoringEfvAttributesForGene(geneIdx, statType);
for (Integer attrIdx : scoringEfvIndexes) {
EfvAttribute attr = statisticsStorage.getAttributeForIndex(attrIdx);
if (attr.getEfv() != null && !attr.getEfv().isEmpty()) {
attr.setStatType(statType);
scoringEfvs.add(attr);
}
}
}
log.debug("getScoringEfsForGene() returned " + scoringEfvs.size() + " efs for geneId: " + geneId + " in: " + (System.currentTimeMillis() - timeStart) + " ms");
return scoringEfvs;
}
/**
* @param ef
* @param geneId
* @param statType
* @return unsorted list of experiments for which geneId has statType expression for ef attr
*/
public List<Experiment> getExperimentsForGeneAndEf(Long geneId, @Nullable String ef, StatisticsType statType) {
List<Experiment> exps = new ArrayList<Experiment>();
Integer geneIdx = statisticsStorage.getIndexForGeneId(geneId);
Integer attrIdx = null;
// Note that if ef == null, this method returns list of experiments across all efs for which this gene has up/down exp counts
if (ef != null)
attrIdx = statisticsStorage.getIndexForAttribute(new EfvAttribute(ef, null));
if (geneIdx != null) {
Set<Integer> expIdxs = statisticsStorage.getExperimentsForGeneAndAttribute(attrIdx, geneIdx, statType);
for (Integer expIdx : expIdxs) {
Experiment exp = statisticsStorage.getExperimentForIndex(expIdx);
if (exp != null) {
exps.add(exp);
}
}
}
return exps;
}
/**
* @param geneIds
* @param statType
* @param autoFactors set of factors of interest
* @return Serted set of non-zero experiment counts (for at least one of geneIds and statType) per efv (note: not efo) attribute
*/
public List<Multiset.Entry<Integer>> getScoringAttributesForGenes(Set<Long> geneIds, StatisticsType statType, Collection<String> autoFactors) {
long timeStart = System.currentTimeMillis();
Multiset<Integer> attrCounts = HashMultiset.create();
Set<EfvAttribute> allEfvAttributesForStat = statisticsStorage.getAllAttributes(statType);
for (EfvAttribute attr : allEfvAttributesForStat) {
if ((autoFactors != null && !autoFactors.contains(attr.getEf())) || attr.getEfv() == null) {
continue; // skip attribute if its factor is not of interest or it's an ef-only attribute
}
Integer attrIndex = statisticsStorage.getIndexForAttribute(attr);
attr.setStatType(statType);
StatisticsQueryCondition statsQuery = new StatisticsQueryCondition(geneIds);
statsQuery.and(getStatisticsOrQuery(Collections.<Attribute>singletonList(attr)));
Set<Experiment> scoringExps = new HashSet<Experiment>();
StatisticsQueryUtils.getExperimentCounts(statsQuery, statisticsStorage, scoringExps);
if (scoringExps.size() > 0) { // at least one gene in geneIds had an experiment count > 0 for attr
attrCounts.add(attrIndex, scoringExps.size());
for (Experiment exp : scoringExps) {
String efoTerm = statisticsStorage.getEfoTerm(attr, exp);
if (efoTerm != null) {
log.debug("Skipping efo: " + efoTerm + " for attr: " + attr + " and exp: " + exp);
}
}
}
}
List<Multiset.Entry<Integer>> sortedAttrCounts = getEntriesBetweenMinMaxFromListSortedByCount(attrCounts, 0, attrCounts.entrySet().size());
log.debug("Retrieved " + sortedAttrCounts.size() + " sorted scoring attributes for statType: " + statType + " and gene ids: (" + geneIds + ") in " + (System.currentTimeMillis() - timeStart) + "ms");
return sortedAttrCounts;
}
/**
* @param geneId
* @param attribute
* @return Set of Experiments in which geneId-ef-efv have statType expression
*/
public Set<Experiment> getScoringExperimentsForGeneAndAttribute(Long geneId, @Nonnull Attribute attribute) {
StatisticsQueryCondition statsQuery = new StatisticsQueryCondition(Collections.singleton(geneId));
statsQuery.and(getStatisticsOrQuery(Collections.<Attribute>singletonList(attribute)));
Set<Experiment> scoringExps = new HashSet<Experiment>();
StatisticsQueryUtils.getExperimentCounts(statsQuery, statisticsStorage, scoringExps);
return scoringExps;
}
/**
* @param attribute
* @param allExpsToAttrs Map: Experiment -> Set<Attribute> to which mappings for an Attribute are to be added.
*/
public void getEfvExperimentMappings(
final Attribute attribute,
Map<Experiment, Set<EfvAttribute>> allExpsToAttrs) {
attribute.getEfvExperimentMappings(statisticsStorage, allExpsToAttrs);
}
/**
* @param statType
* @return Collection of unique experiments with expressions for statType
*/
public Collection<Experiment> getScoringExperiments(StatisticsType statType) {
return statisticsStorage.getScoringExperiments(statType);
}
/**
* @param attribute
* @param statType
* @return the amount of genes with expression statType for efv attribute
*/
public int getGeneCountForEfvAttribute(EfvAttribute attribute, StatisticsType statType) {
return statisticsStorage.getGeneCountForAttribute(attribute, statType);
}
/**
*
* @param attribute
* @param statType
* @return the amount of genes with expression statType for efo attribute
*/
public int getGeneCountForEfoAttribute(Attribute attribute, StatisticsType statType) {
StatisticsQueryCondition statsQuery = new StatisticsQueryCondition(statType);
statsQuery.and(getStatisticsOrQuery(Collections.singletonList(attribute)));
return StatisticsQueryUtils.getExperimentCounts(statsQuery, statisticsStorage, null).entrySet().size();
}
}
| false | true | public List<Experiment> getExperimentsSortedByPvalueTRank(
final Long geneId,
final Attribute attribute,
int fromRow,
int toRow) {
List<Attribute> attrs;
if (attribute.getValue() == null) { // Empty attribute
List<String> efs = getScoringEfsForGene(geneId, StatisticsType.UP_DOWN, null);
attrs = new ArrayList<Attribute>();
for (String expFactor : efs) {
EfvAttribute attr = new EfvAttribute(expFactor, attribute.getStatType());
attrs.add(attr);
}
} else {
attrs = Collections.singletonList(attribute);
}
// Assemble stats query that will be used to extract sorted experiments
StatisticsQueryCondition statsQuery = new StatisticsQueryCondition(Collections.singleton(geneId));
statsQuery.and(getStatisticsOrQuery(attrs));
// retrieve experiments sorted by pValue/tRank for statsQuery
List<Experiment> bestExperiments = new ArrayList<Experiment>();
StatisticsQueryUtils.getBestExperiments(statsQuery, statisticsStorage, bestExperiments);
// Sort bestExperiments by best pVal/tStat ranks first
Collections.sort(bestExperiments, new Comparator<Experiment>() {
public int compare(Experiment e1, Experiment e2) {
return e1.getpValTStatRank().compareTo(e2.getpValTStatRank());
}
});
// Extract the correct chunk (Note that if toRow == fromRow == -1, the whole of bestExperiments is returned)
int maxSize = bestExperiments.size();
if (fromRow == -1)
fromRow = 0;
if (toRow == -1 || toRow >= maxSize)
toRow = maxSize;
else
toRow++; // Increment because the sublist is exclusive of the upper bound
List<Experiment> exps = bestExperiments.subList(fromRow, toRow);
log.debug("Sorted experiments: ");
for (Experiment exp : exps) {
log.debug(exp.getAccession() + ": pval=" + exp.getpValTStatRank().getPValue() +
"; tStat rank: " + exp.getpValTStatRank().getTStatRank() + "; highest ranking ef: " + exp.getHighestRankAttribute());
}
return exps;
}
| public List<Experiment> getExperimentsSortedByPvalueTRank(
final Long geneId,
final Attribute attribute,
int fromRow,
int toRow) {
List<Attribute> attrs;
if (attribute.getValue() == null) { // Empty attribute
List<String> efs = getScoringEfsForGene(geneId, StatisticsType.UP_DOWN, null);
attrs = new ArrayList<Attribute>();
for (String expFactor : efs) {
EfvAttribute attr = new EfvAttribute(expFactor, attribute.getStatType());
attrs.add(attr);
}
} else {
attrs = Collections.singletonList(attribute);
}
// Assemble stats query that will be used to extract sorted experiments
StatisticsQueryCondition statsQuery = new StatisticsQueryCondition(Collections.singleton(geneId));
statsQuery.and(getStatisticsOrQuery(attrs));
// retrieve experiments sorted by pValue/tRank for statsQuery
List<Experiment> bestExperiments = new ArrayList<Experiment>();
StatisticsQueryUtils.getBestExperiments(statsQuery, statisticsStorage, bestExperiments);
// Sort bestExperiments by best pVal/tStat ranks first
Collections.sort(bestExperiments, new Comparator<Experiment>() {
public int compare(Experiment e1, Experiment e2) {
return e1.getpValTStatRank().compareTo(e2.getpValTStatRank());
}
});
// Extract the correct chunk (Note that if toRow == fromRow == -1, the whole of bestExperiments is returned)
int maxSize = bestExperiments.size();
if (fromRow == -1)
fromRow = 0;
if (toRow == -1 || toRow > maxSize)
toRow = maxSize;
List<Experiment> exps = bestExperiments.subList(fromRow, toRow);
log.debug("Sorted experiments: ");
for (Experiment exp : exps) {
log.debug(exp.getAccession() + ": pval=" + exp.getpValTStatRank().getPValue() +
"; tStat rank: " + exp.getpValTStatRank().getTStatRank() + "; highest ranking ef: " + exp.getHighestRankAttribute());
}
return exps;
}
|
diff --git a/src/main/java/org/otherobjects/cms/tools/FormatTool.java b/src/main/java/org/otherobjects/cms/tools/FormatTool.java
index e36e533c..a7bd63c9 100644
--- a/src/main/java/org/otherobjects/cms/tools/FormatTool.java
+++ b/src/main/java/org/otherobjects/cms/tools/FormatTool.java
@@ -1,157 +1,157 @@
package org.otherobjects.cms.tools;
import java.io.StringWriter;
import java.text.NumberFormat;
import java.util.Locale;
import javax.annotation.Resource;
import net.java.textilej.parser.MarkupParser;
import net.java.textilej.parser.builder.HtmlDocumentBuilder;
import net.java.textilej.parser.markup.textile.TextileDialect;
import org.otherobjects.cms.config.OtherObjectsConfigurator;
import org.otherobjects.cms.views.Tool;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Component;
/**
* Tool to be used from templates to aid in generating formatted text.
* @author joerg
*
*/
@Component
@Tool
public class FormatTool
{
@Resource
private MessageSource messageSource;
@Resource
private OtherObjectsConfigurator otherObjectsConfigurator;
@Resource
private InlineFormatter inlineFormatter;
public FormatTool()
{
}
public String getProperty(String name)
{
return otherObjectsConfigurator.getProperty(name);
}
/**
* Formats textile string into HTML. HTML special chars in the textileSource will get escaped (notably the less than and greater than signs)
* @param textileSource
* @return
*/
public String formatTextile(String textileSource)
{
// Remove double line breaks
String text = textileSource;//textileSource.replaceAll("/\n\n/", "\n");
// Recode headings
text = text.replaceAll("\\\\n", "\n");
- text = text.replaceAll("(?m)^h3. ", "h4. ");
- text = text.replaceAll("(?m)^h2. ", "h3. ");
- text = text.replaceAll("(?m)^h1. ", "h2. ");
+ text = text.replaceAll("(?m)^h3", "h4");
+ text = text.replaceAll("(?m)^h2", "h3");
+ text = text.replaceAll("(?m)^h1", "h2");
// Recode code blocks
// text = text.replaceAll("\\[code\\]", "<pre>\n<code>\n");
// text = text.replaceAll("\\[/code\\]", "\n</code>\n</pre>");
// Recode links
// text = text.replaceAll("\\[LINK:([^|]*)\\|CAPTION:([^\\]]*)\\]", "\"$2\":$1");
// text = text.replaceAll("(?m)\\[LINK:([^]]*)\\]", "\"$1\":$1");
// TODO This needs to be optimesd
// TODO Add support for additional markups
MarkupParser parser = new MarkupParser(new TextileDialect());
StringWriter out = new StringWriter();
HtmlDocumentBuilder builder = new HtmlDocumentBuilder(out);
builder.setEmitAsDocument(false);
parser.setBuilder(builder);
parser.parse(text);
parser.setBuilder(null);
String html = out.toString();
if (inlineFormatter != null)
return inlineFormatter.format(html);
else
return html;
}
/**
* Formats file size into huma readable form.
*
* @param size in bytes
* @return formatted string
*/
public static String formatFileSize(Long size)
{
NumberFormat f = NumberFormat.getInstance();
f.setMaximumFractionDigits(1);
f.setMinimumFractionDigits(1);
double s = (double) size / (double) 1024;
if (s < 1028 * 0.8)
{
return f.format(s) + " KB";
}
s /= 1024;
if (s < 1024 * 0.8)
{
return f.format(s) + " MB";
}
s /= 1024;
return f.format(s) + " GB";
}
/**
* Parses a string and looks up messages if appropriate. Useful for form labels that may or may note use
* message codes. If the string appears to be a message code then this is looked up otherwise the string
* is returned unaltered.
*
* TODO Change format.
*
* @param textileSource
* @return
*/
public String getMessage(String message)
{
if (message.startsWith("$"))
{
// Message
// FIXME Get locale from somewhere better
return messageSource.getMessage(message.substring(2, message.length() - 1), null, Locale.ENGLISH);
}
if (message.contains(".") && !message.endsWith(".") && message.matches("[a-z0-9\\.]*"))
{
// Message
// FIXME proper regexp here
return messageSource.getMessage(message, null, Locale.ENGLISH);
}
else
return message;
}
protected void setMessageSource(MessageSource messageSource)
{
this.messageSource = messageSource;
}
protected void setOtherObjectsConfigurator(OtherObjectsConfigurator otherObjectsConfigurator)
{
this.otherObjectsConfigurator = otherObjectsConfigurator;
}
protected void setInlineFormatter(InlineFormatter inlineFormatter)
{
this.inlineFormatter = inlineFormatter;
}
}
| true | true | public String formatTextile(String textileSource)
{
// Remove double line breaks
String text = textileSource;//textileSource.replaceAll("/\n\n/", "\n");
// Recode headings
text = text.replaceAll("\\\\n", "\n");
text = text.replaceAll("(?m)^h3. ", "h4. ");
text = text.replaceAll("(?m)^h2. ", "h3. ");
text = text.replaceAll("(?m)^h1. ", "h2. ");
// Recode code blocks
// text = text.replaceAll("\\[code\\]", "<pre>\n<code>\n");
// text = text.replaceAll("\\[/code\\]", "\n</code>\n</pre>");
// Recode links
// text = text.replaceAll("\\[LINK:([^|]*)\\|CAPTION:([^\\]]*)\\]", "\"$2\":$1");
// text = text.replaceAll("(?m)\\[LINK:([^]]*)\\]", "\"$1\":$1");
// TODO This needs to be optimesd
// TODO Add support for additional markups
MarkupParser parser = new MarkupParser(new TextileDialect());
StringWriter out = new StringWriter();
HtmlDocumentBuilder builder = new HtmlDocumentBuilder(out);
builder.setEmitAsDocument(false);
parser.setBuilder(builder);
parser.parse(text);
parser.setBuilder(null);
String html = out.toString();
if (inlineFormatter != null)
return inlineFormatter.format(html);
else
return html;
}
| public String formatTextile(String textileSource)
{
// Remove double line breaks
String text = textileSource;//textileSource.replaceAll("/\n\n/", "\n");
// Recode headings
text = text.replaceAll("\\\\n", "\n");
text = text.replaceAll("(?m)^h3", "h4");
text = text.replaceAll("(?m)^h2", "h3");
text = text.replaceAll("(?m)^h1", "h2");
// Recode code blocks
// text = text.replaceAll("\\[code\\]", "<pre>\n<code>\n");
// text = text.replaceAll("\\[/code\\]", "\n</code>\n</pre>");
// Recode links
// text = text.replaceAll("\\[LINK:([^|]*)\\|CAPTION:([^\\]]*)\\]", "\"$2\":$1");
// text = text.replaceAll("(?m)\\[LINK:([^]]*)\\]", "\"$1\":$1");
// TODO This needs to be optimesd
// TODO Add support for additional markups
MarkupParser parser = new MarkupParser(new TextileDialect());
StringWriter out = new StringWriter();
HtmlDocumentBuilder builder = new HtmlDocumentBuilder(out);
builder.setEmitAsDocument(false);
parser.setBuilder(builder);
parser.parse(text);
parser.setBuilder(null);
String html = out.toString();
if (inlineFormatter != null)
return inlineFormatter.format(html);
else
return html;
}
|
diff --git a/src/main/java/pl/agh/enrollme/controller/AntTermFileController.java b/src/main/java/pl/agh/enrollme/controller/AntTermFileController.java
index ee9f424..caf7d71 100644
--- a/src/main/java/pl/agh/enrollme/controller/AntTermFileController.java
+++ b/src/main/java/pl/agh/enrollme/controller/AntTermFileController.java
@@ -1,136 +1,140 @@
package pl.agh.enrollme.controller;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import pl.agh.enrollme.model.Enroll;
import pl.agh.enrollme.model.Subject;
import pl.agh.enrollme.model.Term;
import pl.agh.enrollme.repository.ISubjectDAO;
import pl.agh.enrollme.repository.ITermDAO;
import java.io.*;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
/**
* Controller provides implementation for generating files with term for the ants aglorithm
* @author Michal Partyka
*/
@Controller
public class AntTermFileController {
private static final File termsFile = new File("/tmp/termsFile.txt");
private static final Logger LOGGER = LoggerFactory.getLogger(AntTermFileController.class.getName());
private StreamedContent streamedTerms;
@Autowired
ITermDAO termDAO;
@Autowired
ISubjectDAO subjectDAO;
public void generateTermsFile(Enroll enrollment) {
LOGGER.debug("I am in generate Terms...");
try (BufferedWriter output = new BufferedWriter( new FileWriter(termsFile))) {
output.write("\n" + basicTermsInformation(subjectDAO.getSubjectsByEnrollment(enrollment)));
} catch (IOException e) {
LOGGER.error("Some IO Problems: ", e);
}
try {
streamedTerms = new DefaultStreamedContent( new FileInputStream(termsFile));
} catch (FileNotFoundException e) {
LOGGER.debug("there is no given file :(: " + termsFile.getName(), e);
}
}
private String basicTermsInformation(List<Subject> subjects) {
StringBuilder singleTermDetails = new StringBuilder();
StringBuilder collisions = new StringBuilder();
for (Subject subject: subjects) {
//make subjectID a header: (ant format)
singleTermDetails.append("[").append(subject.getSubjectID()).append("]\n");
List<Term> terms = termDAO.getTermsBySubject(subject);
for (Term term: terms) {
+ if (term.getCertain()) {
+ //skip certain terms:
+ continue;
+ }
//Iterate through subjects and for every subject put line into file:
//(Clean foreach costs some performance issue :-)
singleTermDetails.append(createLineWithSeparator(":", term.getTermPerSubjectID(),
term.getCapacity(), getAntFormatOfWeekDay(term.getStartTime()),
getAntFormatOfDate(term.getStartTime()), getAntFormatOfDate(term.getEndTime())));
singleTermDetails.append("\n");
for (Term termCollision: terms) {
- //captured two times situation when term is in collision with another term - ant format require it
+ //captured two times situation when term is in collision with another term - ant format require it
collisions.append(checkForCollision(term, termCollision));
}
}
}
return singleTermDetails.toString() + "[kolizje]\n" + collisions.toString();
}
private String checkForCollision(Term term, Term termCollision) {
if (term.equals(termCollision)) {
return "";
}
Calendar firstTermStart = Calendar.getInstance();
Calendar firstTermEnd = Calendar.getInstance();
Calendar secondTermStart = Calendar.getInstance();
Calendar secondTermEnd = Calendar.getInstance();
firstTermStart.setTime(term.getStartTime());
firstTermEnd.setTime(term.getEndTime());
secondTermStart.setTime(termCollision.getStartTime());
secondTermEnd.setTime(termCollision.getEndTime());
if ( firstTermEnd.after(secondTermStart) && firstTermStart.before(secondTermEnd)) {
//print in the ant format:
return term.getSubject().getSubjectID().toString() + "," +
term.getTermPerSubjectID() + ";" + termCollision.getSubject().getSubjectID() +
"," + termCollision.getTermPerSubjectID() + "\n";
}
return "";
}
private String createLineWithSeparator(String delimiter, Object... objects) {
StringBuilder stringBuilder = new StringBuilder();
int i=0; //number of objects already printed
for (Object part: objects) {
stringBuilder.append(part.toString());
if (++i < objects.length) { // no the last one? add delimiter:
stringBuilder.append(delimiter);
}
}
return stringBuilder .toString();
}
private Integer getAntFormatOfDate(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int hourDiff = hour - 7;
int minute = calendar.get(Calendar.MINUTE);
//Every hour 4 terms, every 15minutes 1 term, counting from 0
return hourDiff*4 + minute/15;
}
private Integer getAntFormatOfWeekDay(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.DAY_OF_WEEK)-2;
}
public StreamedContent getStreamedTerms() {
return streamedTerms;
}
}
| false | true | private String basicTermsInformation(List<Subject> subjects) {
StringBuilder singleTermDetails = new StringBuilder();
StringBuilder collisions = new StringBuilder();
for (Subject subject: subjects) {
//make subjectID a header: (ant format)
singleTermDetails.append("[").append(subject.getSubjectID()).append("]\n");
List<Term> terms = termDAO.getTermsBySubject(subject);
for (Term term: terms) {
//Iterate through subjects and for every subject put line into file:
//(Clean foreach costs some performance issue :-)
singleTermDetails.append(createLineWithSeparator(":", term.getTermPerSubjectID(),
term.getCapacity(), getAntFormatOfWeekDay(term.getStartTime()),
getAntFormatOfDate(term.getStartTime()), getAntFormatOfDate(term.getEndTime())));
singleTermDetails.append("\n");
for (Term termCollision: terms) {
//captured two times situation when term is in collision with another term - ant format require it
collisions.append(checkForCollision(term, termCollision));
}
}
}
return singleTermDetails.toString() + "[kolizje]\n" + collisions.toString();
}
| private String basicTermsInformation(List<Subject> subjects) {
StringBuilder singleTermDetails = new StringBuilder();
StringBuilder collisions = new StringBuilder();
for (Subject subject: subjects) {
//make subjectID a header: (ant format)
singleTermDetails.append("[").append(subject.getSubjectID()).append("]\n");
List<Term> terms = termDAO.getTermsBySubject(subject);
for (Term term: terms) {
if (term.getCertain()) {
//skip certain terms:
continue;
}
//Iterate through subjects and for every subject put line into file:
//(Clean foreach costs some performance issue :-)
singleTermDetails.append(createLineWithSeparator(":", term.getTermPerSubjectID(),
term.getCapacity(), getAntFormatOfWeekDay(term.getStartTime()),
getAntFormatOfDate(term.getStartTime()), getAntFormatOfDate(term.getEndTime())));
singleTermDetails.append("\n");
for (Term termCollision: terms) {
//captured two times situation when term is in collision with another term - ant format require it
collisions.append(checkForCollision(term, termCollision));
}
}
}
return singleTermDetails.toString() + "[kolizje]\n" + collisions.toString();
}
|
diff --git a/de.walware.statet.r.core/src/de/walware/statet/r/internal/core/pkgmanager/RPkgManager.java b/de.walware.statet.r.core/src/de/walware/statet/r/internal/core/pkgmanager/RPkgManager.java
index e97f0073..26d09d00 100644
--- a/de.walware.statet.r.core/src/de/walware/statet/r/internal/core/pkgmanager/RPkgManager.java
+++ b/de.walware.statet.r.core/src/de/walware/statet/r/internal/core/pkgmanager/RPkgManager.java
@@ -1,1268 +1,1280 @@
/*=============================================================================#
# Copyright (c) 2012-2015 Stephan Wahlbrink (WalWare.de) 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:
# Stephan Wahlbrink - initial API and implementation
#=============================================================================*/
package de.walware.statet.r.internal.core.pkgmanager;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.eclipse.core.filesystem.EFS;
import org.eclipse.core.filesystem.IFileStore;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
import org.eclipse.core.runtime.preferences.IScopeContext;
import org.eclipse.core.runtime.preferences.InstanceScope;
import org.eclipse.osgi.util.NLS;
import org.osgi.service.prefs.BackingStoreException;
import de.walware.ecommons.FastList;
import de.walware.ecommons.collections.ConstArrayList;
import de.walware.ecommons.preferences.AbstractPreferencesModelObject;
import de.walware.ecommons.preferences.IPreferenceAccess;
import de.walware.ecommons.preferences.Preference.StringPref2;
import de.walware.ecommons.preferences.PreferencesUtil;
import de.walware.ecommons.preferences.SettingsChangeNotifier;
import de.walware.ecommons.ts.ITool;
import de.walware.ecommons.ts.IToolService;
import de.walware.rj.data.RCharacterStore;
import de.walware.rj.data.RDataFrame;
import de.walware.rj.data.RDataUtil;
import de.walware.rj.data.RLogicalStore;
import de.walware.rj.data.RNumericStore;
import de.walware.rj.data.RObject;
import de.walware.rj.data.RStore;
import de.walware.rj.data.RVector;
import de.walware.rj.data.UnexpectedRDataException;
import de.walware.rj.data.defaultImpl.RCharacterDataImpl;
import de.walware.rj.data.defaultImpl.RVectorImpl;
import de.walware.rj.eclient.AbstractRToolRunnable;
import de.walware.rj.eclient.IRToolService;
import de.walware.rj.renv.IRPkg;
import de.walware.rj.renv.RNumVersion;
import de.walware.rj.renv.RPkgType;
import de.walware.rj.server.srvext.ServerUtil;
import de.walware.rj.services.FunctionCall;
import de.walware.rj.services.RPlatform;
import de.walware.rj.services.RService;
import de.walware.statet.r.core.RCore;
import de.walware.statet.r.core.pkgmanager.IRLibPaths;
import de.walware.statet.r.core.pkgmanager.IRPkgData;
import de.walware.statet.r.core.pkgmanager.IRPkgInfoAndData;
import de.walware.statet.r.core.pkgmanager.IRPkgManager;
import de.walware.statet.r.core.pkgmanager.IRPkgSet;
import de.walware.statet.r.core.pkgmanager.IRView;
import de.walware.statet.r.core.pkgmanager.ISelectedRepos;
import de.walware.statet.r.core.pkgmanager.RPkgAction;
import de.walware.statet.r.core.pkgmanager.RPkgUtil;
import de.walware.statet.r.core.pkgmanager.RRepo;
import de.walware.statet.r.core.pkgmanager.SelectedRepos;
import de.walware.statet.r.core.renv.IREnv;
import de.walware.statet.r.core.renv.IREnvConfiguration;
import de.walware.statet.r.core.tool.AbstractStatetRRunnable;
import de.walware.statet.r.core.tool.IRConsoleService;
import de.walware.statet.r.internal.core.RCorePlugin;
import de.walware.statet.r.internal.core.renv.REnvConfiguration;
public class RPkgManager implements IRPkgManager.Ext, SettingsChangeNotifier.ManageListener {
private final static int REQUIRE_CRAN = 0x10000000;
private final static int REQUIRE_BIOC = 0x20000000;
private final static int REQUIRE_REPOS = 0x80000000;
private final static int REQUIRE_REPO_PKGS = 0x01000000;
private final static int REQUIRE_INST_PKGS = 0x08000000;
private final static RRepoPref LAST_CRAN_PREF = new RRepoPref(PREF_QUALIFIER, "LastCRAN.repo"); //$NON-NLS-1$
private final static RRepoPref LAST_BIOC_PREF = new RRepoPref(PREF_QUALIFIER, "LastBioC.repo"); //$NON-NLS-1$
private final static int MIRROR_CHECK = 1000 * 60 * 60 * 6;
private final static int PKG_CHECK = 1000 * 60 * 60 * 3;
private final IREnv fREnv;
private RPlatform fRPlatform;
private final IFileStore fREnvDirectory;
private boolean fFirstTime;
private String fBioCVersion;
private final StringPref2 fBioCVersionPref;
private List<RRepo> fCustomRepos;
private final List<RRepo> fAddRepos;
private List<RRepo> fRRepos;
private List<RRepo> fAllRepos;
private List<RRepo> fSelectedReposInR;
private final RRepoListPref fSelectedReposPref;
private List<RRepo> fCustomCRAN;
private List<RRepo> fRCRAN;
private RRepo fRCRANByCountry;
private List<RRepo> fAllCRAN;
private String fSelectedCRANInR;
private final RRepoPref fSelectedCRANPref;
private List<RRepo> fCustomBioC;
private List<RRepo> fRBioC;
private List<RRepo> fAllBioC;
private String fSelectedBioCInR;
private final RRepoPref fSelectedBioCPref;
private long fMirrorsStamp;
private SelectedRepos fSelectedRepos;
private RVector<RNumericStore> fLibs = null;
private REnvLibGroups fRLibGroups;
private RLibPaths fRLibPaths;
private RPkgSet fPkgsLight;
private FullRPkgSet fPkgsExt;
private long fPkgsStamp;
final RPkgScanner fPkgScanner = new RPkgScanner();
private volatile int fRequireLoad;
private volatile int fRequireConfirm;
private final FastList<Listener> fListeners = new FastList<>(Listener.class);
private final ReentrantReadWriteLock fLock = new ReentrantReadWriteLock();
private List<RView> fRViews;
private RNumVersion fRViewsVersion;
// private List<RView> fBioCViews;
// private String fBioCViewsVersion;
// private long fBioCViewsStamp;
private ITool fRProcess;
private int fRTask;
private Change fRTaskEvent;
private DB fDB;
private final Cache fCache;
public RPkgManager(final IREnvConfiguration rConfig) {
fREnv = rConfig.getReference();
fREnvDirectory = EFS.getLocalFileSystem().getStore(REnvConfiguration.getStateLocation(fREnv));
final String qualifier = ((AbstractPreferencesModelObject) rConfig).getNodeQualifiers()[0];
fSelectedReposPref = new RRepoListPref(qualifier, "RPkg.Repos.repos"); //$NON-NLS-1$
fSelectedCRANPref = new RRepoPref(qualifier, "RPkg.CRANMirror.repo"); //$NON-NLS-1$
fBioCVersionPref = new StringPref2(qualifier, "RPkg.BioCVersion.ver"); //$NON-NLS-1$
fSelectedBioCPref = new RRepoPref(qualifier, "RPkg.BioCMirror.repo"); //$NON-NLS-1$
final IPreferenceAccess prefs = PreferencesUtil.getInstancePrefs();
fAddRepos = new ArrayList<>();
if (rConfig.getType() == IREnvConfiguration.USER_LOCAL_TYPE) {
final String rjVersion = "" + ServerUtil.RJ_VERSION[0] + '.' + ServerUtil.RJ_VERSION[1]; //$NON-NLS-1$
fAddRepos.add(new RRepo(RRepo.SPECIAL_PREFIX+"rj", "RJ", "http://download.walware.de/rj-" + rjVersion, null)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
fSelectedRepos = new SelectedRepos(
prefs.getPreferenceValue(fSelectedReposPref),
prefs.getPreferenceValue(fSelectedCRANPref),
prefs.getPreferenceValue(fBioCVersionPref),
prefs.getPreferenceValue(fSelectedBioCPref) );
fDB = DB.create(fREnv, fREnvDirectory);
fCache = new Cache(fREnvDirectory);
resetPkgs(rConfig);
fFirstTime = true;
fMirrorsStamp = fPkgsStamp = System.currentTimeMillis();
fRequireLoad |= (REQUIRE_CRAN | REQUIRE_BIOC | REQUIRE_REPOS);
fRequireLoad |= (REQUIRE_REPO_PKGS | REQUIRE_INST_PKGS);
PreferencesUtil.getSettingsChangeNotifier().addManageListener(this);
getWriteLock().lock();
try {
loadPrefs(true);
}
finally {
getWriteLock().unlock();
}
}
private void resetPkgs(final IREnvConfiguration config) {
fPkgsExt = null;
if (fDB != null && config != null) {
fPkgsLight = fDB.loadPkgs(config.getRLibraryGroups());
}
if (fPkgsLight == null) {
fDB = null;
fPkgsLight = new RPkgSet(0);
}
}
@Override
public IREnv getREnv() {
return fREnv;
}
Cache getCache() {
return fCache;
}
@Override
public RPlatform getRPlatform() {
return fRPlatform;
}
@Override
public Lock getReadLock() {
return fLock.readLock();
}
@Override
public Lock getWriteLock() {
return fLock.writeLock();
}
@Override
public void clear() {
getWriteLock().lock();
try {
fSelectedRepos = new SelectedRepos(Collections.<RRepo> emptyList(),
null, null, null);
savePrefs(fSelectedRepos);
fRequireLoad |= (REQUIRE_CRAN | REQUIRE_BIOC);
fRequireLoad |= (REQUIRE_REPOS);
final Change change = new Change(fREnv);
change.fRepos = 1;
checkRepos(change);
fRequireLoad |= (REQUIRE_REPO_PKGS | REQUIRE_INST_PKGS);
resetPkgs(fREnv.getConfig());
fFirstTime = true;
}
finally {
getWriteLock().unlock();
}
}
public void dispose() {
PreferencesUtil.getSettingsChangeNotifier().removeManageListener(this);
}
@Override
public void beforeSettingsChangeNotification(final Set<String> groupIds) {
if (groupIds.contains(CUSTOM_GROUP_ID)) {
loadPrefs(groupIds.contains(CUSTOM_GROUP_ID));
}
}
@Override
public void afterSettingsChangeNotification(final Set<String> groupIds) {
}
@Override
public void check(final int flags, final RService r, final IProgressMonitor monitor) throws CoreException {
checkInit(flags, r, monitor);
check(r, monitor);
}
private void checkInit(final int flags,
final RService r, final IProgressMonitor monitor) throws CoreException {
if ((flags & INITIAL) == INITIAL || fRPlatform == null) {
checkRVersion(r.getPlatform());
final IREnvConfiguration config = fREnv.getConfig();
if (config != null && config.isRemote()) {
fRLibGroups = REnvLibGroups.loadFromR(r, monitor);
}
}
}
private void check(
final RService r, final IProgressMonitor monitor) throws CoreException {
if (!beginRTaskSilent((IToolService) r, monitor)) {
return;
}
try {
checkInstalled(null, r, monitor);
if (fRTaskEvent != null) {
fireUpdate(fRTaskEvent);
}
}
catch (final Exception e) {
throw new CoreException(new Status(IStatus.ERROR, RCore.PLUGIN_ID,
"An error occurred when checking for new and updated R packages.", e));
}
finally {
fRTaskEvent = null;
endRTask();
}
}
private void checkRVersion(final RPlatform rPlatform) {
if (fRPlatform != null && !fRPlatform.getRVersion().equals(rPlatform.getRVersion())) {
getWriteLock().lock();
try {
fRequireLoad |= (REQUIRE_REPOS | REQUIRE_CRAN | REQUIRE_BIOC);
fRequireLoad |= (REQUIRE_REPO_PKGS | REQUIRE_INST_PKGS);
}
finally {
getWriteLock().unlock();
}
refreshPkgs();
}
fRPlatform = rPlatform;
}
@Override
public boolean requiresUpdate() {
final long stamp = System.currentTimeMillis();
if (Math.abs(fMirrorsStamp - stamp) > MIRROR_CHECK) {
getWriteLock().lock();
try {
fRequireLoad |= (REQUIRE_CRAN | REQUIRE_BIOC);
return true;
}
finally {
getWriteLock().unlock();
}
}
if ((fRequireLoad & (REQUIRE_REPOS | REQUIRE_CRAN | REQUIRE_BIOC)) != 0) {
return true;
}
final IStatus status = getReposStatus(null);
if (!status.isOK()) {
return false;
}
if (Math.abs(fPkgsStamp - stamp) > MIRROR_CHECK) {
getWriteLock().lock();
try {
fRequireLoad |= (REQUIRE_REPO_PKGS);
return true;
}
finally {
getWriteLock().unlock();
}
}
if ((fRequireLoad & (REQUIRE_REPO_PKGS | REQUIRE_INST_PKGS)) != 0) {
return true;
}
return false;
}
@Override
public IStatus getReposStatus(final ISelectedRepos repos) {
final ISelectedRepos current = fSelectedRepos;
final int confirm = fRequireConfirm;
return getReposStatus((repos != null) ? repos : current, current, confirm);
}
private IStatus getReposStatus(final ISelectedRepos repos, final ISelectedRepos current, final int confirm) {
if (repos.getRepos().isEmpty()) {
return createStatus(IStatus.ERROR, "No repository is selected. Select the repositories where to install R packages from.");
}
final boolean requireCRAN = RVarRepo.requireCRANMirror(repos.getRepos());
if (requireCRAN && repos.getCRANMirror() == null) {
return createStatus(IStatus.ERROR, "No CRAN mirror is selected. Selected a mirror for CRAN.");
}
final boolean requireBioC = RVarRepo.requireBioCMirror(repos.getRepos());
if (requireBioC && repos.getBioCMirror() == null) {
return createStatus(IStatus.ERROR, "No BioC mirror is selected. Selected a mirror for Bioconductor.");
}
if ((requireCRAN && (confirm & REQUIRE_CRAN) != 0)
|| (requireBioC && (confirm & REQUIRE_BIOC) != 0)
|| (repos != current && !repos.equals(current) )) {
return createStatus(IStatus.INFO, "Check the repository settings and confirm with 'Apply' to show the available R packages.");
}
return Status.OK_STATUS;
}
private static IStatus createStatus(final int severity, final String message) {
return new Status(severity, RCore.PLUGIN_ID, message);
}
@Override
public void update(final RService r, final IProgressMonitor monitor) throws CoreException {
beginRTask((IToolService) r, monitor);
try {
checkInit(0, r, monitor);
fRTaskEvent = new Change(fREnv);
final ISelectedRepos settings = runLoadRepos(r, monitor);
if (settings != null) {
runApplyRepo(settings, r, monitor);
runLoadPkgs(settings, r, monitor);
}
fireUpdate(fRTaskEvent);
}
finally {
fRTaskEvent = null;
endRTask();
}
}
private void checkMirrors(final Change event) {
if ((fRequireLoad & (REQUIRE_CRAN | REQUIRE_BIOC)) != 0) {
return;
}
SelectedRepos selected = fSelectedRepos;
fAllCRAN = ConstArrayList.concat(fCustomCRAN, fRCRAN);
RRepo selectedCRAN = selected.getCRANMirror();
if (selected.getCRANMirror() != null) {
selectedCRAN = Util.findRepo(fAllCRAN, selectedCRAN);
}
else if (fFirstTime && fSelectedCRANInR != null) {
selectedCRAN = Util.getRepoByURL(fAllCRAN, fSelectedCRANInR);
}
if (selectedCRAN == null) {
fRequireConfirm |= REQUIRE_CRAN;
selectedCRAN = PreferencesUtil.getInstancePrefs().getPreferenceValue(LAST_CRAN_PREF);
if (selectedCRAN != null) {
selectedCRAN = Util.findRepo(fAllCRAN, selectedCRAN);
}
if (!fCustomCRAN.isEmpty()
&& (selectedCRAN == null || !selectedCRAN.getId().startsWith(RRepo.CUSTOM_PREFIX)) ) {
selectedCRAN = fCustomCRAN.get(0);
}
if (fFirstTime && selectedCRAN == null) {
selectedCRAN = fRCRANByCountry;
}
}
RRepo selectedBioC = selected.getBioCMirror();
fAllBioC = ConstArrayList.concat(fCustomBioC, fRBioC);
if (selectedBioC != null) {
selectedBioC = Util.findRepo(fAllBioC, selectedBioC);
}
else if (fFirstTime && fSelectedBioCInR != null) {
selectedBioC = RPkgUtil.getRepoByURL(fAllBioC, fSelectedBioCInR);
}
if (selectedBioC == null) {
fRequireConfirm |= REQUIRE_BIOC;
selectedBioC = PreferencesUtil.getInstancePrefs().getPreferenceValue(LAST_BIOC_PREF);
if (!fCustomBioC.isEmpty()
&& (selectedBioC == null || !selectedBioC.getId().startsWith(RRepo.CUSTOM_PREFIX)) ) {
selectedBioC = fCustomBioC.get(0);
}
if (fFirstTime && selectedBioC == null) {
selectedBioC = Util.getRepoByURL(fAllBioC, "http://www.bioconductor.org"); //$NON-NLS-1$
}
}
selected = new SelectedRepos(
selected.getRepos(),
selectedCRAN,
fBioCVersion,
selectedBioC );
if ((fRequireLoad & (REQUIRE_REPOS)) == 0) {
for (final RRepo repo : fAllRepos) {
if (repo instanceof RVarRepo) {
((RVarRepo) repo).updateURL(selected);
}
}
}
fSelectedRepos = selected;
event.fPkgs = 1;
}
private void checkRepos(final Change event) {
if ((fRequireLoad & (REQUIRE_CRAN | REQUIRE_BIOC | REQUIRE_REPOS)) != 0) {
return;
}
SelectedRepos selected = fSelectedRepos;
fAllRepos = new ArrayList<>(fCustomRepos.size() + fAddRepos.size() + fRRepos.size());
fAllRepos.addAll(fCustomRepos);
fAllRepos.addAll(fAddRepos);
for (final RRepo repo : fAllRepos) {
if (repo instanceof RVarRepo) {
((RVarRepo) repo).updateURL(selected);
}
}
for (final RRepo repo : fRRepos) {
if (repo instanceof RVarRepo) {
((RVarRepo) repo).updateURL(selected);
}
}
for (final RRepo repo : fRRepos) {
if (!repo.getId().isEmpty()) {
if (RPkgUtil.getRepoById(fAllRepos, repo.getId()) == null) {
fAllRepos.add(repo);
}
}
else {
if (Util.getRepoByURL(fAllRepos, repo) == null) {
fAllRepos.add(RVarRepo.create(RRepo.R_PREFIX + repo.getURL(), repo.getName(),
repo.getURL(), null ));
}
}
}
{ final Collection<RRepo> selectedRepos = selected.getRepos();
final Collection<RRepo> previous = (fFirstTime && selectedRepos.isEmpty()) ?
fSelectedReposInR : selectedRepos;
final List<RRepo> repos = new ArrayList<>(previous.size());
for (RRepo repo : previous) {
repo = Util.findRepo(fAllRepos, repo);
if (repo != null) {
repos.add(repo);
}
}
selected = new SelectedRepos(
repos,
selected.getCRANMirror(),
selected.getBioCVersion(),
selected.getBioCMirror() );
fSelectedRepos = selected;
}
fRequireLoad |= REQUIRE_REPO_PKGS;
event.fRepos = 1;
}
private void loadPrefs(final boolean custom) {
final Change event = new Change(fREnv);
final IPreferenceAccess prefs = PreferencesUtil.getInstancePrefs();
getWriteLock().lock();
try {
if (custom) {
fCustomRepos = prefs.getPreferenceValue(CUSTOM_REPO_PREF);
fCustomCRAN = prefs.getPreferenceValue(CUSTOM_CRAN_MIRROR_PREF);
fCustomBioC = prefs.getPreferenceValue(CUSTOM_BIOC_MIRROR_PREF);
checkRepos(event);
}
}
finally {
getWriteLock().unlock();
}
fireUpdate(event);
}
@Override
public void addListener(final Listener listener) {
fListeners.add(listener);
}
@Override
public void removeListener(final Listener listener) {
fListeners.remove(listener);
}
private void fireUpdate(final Event event) {
if (event.reposChanged() == 0 && event.pkgsChanged() == 0 && event.viewsChanged() == 0) {
return;
}
final Listener[] listeners = fListeners.toArray();
for (int i = 0; i < listeners.length; i++) {
listeners[i].handleChange(event);
}
}
@Override
public List<RRepo> getAvailableRepos() {
return fAllRepos;
}
@Override
public ISelectedRepos getSelectedRepos() {
return fSelectedRepos;
}
@Override
public void setSelectedRepos(final ISelectedRepos repos) {
List<RRepo> selectedRepos;
{ final Collection<RRepo> selected = repos.getRepos();
selectedRepos = new ArrayList<>(selected.size());
for (final RRepo repo : fAllRepos) {
if (selected.contains(repo)) {
selectedRepos.add(repo);
}
}
}
RRepo selectedCRAN;
{ final RRepo repo = repos.getCRANMirror();
selectedCRAN = (repo != null) ? Util.findRepo(fAllCRAN, repo) : null;
fRequireConfirm &= ~REQUIRE_CRAN;
}
RRepo selectedBioC;
{ final RRepo repo = repos.getBioCMirror();
selectedBioC = (repo != null) ? Util.findRepo(fAllBioC, repo) : null;
fRequireConfirm &= ~REQUIRE_BIOC;
}
final SelectedRepos previousSettings = fSelectedRepos;
final SelectedRepos newSettings = new SelectedRepos(
selectedRepos,
selectedCRAN,
previousSettings.getBioCVersion(), selectedBioC );
for (final RRepo repo : fAllRepos) {
if (repo instanceof RVarRepo) {
((RVarRepo) repo).updateURL(newSettings);
}
}
fSelectedRepos = newSettings;
savePrefs(newSettings);
if (!newSettings.equals(previousSettings)) {
fRequireLoad |= (REQUIRE_REPO_PKGS);
final Change event = new Change(fREnv);
event.fRepos = 1;
fireUpdate(event);
}
}
@Override
public RRepo getRepo(final String repoId) {
if (repoId.isEmpty()) {
return null;
}
RRepo repo = fSelectedRepos.getRepo(repoId);
if (repo == null) {
repo = RPkgUtil.getRepoById(fAllRepos, repoId);
}
return repo;
}
private void savePrefs(final SelectedRepos repos) {
if (fREnv.getConfig() == null) {
return;
}
final IScopeContext prefs = InstanceScope.INSTANCE;
final IEclipsePreferences node = prefs.getNode(fSelectedReposPref.getQualifier());
PreferencesUtil.setPrefValue(node, fSelectedReposPref, repos.getRepos());
PreferencesUtil.setPrefValue(node, fSelectedCRANPref, repos.getCRANMirror());
PreferencesUtil.setPrefValue(node, fBioCVersionPref, repos.getBioCVersion());
PreferencesUtil.setPrefValue(node, fSelectedBioCPref, repos.getBioCMirror());
if (repos.getCRANMirror() != null) {
PreferencesUtil.setPrefValue(prefs, LAST_CRAN_PREF, repos.getCRANMirror());
}
if (repos.getBioCMirror() != null) {
PreferencesUtil.setPrefValue(prefs, LAST_BIOC_PREF, repos.getBioCMirror());
}
try {
node.flush();
}
catch (final BackingStoreException e) {
RCorePlugin.log(new Status(IStatus.ERROR, RCore.PLUGIN_ID,
"An error occurred when saving the R package manager preferences.", e ));
}
}
@Override
public void refreshPkgs() {
fRequireLoad |= (REQUIRE_REPO_PKGS | REQUIRE_INST_PKGS);
}
@Override
public List<RRepo> getAvailableCRANMirrors() {
return fAllCRAN;
}
@Override
public List<RRepo> getAvailableBioCMirrors() {
return fAllBioC;
}
@Override
public IRLibPaths getRLibPaths() {
return fRLibPaths;
}
public REnvLibGroups getRLibGroups() {
if (fRLibGroups != null) {
return fRLibGroups;
}
final IREnvConfiguration config = fREnv.getConfig();
if (config != null) {
return new REnvLibGroups(config);
}
return null;
}
@Override
public IRPkgSet getRPkgSet() {
return (fPkgsExt != null) ? fPkgsExt : fPkgsLight;
}
@Override
public IRPkgSet.Ext getExtRPkgSet() {
return fPkgsExt;
}
@Override
public List<? extends IRView> getRViews() {
return fRViews;
}
// @Override
// public List<? extends IRView> getBioCViews() {
// return fBioCViews;
// }
@Override
public void apply(final ITool process) {
process.getQueue().add(new AbstractRToolRunnable("r/renv/rpkg.apply", //$NON-NLS-1$
"Perform Package Manager Operations") {
@Override
protected void run(final IRToolService r, final IProgressMonitor monitor) throws CoreException {
runApply(r, monitor);
}
});
}
private boolean beginRTaskSilent(final IToolService r,
final IProgressMonitor monitor) {
synchronized (this) {
if (fRProcess != null) {
return false;
}
fRProcess = r.getTool();
fRTask = 1;
return true;
}
}
private void beginRTask(final IToolService r,
final IProgressMonitor monitor) throws CoreException {
synchronized (this) {
while (fRProcess != null) {
if (fRTask == 1) {
monitor.subTask("Waiting for package check...");
try {
wait();
}
catch (final InterruptedException e) {
if (monitor.isCanceled()) {
throw new CoreException(Status.CANCEL_STATUS);
}
}
}
else {
final Status status = new Status(IStatus.ERROR, RCore.PLUGIN_ID,
NLS.bind("Another package manager task for ''{0}'' is already running in ''{0}''",
fREnv.getName(), fRProcess.getLabel(ITool.DEFAULT_LABEL) ));
// r.handleStatus(status, monitor);
throw new CoreException(status);
}
}
fRProcess = r.getTool();
fRTask = 2;
}
}
private void endRTask() {
synchronized (this) {
fRProcess = null;
fRTask = 0;
notifyAll();
}
}
protected void runApply(final RService r, final IProgressMonitor monitor)
throws CoreException {
beginRTask((IToolService) r, monitor);
try {
final ISelectedRepos selectedRepos;
getReadLock().lock();
try {
selectedRepos = fSelectedRepos;
}
finally {
getReadLock().unlock();
}
if (getReposStatus(selectedRepos).getSeverity() != IStatus.ERROR) {
fRTaskEvent = new Change(fREnv);
runApplyRepo(selectedRepos, r, monitor);
runLoadPkgs(selectedRepos, r, monitor);
fireUpdate(fRTaskEvent);
}
}
finally {
fRTaskEvent = null;
endRTask();
}
}
private ISelectedRepos runLoadRepos(final RService r,
final IProgressMonitor monitor) throws CoreException {
try {
- String bioCVersion;
- { final RObject data = r.evalData("as.character(tools:::.BioC_version_associated_with_R_version)", monitor);
- bioCVersion = RDataUtil.checkSingleCharValue(data);
+ String bioCVersion= null;
+ try {
+ final RObject data= r.evalData("as.character(rj:::.renv.getBioCVersion())", monitor);
+ bioCVersion= RDataUtil.checkSingleCharValue(data);
+ }
+ catch (final CoreException e) {
+ try {
+ final RObject data= r.evalData("as.character(tools:::.BioC_version_associated_with_R_version)", monitor);
+ bioCVersion= RDataUtil.checkSingleCharValue(data);
+ }
+ catch (final CoreException ignore) {
+ final Status status = new Status(IStatus.ERROR, RCore.PLUGIN_ID, 0,
+ "Failed to get the version of BioC.", e );
+ RCorePlugin.log(status);
+ }
}
final boolean loadRMirrors = ((fRequireLoad & (REQUIRE_CRAN | REQUIRE_BIOC)) != 0);
final boolean loadRRepos = ((fRequireLoad & (REQUIRE_REPOS)) != 0);
List<RRepo> rCRAN = null;
List<RRepo> rBioC = null;
String selectedCRAN = null;
RRepo rCRANByCountry = null;
String selectedBioC = null;
if (loadRMirrors) {
monitor.subTask("Fetching available mirrors...");
final String region = Locale.getDefault().getCountry().toLowerCase();
{ final RObject data = r.evalData("getCRANmirrors()[c('Name', 'URL', 'CountryCode')]", monitor); //$NON-NLS-1$
final RDataFrame df = RDataUtil.checkRDataFrame(data);
final RCharacterStore names = RDataUtil.checkRCharVector(df.get("Name")).getData(); //$NON-NLS-1$
final RCharacterStore urls = RDataUtil.checkRCharVector(df.get("URL")).getData(); //$NON-NLS-1$
final RCharacterStore regions = RDataUtil.checkRCharVector(df.get("CountryCode")).getData(); //$NON-NLS-1$
final int l = RDataUtil.checkIntLength(names);
rCRAN = new ArrayList<>(l);
for (int i = 0; i < l; i++) {
final String url = Util.checkURL(urls.getChar(i));
if (!url.isEmpty()) {
final RRepo repo = new RRepo(RRepo.R_PREFIX + url, names.getChar(i),
url, null );
rCRAN.add(repo);
if (rCRANByCountry == null && !region.isEmpty()
&& region.equals(regions.getChar(i))) {
rCRANByCountry = repo;
}
}
}
}
{ final String[][] fix = new String[][] {
{ "Seattle (USA)", "http://www.bioconductor.org" },
{ "Bethesda (USA)", "http://watson.nci.nih.gov/bioc_mirror" },
{ "Dortmund (Germany)", "http://bioconductor.statistik.tu-dortmund.de" },
{ "Bergen (Norway)", "http://bioconductor.uib.no" },
{ "Cambridge (UK)", "http://mirrors.ebi.ac.uk/bioconductor" }
};
rBioC = new ArrayList<>(fix.length);
for (int i = 0; i < fix.length; i++) {
final String url = Util.checkURL(fix[i][1]);
if (!url.isEmpty()) {
rBioC.add(new RRepo(RRepo.R_PREFIX + url, fix[i][0], url, null));
}
}
}
}
List<RRepo> rrepos = null;
List<RRepo> selected = null;
if (loadRRepos) {
monitor.subTask("Fetching available repositories...");
{ final RObject data = r.evalData("options('repos')[[1L]]", monitor); //$NON-NLS-1$
if (data.getRObjectType() != RObject.TYPE_NULL) {
final RCharacterStore urls = RDataUtil.checkRCharVector(data).getData();
final RStore ids = ((RVector<?>) data).getNames();
final int l = RDataUtil.checkIntLength(urls);
selected = new ArrayList<>(l);
for (int i = 0; i < l; i++) {
final String id = (ids != null) ? ids.getChar(i) : null;
final String url = urls.getChar(i);
final RRepo repo = Util.createRepoFromR(id, null, url);
if (repo != null) {
selected.add(repo);
}
}
}
else {
selected = new ArrayList<>(4);
}
}
final RObject data = r.evalData("local({" + //$NON-NLS-1$
"p <- file.path(Sys.getenv('HOME'), '.R', 'repositories')\n" + //$NON-NLS-1$
"if (!file.exists(p)) p <- file.path(R.home('etc'), 'repositories')\n" + //$NON-NLS-1$
"r <- utils::read.delim(p, header = TRUE, comment.char = '#', colClasses = c(rep.int('character', 3L), rep.int('logical', 4L)))\n" + //$NON-NLS-1$
"r[c(names(r)[1L], 'URL', 'default')]\n" + //$NON-NLS-1$
"})", monitor); //$NON-NLS-1$
final RDataFrame df = RDataUtil.checkRDataFrame(data);
final RStore ids = df.getRowNames();
final RCharacterStore labels = RDataUtil.checkRCharVector(df.get(0)).getData();
final RCharacterStore urls = RDataUtil.checkRCharVector(df.get("URL")).getData(); //$NON-NLS-1$
final RLogicalStore isDefault = (selected.isEmpty()) ?
RDataUtil.checkRLogiVector(df.get("default")).getData() : null; //$NON-NLS-1$
{ final int l = RDataUtil.checkIntLength(labels);
rrepos = new ArrayList<>(l + 4);
for (int i = 0; i < l; i++) {
final String id = (ids != null) ? ids.getChar(i) : null;
final String url = urls.getChar(i);
final RRepo repo = Util.createRepoFromR(id, labels.getChar(i), url);
if (repo != null) {
rrepos.add(repo);
if (isDefault != null && isDefault.getLogi(i)) {
selected.add(repo);
}
}
}
}
for (int i = 0; i < selected.size(); i++) {
final RRepo repo = selected.get(i);
RRepo rrepo = null;
if (!repo.getURL().isEmpty()) {
rrepo = RPkgUtil.getRepoByURL(rrepos, repo.getURL());
}
if (rrepo != null) {
selected.set(i, rrepo);
continue;
}
if (!repo.getId().isEmpty()) {
final int j = rrepos.indexOf(repo); // by id
if (j >= 0) {
rrepo = rrepos.get(j);
if (!RVarRepo.hasVars(rrepo.getURL())) {
rrepo.setURL(repo.getURL());
}
selected.set(i, rrepo);
continue;
}
}
repo.setName(RRepo.hintName(repo));
continue;
}
}
if (loadRMirrors) {
if (loadRRepos) {
final RRepo repo = RPkgUtil.getRepoById(rrepos, RRepo.CRAN_ID);
if (repo != null && !repo.getURL().isEmpty()
&& !RVarRepo.hasVars(repo.getURL()) ) {
selectedCRAN = repo.getURL();
}
}
else {
final RObject data = r.evalData("options('repos')[[1L]]['CRAN']", monitor); //$NON-NLS-1$
if (data.getRObjectType() != RObject.TYPE_NULL) {
final String url = Util.checkURL(RDataUtil.checkSingleChar(data));
if (!url.isEmpty() && !RVarRepo.hasVars(url)) {
selectedCRAN = url;
}
}
}
{ final RObject data = r.evalData("options('BioC_mirror')[[1L]]", monitor); //$NON-NLS-1$
if (data.getRObjectType() != RObject.TYPE_NULL) {
selectedBioC = RDataUtil.checkSingleChar(data);
}
}
}
getWriteLock().lock();
try {
fBioCVersion = bioCVersion;
if (loadRMirrors) {
fRequireLoad &= ~(REQUIRE_CRAN | REQUIRE_BIOC);
fRCRAN = rCRAN;
fRCRANByCountry = rCRANByCountry;
fSelectedCRANInR = selectedCRAN;
fRBioC = rBioC;
fSelectedBioCInR = selectedBioC;
fMirrorsStamp = fRTaskEvent.fStamp;
checkMirrors(fRTaskEvent);
}
if (loadRRepos) {
fRequireLoad &= ~(REQUIRE_REPOS);
fRRepos = rrepos;
fSelectedReposInR = selected;
checkRepos(fRTaskEvent);
}
fFirstTime = false;
if (getReposStatus(fSelectedRepos, fSelectedRepos, fRequireConfirm).isOK()) {
return fSelectedRepos;
}
return null;
}
finally {
getWriteLock().unlock();
}
}
catch (final Exception e) {
throw new CoreException(new Status(IStatus.ERROR, RCore.PLUGIN_ID, 0,
"An error occurred when loading data for package manager.", e));
}
}
private void runApplyRepo(final ISelectedRepos repos, final RService r,
final IProgressMonitor monitor) throws CoreException {
monitor.subTask("Setting repository configuration...");
try {
if (repos.getBioCMirror() != null) {
final FunctionCall call = r.createFunctionCall("options");
call.addChar("BioC_mirror", repos.getBioCMirror().getURL());
call.evalVoid(monitor);
}
{ final List<RRepo> selectedRepos = (List<RRepo>) repos.getRepos();
final String[] ids = new String[selectedRepos.size()];
final String[] urls = new String[selectedRepos.size()];
for (int i = 0; i < urls.length; i++) {
final RRepo repo = selectedRepos.get(i);
ids[i] = repo.getId();
urls[i] = repo.getURL();
}
final RVector<RCharacterStore> data = new RVectorImpl<RCharacterStore>(
new RCharacterDataImpl(urls), RObject.CLASSNAME_CHARACTER, ids);
final FunctionCall call = r.createFunctionCall("options");
call.add("repos", data);
call.evalVoid(monitor);
}
}
catch (final CoreException e) {
throw new CoreException(new Status(IStatus.ERROR, RCore.PLUGIN_ID,
"An error occurred when setting repository configuration in R.",
e ));
}
}
private void runLoadPkgs(final ISelectedRepos repoSettings, final RService r,
final IProgressMonitor monitor) throws CoreException {
final boolean loadRepoPkgs = (fRequireLoad & (REQUIRE_REPO_PKGS)) != 0
&& getReposStatus(repoSettings).isOK();
final boolean loadInstPkgs = ((fRequireLoad & (REQUIRE_INST_PKGS)) != 0);
FullRPkgSet pkgs = null;
if (loadRepoPkgs) {
fRTaskEvent.fOldPkgs = getRPkgSet();
fRTaskEvent.fNewPkgs = pkgs = fPkgScanner.loadAvailable(repoSettings, r, monitor);
}
if (loadInstPkgs) {
if (pkgs == null) {
if (fPkgsExt != null) {
pkgs = fPkgsExt.cloneAvailable();
}
else {
pkgs = new FullRPkgSet(0);
}
}
checkInstalled(pkgs, r, monitor);
updateRViews(repoSettings, pkgs, r, monitor);
}
if (pkgs != null) {
getWriteLock().lock();
try {
setPkgs();
if (loadRepoPkgs) {
fRequireLoad &= ~REQUIRE_REPO_PKGS;
fPkgsStamp = fRTaskEvent.fStamp;
fRTaskEvent.fPkgs |= AVAILABLE;
}
if (loadInstPkgs) {
fRequireLoad &= ~REQUIRE_INST_PKGS;
}
}
finally {
getWriteLock().unlock();
}
}
}
private void checkInstalled(final FullRPkgSet pkgs,
final RService r, final IProgressMonitor monitor)
throws CoreException {
RVector<RNumericStore> libs = null;
boolean[] update = null;
try {
libs = RDataUtil.checkRNumVector(r.evalData(
"rj:::.renv.checkLibs()", monitor )); //$NON-NLS-1$
final int l = RDataUtil.checkIntLength(libs.getData());
ITER_LIBS: for (int idxLib = 0; idxLib < l; idxLib++) {
final String libPath = libs.getNames().getChar(idxLib);
if (fLibs != null) {
final int idx = (int) fLibs.getNames().indexOf(libPath);
if (idx >= 0) {
if (fLibs.getData().getNum(idx) == libs.getData().getNum(idxLib)) {
continue ITER_LIBS;
}
}
}
if (update == null) {
update = new boolean[l];
}
update[idxLib] = true;
}
fLibs = libs;
}
catch (final UnexpectedRDataException | CoreException e) {
throw new CoreException(new Status(IStatus.ERROR, RCore.PLUGIN_ID,
"An error occurred when checking for changed R libraries.",
e ));
}
if (update != null || pkgs != null) {
if (fRTaskEvent == null) {
fRTaskEvent = new Change(fREnv);
}
if (fRTaskEvent.fOldPkgs == null) {
fRTaskEvent.fOldPkgs = getRPkgSet();
}
if (fPkgsExt != null || pkgs != null) {
final FullRPkgSet newPkgs = (pkgs != null) ? pkgs : fPkgsExt.cloneAvailable();
fRTaskEvent.fNewPkgs = newPkgs;
fRLibPaths = RLibPaths.create(getRLibGroups(), libs, r, monitor);
fPkgScanner.updateInstFull(fRLibPaths, update, newPkgs, fRTaskEvent, r, monitor);
}
else {
final RPkgSet newPkgs = new RPkgSet((int) libs.getLength());
fRTaskEvent.fNewPkgs = newPkgs;
fRLibPaths = RLibPaths.createLight(getRLibGroups(), libs);
fPkgScanner.updateInstLight(fRLibPaths, update, newPkgs, fRTaskEvent, r, monitor);
}
if (fRTaskEvent.fInstalledPkgs != null && fRTaskEvent.fInstalledPkgs.names.isEmpty()) {
fRTaskEvent.fInstalledPkgs = null;
}
if (pkgs == null) {
setPkgs();
}
if (fRTaskEvent.fInstalledPkgs != null && fDB != null) {
fDB.updatePkgs(fRTaskEvent);
}
}
}
private void setPkgs() {
final Change event = fRTaskEvent;
if (event.fNewPkgs instanceof FullRPkgSet) {
fPkgsExt = (FullRPkgSet) event.fNewPkgs;
fPkgsLight = null;
}
else if (event.fNewPkgs instanceof RPkgSet) {
fPkgsExt = null;
fPkgsLight = (RPkgSet) event.fNewPkgs;
}
if (event.fInstalledPkgs != null) {
event.fPkgs |= INSTALLED;
}
}
private void updateRViews(final ISelectedRepos repoSettings, final FullRPkgSet pkgs,
final RService r, final IProgressMonitor monitor) {
final RPkgInfoAndData pkg = pkgs.getInstalled().getFirstByName("ctv"); //$NON-NLS-1$
if (pkg == null || pkg.getVersion().equals(fRViewsVersion)) {
return;
}
final List<RView> rViews = RViewTasks.loadRViews(r, monitor);
if (rViews != null) {
fRViews = rViews;
fRViewsVersion = pkg.getVersion();
fRTaskEvent.fViews = 1;
}
}
@Override
public IRPkgData addToCache(final IFileStore store, final IProgressMonitor monitor) throws CoreException {
final IRPkg pkg = RPkgUtil.checkPkgFileName(store.getName());
final RPkgType type = RPkgUtil.checkPkgType(store.getName(), fRPlatform);
fCache.add(pkg.getName(), type, store, monitor);
return new RPkgData(pkg.getName(), RNumVersion.NONE, RRepo.WS_CACHE_PREFIX + type.name().toLowerCase());
}
@Override
public void perform(final ITool rTool, final List<? extends RPkgAction> actions) {
if (actions.isEmpty()) {
return;
}
final String label = (actions.get(0).getAction() == RPkgAction.UNINSTALL) ?
"Uninstall R Packages" : "Install/Update R Packages";
final RPkgOperator op = new RPkgOperator(this);
rTool.getQueue().add(new AbstractStatetRRunnable("r/renv/pkgs.inst", label) { //$NON-NLS-1$
@Override
protected void run(final IRConsoleService r, final IProgressMonitor monitor) throws CoreException {
beginRTask(r, monitor);
try {
checkNewCommand(r, monitor);
op.runActions(actions, r, monitor);
}
catch (final UnexpectedRDataException | CoreException e) {
throw new CoreException(new Status(IStatus.ERROR, RCore.PLUGIN_ID, 0,
"An error occurred when installing and updating R packages.",
e ));
}
finally {
endRTask();
r.briefAboutChange(0x10); // packages
}
}
});
}
@Override
public void loadPkgs(final ITool rTool, final List<? extends IRPkgInfoAndData> pkgs,
final boolean expliciteLocation) {
final RPkgOperator op = new RPkgOperator(this);
rTool.getQueue().add(new AbstractStatetRRunnable("r/renv/pkgs.load", //$NON-NLS-1$
"Load R Packages") {
@Override
protected void run(final IRConsoleService r, final IProgressMonitor monitor) throws CoreException {
checkNewCommand(r, monitor);
op.loadPkgs(pkgs, expliciteLocation, r, monitor);
}
});
}
}
| true | true | private ISelectedRepos runLoadRepos(final RService r,
final IProgressMonitor monitor) throws CoreException {
try {
String bioCVersion;
{ final RObject data = r.evalData("as.character(tools:::.BioC_version_associated_with_R_version)", monitor);
bioCVersion = RDataUtil.checkSingleCharValue(data);
}
final boolean loadRMirrors = ((fRequireLoad & (REQUIRE_CRAN | REQUIRE_BIOC)) != 0);
final boolean loadRRepos = ((fRequireLoad & (REQUIRE_REPOS)) != 0);
List<RRepo> rCRAN = null;
List<RRepo> rBioC = null;
String selectedCRAN = null;
RRepo rCRANByCountry = null;
String selectedBioC = null;
if (loadRMirrors) {
monitor.subTask("Fetching available mirrors...");
final String region = Locale.getDefault().getCountry().toLowerCase();
{ final RObject data = r.evalData("getCRANmirrors()[c('Name', 'URL', 'CountryCode')]", monitor); //$NON-NLS-1$
final RDataFrame df = RDataUtil.checkRDataFrame(data);
final RCharacterStore names = RDataUtil.checkRCharVector(df.get("Name")).getData(); //$NON-NLS-1$
final RCharacterStore urls = RDataUtil.checkRCharVector(df.get("URL")).getData(); //$NON-NLS-1$
final RCharacterStore regions = RDataUtil.checkRCharVector(df.get("CountryCode")).getData(); //$NON-NLS-1$
final int l = RDataUtil.checkIntLength(names);
rCRAN = new ArrayList<>(l);
for (int i = 0; i < l; i++) {
final String url = Util.checkURL(urls.getChar(i));
if (!url.isEmpty()) {
final RRepo repo = new RRepo(RRepo.R_PREFIX + url, names.getChar(i),
url, null );
rCRAN.add(repo);
if (rCRANByCountry == null && !region.isEmpty()
&& region.equals(regions.getChar(i))) {
rCRANByCountry = repo;
}
}
}
}
{ final String[][] fix = new String[][] {
{ "Seattle (USA)", "http://www.bioconductor.org" },
{ "Bethesda (USA)", "http://watson.nci.nih.gov/bioc_mirror" },
{ "Dortmund (Germany)", "http://bioconductor.statistik.tu-dortmund.de" },
{ "Bergen (Norway)", "http://bioconductor.uib.no" },
{ "Cambridge (UK)", "http://mirrors.ebi.ac.uk/bioconductor" }
};
rBioC = new ArrayList<>(fix.length);
for (int i = 0; i < fix.length; i++) {
final String url = Util.checkURL(fix[i][1]);
if (!url.isEmpty()) {
rBioC.add(new RRepo(RRepo.R_PREFIX + url, fix[i][0], url, null));
}
}
}
}
List<RRepo> rrepos = null;
List<RRepo> selected = null;
if (loadRRepos) {
monitor.subTask("Fetching available repositories...");
{ final RObject data = r.evalData("options('repos')[[1L]]", monitor); //$NON-NLS-1$
if (data.getRObjectType() != RObject.TYPE_NULL) {
final RCharacterStore urls = RDataUtil.checkRCharVector(data).getData();
final RStore ids = ((RVector<?>) data).getNames();
final int l = RDataUtil.checkIntLength(urls);
selected = new ArrayList<>(l);
for (int i = 0; i < l; i++) {
final String id = (ids != null) ? ids.getChar(i) : null;
final String url = urls.getChar(i);
final RRepo repo = Util.createRepoFromR(id, null, url);
if (repo != null) {
selected.add(repo);
}
}
}
else {
selected = new ArrayList<>(4);
}
}
final RObject data = r.evalData("local({" + //$NON-NLS-1$
"p <- file.path(Sys.getenv('HOME'), '.R', 'repositories')\n" + //$NON-NLS-1$
"if (!file.exists(p)) p <- file.path(R.home('etc'), 'repositories')\n" + //$NON-NLS-1$
"r <- utils::read.delim(p, header = TRUE, comment.char = '#', colClasses = c(rep.int('character', 3L), rep.int('logical', 4L)))\n" + //$NON-NLS-1$
"r[c(names(r)[1L], 'URL', 'default')]\n" + //$NON-NLS-1$
"})", monitor); //$NON-NLS-1$
final RDataFrame df = RDataUtil.checkRDataFrame(data);
final RStore ids = df.getRowNames();
final RCharacterStore labels = RDataUtil.checkRCharVector(df.get(0)).getData();
final RCharacterStore urls = RDataUtil.checkRCharVector(df.get("URL")).getData(); //$NON-NLS-1$
final RLogicalStore isDefault = (selected.isEmpty()) ?
RDataUtil.checkRLogiVector(df.get("default")).getData() : null; //$NON-NLS-1$
{ final int l = RDataUtil.checkIntLength(labels);
rrepos = new ArrayList<>(l + 4);
for (int i = 0; i < l; i++) {
final String id = (ids != null) ? ids.getChar(i) : null;
final String url = urls.getChar(i);
final RRepo repo = Util.createRepoFromR(id, labels.getChar(i), url);
if (repo != null) {
rrepos.add(repo);
if (isDefault != null && isDefault.getLogi(i)) {
selected.add(repo);
}
}
}
}
for (int i = 0; i < selected.size(); i++) {
final RRepo repo = selected.get(i);
RRepo rrepo = null;
if (!repo.getURL().isEmpty()) {
rrepo = RPkgUtil.getRepoByURL(rrepos, repo.getURL());
}
if (rrepo != null) {
selected.set(i, rrepo);
continue;
}
if (!repo.getId().isEmpty()) {
final int j = rrepos.indexOf(repo); // by id
if (j >= 0) {
rrepo = rrepos.get(j);
if (!RVarRepo.hasVars(rrepo.getURL())) {
rrepo.setURL(repo.getURL());
}
selected.set(i, rrepo);
continue;
}
}
repo.setName(RRepo.hintName(repo));
continue;
}
}
if (loadRMirrors) {
if (loadRRepos) {
final RRepo repo = RPkgUtil.getRepoById(rrepos, RRepo.CRAN_ID);
if (repo != null && !repo.getURL().isEmpty()
&& !RVarRepo.hasVars(repo.getURL()) ) {
selectedCRAN = repo.getURL();
}
}
else {
final RObject data = r.evalData("options('repos')[[1L]]['CRAN']", monitor); //$NON-NLS-1$
if (data.getRObjectType() != RObject.TYPE_NULL) {
final String url = Util.checkURL(RDataUtil.checkSingleChar(data));
if (!url.isEmpty() && !RVarRepo.hasVars(url)) {
selectedCRAN = url;
}
}
}
{ final RObject data = r.evalData("options('BioC_mirror')[[1L]]", monitor); //$NON-NLS-1$
if (data.getRObjectType() != RObject.TYPE_NULL) {
selectedBioC = RDataUtil.checkSingleChar(data);
}
}
}
getWriteLock().lock();
try {
fBioCVersion = bioCVersion;
if (loadRMirrors) {
fRequireLoad &= ~(REQUIRE_CRAN | REQUIRE_BIOC);
fRCRAN = rCRAN;
fRCRANByCountry = rCRANByCountry;
fSelectedCRANInR = selectedCRAN;
fRBioC = rBioC;
fSelectedBioCInR = selectedBioC;
fMirrorsStamp = fRTaskEvent.fStamp;
checkMirrors(fRTaskEvent);
}
if (loadRRepos) {
fRequireLoad &= ~(REQUIRE_REPOS);
fRRepos = rrepos;
fSelectedReposInR = selected;
checkRepos(fRTaskEvent);
}
fFirstTime = false;
if (getReposStatus(fSelectedRepos, fSelectedRepos, fRequireConfirm).isOK()) {
return fSelectedRepos;
}
return null;
}
finally {
getWriteLock().unlock();
}
}
catch (final Exception e) {
throw new CoreException(new Status(IStatus.ERROR, RCore.PLUGIN_ID, 0,
"An error occurred when loading data for package manager.", e));
}
}
| private ISelectedRepos runLoadRepos(final RService r,
final IProgressMonitor monitor) throws CoreException {
try {
String bioCVersion= null;
try {
final RObject data= r.evalData("as.character(rj:::.renv.getBioCVersion())", monitor);
bioCVersion= RDataUtil.checkSingleCharValue(data);
}
catch (final CoreException e) {
try {
final RObject data= r.evalData("as.character(tools:::.BioC_version_associated_with_R_version)", monitor);
bioCVersion= RDataUtil.checkSingleCharValue(data);
}
catch (final CoreException ignore) {
final Status status = new Status(IStatus.ERROR, RCore.PLUGIN_ID, 0,
"Failed to get the version of BioC.", e );
RCorePlugin.log(status);
}
}
final boolean loadRMirrors = ((fRequireLoad & (REQUIRE_CRAN | REQUIRE_BIOC)) != 0);
final boolean loadRRepos = ((fRequireLoad & (REQUIRE_REPOS)) != 0);
List<RRepo> rCRAN = null;
List<RRepo> rBioC = null;
String selectedCRAN = null;
RRepo rCRANByCountry = null;
String selectedBioC = null;
if (loadRMirrors) {
monitor.subTask("Fetching available mirrors...");
final String region = Locale.getDefault().getCountry().toLowerCase();
{ final RObject data = r.evalData("getCRANmirrors()[c('Name', 'URL', 'CountryCode')]", monitor); //$NON-NLS-1$
final RDataFrame df = RDataUtil.checkRDataFrame(data);
final RCharacterStore names = RDataUtil.checkRCharVector(df.get("Name")).getData(); //$NON-NLS-1$
final RCharacterStore urls = RDataUtil.checkRCharVector(df.get("URL")).getData(); //$NON-NLS-1$
final RCharacterStore regions = RDataUtil.checkRCharVector(df.get("CountryCode")).getData(); //$NON-NLS-1$
final int l = RDataUtil.checkIntLength(names);
rCRAN = new ArrayList<>(l);
for (int i = 0; i < l; i++) {
final String url = Util.checkURL(urls.getChar(i));
if (!url.isEmpty()) {
final RRepo repo = new RRepo(RRepo.R_PREFIX + url, names.getChar(i),
url, null );
rCRAN.add(repo);
if (rCRANByCountry == null && !region.isEmpty()
&& region.equals(regions.getChar(i))) {
rCRANByCountry = repo;
}
}
}
}
{ final String[][] fix = new String[][] {
{ "Seattle (USA)", "http://www.bioconductor.org" },
{ "Bethesda (USA)", "http://watson.nci.nih.gov/bioc_mirror" },
{ "Dortmund (Germany)", "http://bioconductor.statistik.tu-dortmund.de" },
{ "Bergen (Norway)", "http://bioconductor.uib.no" },
{ "Cambridge (UK)", "http://mirrors.ebi.ac.uk/bioconductor" }
};
rBioC = new ArrayList<>(fix.length);
for (int i = 0; i < fix.length; i++) {
final String url = Util.checkURL(fix[i][1]);
if (!url.isEmpty()) {
rBioC.add(new RRepo(RRepo.R_PREFIX + url, fix[i][0], url, null));
}
}
}
}
List<RRepo> rrepos = null;
List<RRepo> selected = null;
if (loadRRepos) {
monitor.subTask("Fetching available repositories...");
{ final RObject data = r.evalData("options('repos')[[1L]]", monitor); //$NON-NLS-1$
if (data.getRObjectType() != RObject.TYPE_NULL) {
final RCharacterStore urls = RDataUtil.checkRCharVector(data).getData();
final RStore ids = ((RVector<?>) data).getNames();
final int l = RDataUtil.checkIntLength(urls);
selected = new ArrayList<>(l);
for (int i = 0; i < l; i++) {
final String id = (ids != null) ? ids.getChar(i) : null;
final String url = urls.getChar(i);
final RRepo repo = Util.createRepoFromR(id, null, url);
if (repo != null) {
selected.add(repo);
}
}
}
else {
selected = new ArrayList<>(4);
}
}
final RObject data = r.evalData("local({" + //$NON-NLS-1$
"p <- file.path(Sys.getenv('HOME'), '.R', 'repositories')\n" + //$NON-NLS-1$
"if (!file.exists(p)) p <- file.path(R.home('etc'), 'repositories')\n" + //$NON-NLS-1$
"r <- utils::read.delim(p, header = TRUE, comment.char = '#', colClasses = c(rep.int('character', 3L), rep.int('logical', 4L)))\n" + //$NON-NLS-1$
"r[c(names(r)[1L], 'URL', 'default')]\n" + //$NON-NLS-1$
"})", monitor); //$NON-NLS-1$
final RDataFrame df = RDataUtil.checkRDataFrame(data);
final RStore ids = df.getRowNames();
final RCharacterStore labels = RDataUtil.checkRCharVector(df.get(0)).getData();
final RCharacterStore urls = RDataUtil.checkRCharVector(df.get("URL")).getData(); //$NON-NLS-1$
final RLogicalStore isDefault = (selected.isEmpty()) ?
RDataUtil.checkRLogiVector(df.get("default")).getData() : null; //$NON-NLS-1$
{ final int l = RDataUtil.checkIntLength(labels);
rrepos = new ArrayList<>(l + 4);
for (int i = 0; i < l; i++) {
final String id = (ids != null) ? ids.getChar(i) : null;
final String url = urls.getChar(i);
final RRepo repo = Util.createRepoFromR(id, labels.getChar(i), url);
if (repo != null) {
rrepos.add(repo);
if (isDefault != null && isDefault.getLogi(i)) {
selected.add(repo);
}
}
}
}
for (int i = 0; i < selected.size(); i++) {
final RRepo repo = selected.get(i);
RRepo rrepo = null;
if (!repo.getURL().isEmpty()) {
rrepo = RPkgUtil.getRepoByURL(rrepos, repo.getURL());
}
if (rrepo != null) {
selected.set(i, rrepo);
continue;
}
if (!repo.getId().isEmpty()) {
final int j = rrepos.indexOf(repo); // by id
if (j >= 0) {
rrepo = rrepos.get(j);
if (!RVarRepo.hasVars(rrepo.getURL())) {
rrepo.setURL(repo.getURL());
}
selected.set(i, rrepo);
continue;
}
}
repo.setName(RRepo.hintName(repo));
continue;
}
}
if (loadRMirrors) {
if (loadRRepos) {
final RRepo repo = RPkgUtil.getRepoById(rrepos, RRepo.CRAN_ID);
if (repo != null && !repo.getURL().isEmpty()
&& !RVarRepo.hasVars(repo.getURL()) ) {
selectedCRAN = repo.getURL();
}
}
else {
final RObject data = r.evalData("options('repos')[[1L]]['CRAN']", monitor); //$NON-NLS-1$
if (data.getRObjectType() != RObject.TYPE_NULL) {
final String url = Util.checkURL(RDataUtil.checkSingleChar(data));
if (!url.isEmpty() && !RVarRepo.hasVars(url)) {
selectedCRAN = url;
}
}
}
{ final RObject data = r.evalData("options('BioC_mirror')[[1L]]", monitor); //$NON-NLS-1$
if (data.getRObjectType() != RObject.TYPE_NULL) {
selectedBioC = RDataUtil.checkSingleChar(data);
}
}
}
getWriteLock().lock();
try {
fBioCVersion = bioCVersion;
if (loadRMirrors) {
fRequireLoad &= ~(REQUIRE_CRAN | REQUIRE_BIOC);
fRCRAN = rCRAN;
fRCRANByCountry = rCRANByCountry;
fSelectedCRANInR = selectedCRAN;
fRBioC = rBioC;
fSelectedBioCInR = selectedBioC;
fMirrorsStamp = fRTaskEvent.fStamp;
checkMirrors(fRTaskEvent);
}
if (loadRRepos) {
fRequireLoad &= ~(REQUIRE_REPOS);
fRRepos = rrepos;
fSelectedReposInR = selected;
checkRepos(fRTaskEvent);
}
fFirstTime = false;
if (getReposStatus(fSelectedRepos, fSelectedRepos, fRequireConfirm).isOK()) {
return fSelectedRepos;
}
return null;
}
finally {
getWriteLock().unlock();
}
}
catch (final Exception e) {
throw new CoreException(new Status(IStatus.ERROR, RCore.PLUGIN_ID, 0,
"An error occurred when loading data for package manager.", e));
}
}
|
diff --git a/TFC_Shared/src/TFC/Blocks/Vanilla/BlockCustomFlowing.java b/TFC_Shared/src/TFC/Blocks/Vanilla/BlockCustomFlowing.java
index 2557c1b74..a08a573b4 100644
--- a/TFC_Shared/src/TFC/Blocks/Vanilla/BlockCustomFlowing.java
+++ b/TFC_Shared/src/TFC/Blocks/Vanilla/BlockCustomFlowing.java
@@ -1,437 +1,437 @@
package TFC.Blocks.Vanilla;
import java.util.Random;
import net.minecraft.block.Block;
import net.minecraft.block.BlockFlowing;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IconRegister;
import net.minecraft.util.Icon;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
public class BlockCustomFlowing extends BlockFlowing
{
/**
* Number of horizontally adjacent liquid source blocks. Diagonal doesn't count. Only source blocks of the same
* liquid as the block using the field are counted.
*/
int numAdjacentSources = 0;
/**
* Indicates whether the flow direction is optimal. Each array index corresponds to one of the four cardinal
* directions.
*/
boolean[] isOptimalFlowDirection = new boolean[4];
/**
* The estimated cost to flow in a given direction from the current point. Each array index corresponds to one of
* the four cardinal directions.
*/
int[] flowCost = new int[4];
public BlockCustomFlowing(int par1, Material par2Material)
{
super(par1, par2Material);
}
@Override
public void registerIcons(IconRegister par1IconRegister)
{
if (this.blockMaterial == Material.lava)
{
this.theIcon = new Icon[] {par1IconRegister.registerIcon("lava_still"), par1IconRegister.registerIcon("lava_flow")};
}
else
{
this.theIcon = new Icon[] {par1IconRegister.registerIcon("water_still"), par1IconRegister.registerIcon("water_flow")};
}
}
/**
* Updates the flow for the BlockFlowing object.
*/
private void updateFlow(World par1World, int par2, int par3, int par4)
{
int var5 = par1World.getBlockMetadata(par2, par3, par4);
par1World.setBlock(par2, par3, par4, this.blockID + 1, var5, 2);
}
@Override
public boolean getBlocksMovement(IBlockAccess par1IBlockAccess, int par2, int par3, int par4)
{
return this.blockMaterial != Material.lava;
}
@Override
public void updateTick(World par1World, int par2, int par3, int par4, Random par5Random)
{
int var6 = this.getFlowDecay(par1World, par2, par3, par4);
byte var7 = 1;
if (this.blockMaterial == Material.lava /*&& !par1World.provider.isHellWorld*/)
{
var7 = 2;
}
boolean var8 = true;
int var10;
if (var6 > 0)
{
byte var9 = -100;
this.numAdjacentSources = 0;
int var12 = this.getSmallestFlowDecay(par1World, par2 - 1, par3, par4, var9);
var12 = this.getSmallestFlowDecay(par1World, par2 + 1, par3, par4, var12);
var12 = this.getSmallestFlowDecay(par1World, par2, par3, par4 - 1, var12);
var12 = this.getSmallestFlowDecay(par1World, par2, par3, par4 + 1, var12);
var10 = var12 + var7;
if (var10 >= 8 || var12 < 0)
{
var10 = -1;
}
if (this.getFlowDecay(par1World, par2, par3 + 1, par4) >= 0)
{
int var11 = this.getFlowDecay(par1World, par2, par3 + 1, par4);
if (var11 >= 8)
{
var10 = var11;
}
else
{
var10 = var11 + 8;
}
}
if (this.numAdjacentSources >= 2 && this.blockMaterial == Material.water)
{
if (par1World.getBlockMaterial(par2, par3 - 1, par4).isSolid())
{
var10 = 0;
}
- else if (par1World.getBlockMaterial(par2, par3 - 1, par4) == this.blockMaterial && par1World.getBlockMetadata(par2, par3, par4) == 0)
+ else if (par1World.getBlockMaterial(par2, par3 - 1, par4) == this.blockMaterial && par1World.getBlockMetadata(par2, par3 - 1, par4) == 0)
{
var10 = 0;
}
}
if (this.blockMaterial == Material.lava && var6 < 8 && var10 < 8 && var10 > var6 && par5Random.nextInt(4) != 0)
{
var10 = var6;
var8 = false;
}
if (var10 == var6)
{
if (var8)
{
this.updateFlow(par1World, par2, par3, par4);
}
}
else
{
var6 = var10;
if (var10 < 0)
{
par1World.setBlockToAir(par2, par3, par4);
}
else
{
par1World.setBlockMetadataWithNotify(par2, par3, par4, var10, 2);
par1World.scheduleBlockUpdate(par2, par3, par4, this.blockID, this.tickRate(par1World));
par1World.notifyBlocksOfNeighborChange(par2, par3, par4, this.blockID);
}
}
}
else
{
this.updateFlow(par1World, par2, par3, par4);
}
if (this.liquidCanDisplaceBlock(par1World, par2, par3 - 1, par4))
{
if (this.blockMaterial == Material.lava && par1World.getBlockMaterial(par2, par3 - 1, par4) == Material.water)
{
par1World.setBlock(par2, par3 - 1, par4, Block.stone.blockID, 0, 2);
this.triggerLavaMixEffects(par1World, par2, par3 - 1, par4);
return;
}
if (var6 >= 8)
{
this.flowIntoBlock(par1World, par2, par3 - 1, par4, var6);
}
else
{
this.flowIntoBlock(par1World, par2, par3 - 1, par4, var6 + 8);
}
}
else if (var6 >= 0 && (var6 == 0 || this.blockBlocksFlow(par1World, par2, par3 - 1, par4)))
{
boolean[] var13 = this.getOptimalFlowDirections(par1World, par2, par3, par4);
var10 = var6 + var7;
if (var6 >= 8)
{
var10 = 1;
}
if (var10 >= 8)
{
return;
}
if (var13[0])
{
this.flowIntoBlock(par1World, par2 - 1, par3, par4, var10);
}
if (var13[1])
{
this.flowIntoBlock(par1World, par2 + 1, par3, par4, var10);
}
if (var13[2])
{
this.flowIntoBlock(par1World, par2, par3, par4 - 1, var10);
}
if (var13[3])
{
this.flowIntoBlock(par1World, par2, par3, par4 + 1, var10);
}
}
}
/**
* flowIntoBlock(World world, int x, int y, int z, int newFlowDecay) - Flows into the block at the coordinates and
* changes the block type to the liquid.
*/
private void flowIntoBlock(World par1World, int par2, int par3, int par4, int par5)
{
if (this.liquidCanDisplaceBlock(par1World, par2, par3, par4))
{
int i1 = par1World.getBlockId(par2, par3, par4);
if (i1 > 0)
{
if (this.blockMaterial == Material.lava)
{
this.triggerLavaMixEffects(par1World, par2, par3, par4);
}
else
{
Block.blocksList[i1].dropBlockAsItem(par1World, par2, par3, par4, par1World.getBlockMetadata(par2, par3, par4), 0);
}
}
par1World.setBlock(par2, par3, par4, this.blockID, par5, 2);
}
}
/**
* calculateFlowCost(World world, int x, int y, int z, int accumulatedCost, int previousDirectionOfFlow) - Used to
* determine the path of least resistance, this method returns the lowest possible flow cost for the direction of
* flow indicated. Each necessary horizontal flow adds to the flow cost.
*/
private int calculateFlowCost(World par1World, int par2, int par3, int par4, int par5, int par6)
{
int var7 = 1000;
for (int var8 = 0; var8 < 4; ++var8)
{
if ((var8 != 0 || par6 != 1) && (var8 != 1 || par6 != 0) && (var8 != 2 || par6 != 3) && (var8 != 3 || par6 != 2))
{
int var9 = par2;
int var11 = par4;
if (var8 == 0)
{
var9 = par2 - 1;
}
if (var8 == 1)
{
++var9;
}
if (var8 == 2)
{
var11 = par4 - 1;
}
if (var8 == 3)
{
++var11;
}
if (!this.blockBlocksFlow(par1World, var9, par3, var11) && (par1World.getBlockMaterial(var9, par3, var11) != this.blockMaterial || par1World.getBlockMetadata(var9, par3, var11) != 0))
{
if (!this.blockBlocksFlow(par1World, var9, par3 - 1, var11))
{
return par5;
}
if (par5 < 4)
{
int var12 = this.calculateFlowCost(par1World, var9, par3, var11, par5 + 1, var8);
if (var12 < var7)
{
var7 = var12;
}
}
}
}
}
return var7;
}
/**
* Returns a boolean array indicating which flow directions are optimal based on each direction's calculated flow
* cost. Each array index corresponds to one of the four cardinal directions. A value of true indicates the
* direction is optimal.
*/
private boolean[] getOptimalFlowDirections(World par1World, int par2, int par3, int par4)
{
int var5;
int var6;
for (var5 = 0; var5 < 4; ++var5)
{
this.flowCost[var5] = 1000;
var6 = par2;
int var8 = par4;
if (var5 == 0)
{
var6 = par2 - 1;
}
if (var5 == 1)
{
++var6;
}
if (var5 == 2)
{
var8 = par4 - 1;
}
if (var5 == 3)
{
++var8;
}
if (!this.blockBlocksFlow(par1World, var6, par3, var8) && (par1World.getBlockMaterial(var6, par3, var8) != this.blockMaterial || par1World.getBlockMetadata(var6, par3, var8) != 0))
{
if (this.blockBlocksFlow(par1World, var6, par3 - 1, var8))
{
this.flowCost[var5] = this.calculateFlowCost(par1World, var6, par3, var8, 1, var5);
}
else
{
this.flowCost[var5] = 0;
}
}
}
var5 = this.flowCost[0];
for (var6 = 1; var6 < 4; ++var6)
{
if (this.flowCost[var6] < var5)
{
var5 = this.flowCost[var6];
}
}
for (var6 = 0; var6 < 4; ++var6)
{
this.isOptimalFlowDirection[var6] = this.flowCost[var6] == var5;
}
return this.isOptimalFlowDirection;
}
/**
* Returns true if block at coords blocks fluids
*/
private boolean blockBlocksFlow(World par1World, int par2, int par3, int par4)
{
int var5 = par1World.getBlockId(par2, par3, par4);
if (var5 != Block.doorWood.blockID && var5 != Block.doorIron.blockID && var5 != Block.signPost.blockID && var5 != Block.ladder.blockID && var5 != Block.reed.blockID)
{
if (var5 == 0)
{
return false;
}
else
{
Material var6 = Block.blocksList[var5].blockMaterial;
return var6 == Material.portal ? true : var6.blocksMovement();
}
}
else
{
return true;
}
}
/**
* getSmallestFlowDecay(World world, intx, int y, int z, int currentSmallestFlowDecay) - Looks up the flow decay at
* the coordinates given and returns the smaller of this value or the provided currentSmallestFlowDecay. If one
* value is valid and the other isn't, the valid value will be returned. Valid values are >= 0. Flow decay is the
* amount that a liquid has dissipated. 0 indicates a source block.
*/
@Override
protected int getSmallestFlowDecay(World par1World, int par2, int par3, int par4, int par5)
{
int var6 = this.getFlowDecay(par1World, par2, par3, par4);
if (var6 < 0)
{
return par5;
}
else
{
if (var6 == 0)
{
++this.numAdjacentSources;
}
if (var6 >= 8)
{
var6 = 0;
}
return par5 >= 0 && var6 >= par5 ? par5 : var6;
}
}
/**
* Returns true if the block at the coordinates can be displaced by the liquid.
*/
private boolean liquidCanDisplaceBlock(World par1World, int par2, int par3, int par4)
{
Material var5 = par1World.getBlockMaterial(par2, par3, par4);
return var5 == this.blockMaterial ? false : (var5 == Material.lava ? false : !this.blockBlocksFlow(par1World, par2, par3, par4));
}
@Override
public void onBlockAdded(World par1World, int par2, int par3, int par4)
{
super.onBlockAdded(par1World, par2, par3, par4);
if (par1World.getBlockId(par2, par3, par4) == this.blockID)
{
par1World.scheduleBlockUpdate(par2, par3, par4, this.blockID, this.tickRate(par1World));
}
}
}
| true | true | public void updateTick(World par1World, int par2, int par3, int par4, Random par5Random)
{
int var6 = this.getFlowDecay(par1World, par2, par3, par4);
byte var7 = 1;
if (this.blockMaterial == Material.lava /*&& !par1World.provider.isHellWorld*/)
{
var7 = 2;
}
boolean var8 = true;
int var10;
if (var6 > 0)
{
byte var9 = -100;
this.numAdjacentSources = 0;
int var12 = this.getSmallestFlowDecay(par1World, par2 - 1, par3, par4, var9);
var12 = this.getSmallestFlowDecay(par1World, par2 + 1, par3, par4, var12);
var12 = this.getSmallestFlowDecay(par1World, par2, par3, par4 - 1, var12);
var12 = this.getSmallestFlowDecay(par1World, par2, par3, par4 + 1, var12);
var10 = var12 + var7;
if (var10 >= 8 || var12 < 0)
{
var10 = -1;
}
if (this.getFlowDecay(par1World, par2, par3 + 1, par4) >= 0)
{
int var11 = this.getFlowDecay(par1World, par2, par3 + 1, par4);
if (var11 >= 8)
{
var10 = var11;
}
else
{
var10 = var11 + 8;
}
}
if (this.numAdjacentSources >= 2 && this.blockMaterial == Material.water)
{
if (par1World.getBlockMaterial(par2, par3 - 1, par4).isSolid())
{
var10 = 0;
}
else if (par1World.getBlockMaterial(par2, par3 - 1, par4) == this.blockMaterial && par1World.getBlockMetadata(par2, par3, par4) == 0)
{
var10 = 0;
}
}
if (this.blockMaterial == Material.lava && var6 < 8 && var10 < 8 && var10 > var6 && par5Random.nextInt(4) != 0)
{
var10 = var6;
var8 = false;
}
if (var10 == var6)
{
if (var8)
{
this.updateFlow(par1World, par2, par3, par4);
}
}
else
{
var6 = var10;
if (var10 < 0)
{
par1World.setBlockToAir(par2, par3, par4);
}
else
{
par1World.setBlockMetadataWithNotify(par2, par3, par4, var10, 2);
par1World.scheduleBlockUpdate(par2, par3, par4, this.blockID, this.tickRate(par1World));
par1World.notifyBlocksOfNeighborChange(par2, par3, par4, this.blockID);
}
}
}
else
{
this.updateFlow(par1World, par2, par3, par4);
}
if (this.liquidCanDisplaceBlock(par1World, par2, par3 - 1, par4))
{
if (this.blockMaterial == Material.lava && par1World.getBlockMaterial(par2, par3 - 1, par4) == Material.water)
{
par1World.setBlock(par2, par3 - 1, par4, Block.stone.blockID, 0, 2);
this.triggerLavaMixEffects(par1World, par2, par3 - 1, par4);
return;
}
if (var6 >= 8)
{
this.flowIntoBlock(par1World, par2, par3 - 1, par4, var6);
}
else
{
this.flowIntoBlock(par1World, par2, par3 - 1, par4, var6 + 8);
}
}
else if (var6 >= 0 && (var6 == 0 || this.blockBlocksFlow(par1World, par2, par3 - 1, par4)))
{
boolean[] var13 = this.getOptimalFlowDirections(par1World, par2, par3, par4);
var10 = var6 + var7;
if (var6 >= 8)
{
var10 = 1;
}
if (var10 >= 8)
{
return;
}
if (var13[0])
{
this.flowIntoBlock(par1World, par2 - 1, par3, par4, var10);
}
if (var13[1])
{
this.flowIntoBlock(par1World, par2 + 1, par3, par4, var10);
}
if (var13[2])
{
this.flowIntoBlock(par1World, par2, par3, par4 - 1, var10);
}
if (var13[3])
{
this.flowIntoBlock(par1World, par2, par3, par4 + 1, var10);
}
}
}
| public void updateTick(World par1World, int par2, int par3, int par4, Random par5Random)
{
int var6 = this.getFlowDecay(par1World, par2, par3, par4);
byte var7 = 1;
if (this.blockMaterial == Material.lava /*&& !par1World.provider.isHellWorld*/)
{
var7 = 2;
}
boolean var8 = true;
int var10;
if (var6 > 0)
{
byte var9 = -100;
this.numAdjacentSources = 0;
int var12 = this.getSmallestFlowDecay(par1World, par2 - 1, par3, par4, var9);
var12 = this.getSmallestFlowDecay(par1World, par2 + 1, par3, par4, var12);
var12 = this.getSmallestFlowDecay(par1World, par2, par3, par4 - 1, var12);
var12 = this.getSmallestFlowDecay(par1World, par2, par3, par4 + 1, var12);
var10 = var12 + var7;
if (var10 >= 8 || var12 < 0)
{
var10 = -1;
}
if (this.getFlowDecay(par1World, par2, par3 + 1, par4) >= 0)
{
int var11 = this.getFlowDecay(par1World, par2, par3 + 1, par4);
if (var11 >= 8)
{
var10 = var11;
}
else
{
var10 = var11 + 8;
}
}
if (this.numAdjacentSources >= 2 && this.blockMaterial == Material.water)
{
if (par1World.getBlockMaterial(par2, par3 - 1, par4).isSolid())
{
var10 = 0;
}
else if (par1World.getBlockMaterial(par2, par3 - 1, par4) == this.blockMaterial && par1World.getBlockMetadata(par2, par3 - 1, par4) == 0)
{
var10 = 0;
}
}
if (this.blockMaterial == Material.lava && var6 < 8 && var10 < 8 && var10 > var6 && par5Random.nextInt(4) != 0)
{
var10 = var6;
var8 = false;
}
if (var10 == var6)
{
if (var8)
{
this.updateFlow(par1World, par2, par3, par4);
}
}
else
{
var6 = var10;
if (var10 < 0)
{
par1World.setBlockToAir(par2, par3, par4);
}
else
{
par1World.setBlockMetadataWithNotify(par2, par3, par4, var10, 2);
par1World.scheduleBlockUpdate(par2, par3, par4, this.blockID, this.tickRate(par1World));
par1World.notifyBlocksOfNeighborChange(par2, par3, par4, this.blockID);
}
}
}
else
{
this.updateFlow(par1World, par2, par3, par4);
}
if (this.liquidCanDisplaceBlock(par1World, par2, par3 - 1, par4))
{
if (this.blockMaterial == Material.lava && par1World.getBlockMaterial(par2, par3 - 1, par4) == Material.water)
{
par1World.setBlock(par2, par3 - 1, par4, Block.stone.blockID, 0, 2);
this.triggerLavaMixEffects(par1World, par2, par3 - 1, par4);
return;
}
if (var6 >= 8)
{
this.flowIntoBlock(par1World, par2, par3 - 1, par4, var6);
}
else
{
this.flowIntoBlock(par1World, par2, par3 - 1, par4, var6 + 8);
}
}
else if (var6 >= 0 && (var6 == 0 || this.blockBlocksFlow(par1World, par2, par3 - 1, par4)))
{
boolean[] var13 = this.getOptimalFlowDirections(par1World, par2, par3, par4);
var10 = var6 + var7;
if (var6 >= 8)
{
var10 = 1;
}
if (var10 >= 8)
{
return;
}
if (var13[0])
{
this.flowIntoBlock(par1World, par2 - 1, par3, par4, var10);
}
if (var13[1])
{
this.flowIntoBlock(par1World, par2 + 1, par3, par4, var10);
}
if (var13[2])
{
this.flowIntoBlock(par1World, par2, par3, par4 - 1, var10);
}
if (var13[3])
{
this.flowIntoBlock(par1World, par2, par3, par4 + 1, var10);
}
}
}
|
diff --git a/src/org/odk/collect/android/widgets/DecimalWidget.java b/src/org/odk/collect/android/widgets/DecimalWidget.java
index db2eb31..0d77d19 100644
--- a/src/org/odk/collect/android/widgets/DecimalWidget.java
+++ b/src/org/odk/collect/android/widgets/DecimalWidget.java
@@ -1,94 +1,103 @@
/*
* Copyright (C) 2009 University of Washington
*
* 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.odk.collect.android.widgets;
import java.text.NumberFormat;
import org.javarosa.core.model.data.DecimalData;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.form.api.FormEntryPrompt;
import android.content.Context;
import android.text.InputFilter;
import android.text.InputType;
import android.text.method.DigitsKeyListener;
import android.util.TypedValue;
/**
* A widget that restricts values to floating point numbers.
*
* @author Carl Hartung ([email protected])
*/
public class DecimalWidget extends StringWidget {
public DecimalWidget(Context context, FormEntryPrompt prompt) {
super(context, prompt);
// formatting
mAnswer.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
mAnswer.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
// needed to make long readonly text scroll
mAnswer.setHorizontallyScrolling(false);
mAnswer.setSingleLine(false);
// only numbers are allowed
mAnswer.setKeyListener(new DigitsKeyListener(true, true));
// only 15 characters allowed
InputFilter[] fa = new InputFilter[1];
fa[0] = new InputFilter.LengthFilter(15);
mAnswer.setFilters(fa);
Double d = null;
if (prompt.getAnswerValue() != null) {
- d = (Double) prompt.getAnswerValue().getValue();
+ if (prompt.getAnswerValue().getValue() instanceof Integer){
+ d = new Double(((Integer)prompt.getAnswerValue().getValue()).intValue());
+ } else {
+ d = (Double) prompt.getAnswerValue().getValue();
+ }
}
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(15);
nf.setMaximumIntegerDigits(15);
nf.setGroupingUsed(false);
if (d != null) {
- Double dAnswer = (Double) prompt.getAnswerValue().getValue();
+ Double dAnswer;
+ if (prompt.getAnswerValue().getValue() instanceof Integer){
+ dAnswer = new Double(((Integer)prompt.getAnswerValue().getValue()).intValue());
+ } else {
+ dAnswer = (Double) prompt.getAnswerValue().getValue();
+ }
String dString = nf.format(dAnswer);
d = Double.parseDouble(dString.replace(',', '.'));
mAnswer.setText(d.toString());
}
// disable if read only
if (prompt.isReadOnly()) {
setBackgroundDrawable(null);
setFocusable(false);
setClickable(false);
}
}
@Override
public IAnswerData getAnswer() {
String s = mAnswer.getText().toString();
if (s == null || s.equals("")) {
return null;
} else {
try {
return new DecimalData(Double.valueOf(s).doubleValue());
} catch (Exception NumberFormatException) {
return null;
}
}
}
}
| false | true | public DecimalWidget(Context context, FormEntryPrompt prompt) {
super(context, prompt);
// formatting
mAnswer.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
mAnswer.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
// needed to make long readonly text scroll
mAnswer.setHorizontallyScrolling(false);
mAnswer.setSingleLine(false);
// only numbers are allowed
mAnswer.setKeyListener(new DigitsKeyListener(true, true));
// only 15 characters allowed
InputFilter[] fa = new InputFilter[1];
fa[0] = new InputFilter.LengthFilter(15);
mAnswer.setFilters(fa);
Double d = null;
if (prompt.getAnswerValue() != null) {
d = (Double) prompt.getAnswerValue().getValue();
}
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(15);
nf.setMaximumIntegerDigits(15);
nf.setGroupingUsed(false);
if (d != null) {
Double dAnswer = (Double) prompt.getAnswerValue().getValue();
String dString = nf.format(dAnswer);
d = Double.parseDouble(dString.replace(',', '.'));
mAnswer.setText(d.toString());
}
// disable if read only
if (prompt.isReadOnly()) {
setBackgroundDrawable(null);
setFocusable(false);
setClickable(false);
}
}
| public DecimalWidget(Context context, FormEntryPrompt prompt) {
super(context, prompt);
// formatting
mAnswer.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
mAnswer.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
// needed to make long readonly text scroll
mAnswer.setHorizontallyScrolling(false);
mAnswer.setSingleLine(false);
// only numbers are allowed
mAnswer.setKeyListener(new DigitsKeyListener(true, true));
// only 15 characters allowed
InputFilter[] fa = new InputFilter[1];
fa[0] = new InputFilter.LengthFilter(15);
mAnswer.setFilters(fa);
Double d = null;
if (prompt.getAnswerValue() != null) {
if (prompt.getAnswerValue().getValue() instanceof Integer){
d = new Double(((Integer)prompt.getAnswerValue().getValue()).intValue());
} else {
d = (Double) prompt.getAnswerValue().getValue();
}
}
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(15);
nf.setMaximumIntegerDigits(15);
nf.setGroupingUsed(false);
if (d != null) {
Double dAnswer;
if (prompt.getAnswerValue().getValue() instanceof Integer){
dAnswer = new Double(((Integer)prompt.getAnswerValue().getValue()).intValue());
} else {
dAnswer = (Double) prompt.getAnswerValue().getValue();
}
String dString = nf.format(dAnswer);
d = Double.parseDouble(dString.replace(',', '.'));
mAnswer.setText(d.toString());
}
// disable if read only
if (prompt.isReadOnly()) {
setBackgroundDrawable(null);
setFocusable(false);
setClickable(false);
}
}
|
diff --git a/src/examples/api/document-markup/src/main/java/org/apache/commons/digester3/examples/api/documentmarkup/MarkupDigester.java b/src/examples/api/document-markup/src/main/java/org/apache/commons/digester3/examples/api/documentmarkup/MarkupDigester.java
index a57c320d..a4209ed6 100644
--- a/src/examples/api/document-markup/src/main/java/org/apache/commons/digester3/examples/api/documentmarkup/MarkupDigester.java
+++ b/src/examples/api/document-markup/src/main/java/org/apache/commons/digester3/examples/api/documentmarkup/MarkupDigester.java
@@ -1,164 +1,164 @@
package org.apache.commons.digester3.examples.api.documentmarkup;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import org.apache.commons.digester3.Digester;
import org.apache.commons.digester3.Rule;
import java.util.List;
import javax.xml.parsers.SAXParser;
import org.xml.sax.XMLReader;
import org.xml.sax.SAXException;
import org.xml.sax.Attributes;
/**
* This is a subclass of digester which supports rules which implement
* the TextSegmentHandler interface, causing the "textSegment" method
* on each matching rule (of the appropriate type) to be invoked when
* an element contains a segment of text followed by a child element.
* <p>
* See the readme file included with this example for more information.
*/
public class MarkupDigester
extends Digester
{
/** See equivalent constructor in Digester class. */
public MarkupDigester()
{
}
/** See equivalent constructor in Digester class. */
public MarkupDigester( SAXParser parser )
{
super( parser );
}
/** See equivalent constructor in Digester class. */
public MarkupDigester( XMLReader reader )
{
super( reader );
}
//===================================================================
/**
* The text found in the current element since the last child element.
*/
protected StringBuilder currTextSegment = new StringBuilder();
/**
* Process notification of character data received from the body of
* an XML element.
*
* @param buffer The characters from the XML document
* @param start Starting offset into the buffer
* @param length Number of characters from the buffer
*
* @exception SAXException if a parsing error is to be reported
*/
@Override
public void characters( char buffer[], int start, int length )
throws SAXException
{
super.characters( buffer, start, length );
currTextSegment.append( buffer, start, length );
}
/**
* Process notification of the start of an XML element being reached.
*
* @param namespaceURI The Namespace URI, or the empty string if the element
* has no Namespace URI or if Namespace processing is not being performed.
* @param localName The local name (without prefix), or the empty
* string if Namespace processing is not being performed.
* @param qName The qualified name (with prefix), or the empty
* string if qualified names are not available.
* @param list The attributes attached to the element. If there are
* no attributes, it shall be an empty Attributes object.
* @exception SAXException if a parsing error is to be reported
*/
@Override
public void startElement( String namespaceURI, String localName, String qName, Attributes list )
throws SAXException
{
handleTextSegments();
// Unlike bodyText, which accumulates despite intervening child
// elements, currTextSegment gets cleared here. This means that
// we don't need to save it on a stack either.
currTextSegment.setLength( 0 );
super.startElement( namespaceURI, localName, qName, list );
}
/**
* Process notification of the end of an XML element being reached.
*
* @param namespaceURI - The Namespace URI, or the empty string if the
* element has no Namespace URI or if Namespace processing is not
* being performed.
* @param localName - The local name (without prefix), or the empty
* string if Namespace processing is not being performed.
* @param qName - The qualified XML 1.0 name (with prefix), or the
* empty string if qualified names are not available.
* @exception SAXException if a parsing error is to be reported
*/
@Override
public void endElement( String namespaceURI, String localName, String qName )
throws SAXException
{
handleTextSegments();
currTextSegment.setLength( 0 );
super.endElement( namespaceURI, localName, qName );
}
/**
* Iterate over the list of rules most recently matched, and
* if any of them implement the TextSegmentHandler interface then
* invoke that rule's textSegment method passing the current
* segment of text from the xml element body.
*/
private void handleTextSegments()
throws SAXException
{
if ( currTextSegment.length() > 0 )
{
String segment = currTextSegment.toString();
- List parentMatches = (List) matches.peek();
+ List<Rule> parentMatches = getMatches().peek();
int len = parentMatches.size();
for ( int i = 0; i < len; ++i )
{
- Rule r = (Rule) parentMatches.get( i );
+ Rule r = parentMatches.get( i );
if ( r instanceof TextSegmentHandler )
{
TextSegmentHandler h = (TextSegmentHandler) r;
try
{
h.textSegment( segment );
}
catch ( Exception e )
{
throw createSAXException( e );
}
}
}
}
}
}
| false | true | private void handleTextSegments()
throws SAXException
{
if ( currTextSegment.length() > 0 )
{
String segment = currTextSegment.toString();
List parentMatches = (List) matches.peek();
int len = parentMatches.size();
for ( int i = 0; i < len; ++i )
{
Rule r = (Rule) parentMatches.get( i );
if ( r instanceof TextSegmentHandler )
{
TextSegmentHandler h = (TextSegmentHandler) r;
try
{
h.textSegment( segment );
}
catch ( Exception e )
{
throw createSAXException( e );
}
}
}
}
}
| private void handleTextSegments()
throws SAXException
{
if ( currTextSegment.length() > 0 )
{
String segment = currTextSegment.toString();
List<Rule> parentMatches = getMatches().peek();
int len = parentMatches.size();
for ( int i = 0; i < len; ++i )
{
Rule r = parentMatches.get( i );
if ( r instanceof TextSegmentHandler )
{
TextSegmentHandler h = (TextSegmentHandler) r;
try
{
h.textSegment( segment );
}
catch ( Exception e )
{
throw createSAXException( e );
}
}
}
}
}
|
diff --git a/model/org/eclipse/cdt/internal/core/settings/model/ResourceChangeHandler.java b/model/org/eclipse/cdt/internal/core/settings/model/ResourceChangeHandler.java
index b7f2d6793..3de2bd5f0 100644
--- a/model/org/eclipse/cdt/internal/core/settings/model/ResourceChangeHandler.java
+++ b/model/org/eclipse/cdt/internal/core/settings/model/ResourceChangeHandler.java
@@ -1,329 +1,332 @@
/*******************************************************************************
* Copyright (c) 2007, 2010 Intel Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Intel Corporation - Initial API and implementation
* Broadcom Corporation - Bug 311189 and clean-up
*******************************************************************************/
package org.eclipse.cdt.internal.core.settings.model;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.settings.model.ICConfigurationDescription;
import org.eclipse.cdt.core.settings.model.ICProjectDescription;
import org.eclipse.cdt.core.settings.model.ICProjectDescriptionManager;
import org.eclipse.cdt.core.settings.model.ICResourceDescription;
import org.eclipse.cdt.core.settings.model.ICSourceEntry;
import org.eclipse.cdt.core.settings.model.WriteAccessException;
import org.eclipse.cdt.core.settings.model.util.CDataUtil;
import org.eclipse.cdt.core.settings.model.util.ResourceChangeHandlerBase;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.resources.ISaveContext;
import org.eclipse.core.resources.ISaveParticipant;
import org.eclipse.core.resources.IWorkspaceRunnable;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
/**
* This resource change handler notices external changes to the cdt projects
* and associated project storage metadata files, as well as changes to
* source folders
*
* Notifies CProjectDescriptionManager on some events, in particular project close and remove
*/
public class ResourceChangeHandler extends ResourceChangeHandlerBase implements ISaveParticipant {
/**
* A resource move handler which updates the model when C model resources are moved / removed.
* It's responsible for:
* - Handling project description update after a project move
* - Noticing the removal of directories that correspond to SourceEntrys
* - Removing resource specific configuration from removed removed files and folders
*
* It records changes made during an IResourceChangeEvent for subsequent update to the model. This
* is performed in a WorkspaceJob to ensure we don't remove model entries while many changes are in
* progress as part of a team operation. See also Bug 311189
*/
private static class RcMoveHandler implements IResourceMoveHandler {
CProjectDescriptionManager fMngr = CProjectDescriptionManager.getInstance();
/** Map of modified project descriptions to update */
Map<IProject, ICProjectDescription> fProjDesMap = new HashMap<IProject, ICProjectDescription>();
/** Set of removed resources */
Collection<IProject> fRemovedProjects = new HashSet<IProject>();
/** Map of moved & removed resources: 'from' -> 'to'; 'to' may be null for removed resources */
Map<IResource, IResource> fMovedResources = new HashMap<IResource, IResource>();
public void handleProjectClose(IProject project) {
fMngr.projectClosedRemove(project);
}
/**
* Check and return a new ICSourceEntry[] when a path has been changed in a project
* @param fromFullPath
* @param toFullPath
* @param entries - source entries to check
* @return ICSourceEntry[] or null if no change to the source entries
*/
private ICSourceEntry[] checkMove(IPath fromFullPath, IPath toFullPath, ICSourceEntry[] entries){
boolean modified = false;
for(int k = 0; k < entries.length; k++){
if(entries[k].getFullPath().equals(fromFullPath)){
ICSourceEntry entry = entries[k];
entries[k] = (ICSourceEntry)CDataUtil.createEntry(entry.getKind(), toFullPath.toString(), null, entry.getExclusionPatterns(), entry.getFlags());
modified = true;
}
}
return modified ? entries : null;
}
/**
* Check and return a new ICSourceEntry[] which doesn't contain rcFullPath as a source path
* @param rcFullPath - that path being removed
* @param entries - source entries to check
* @return ICSourceEntry[] or null if no change
*/
private ICSourceEntry[] checkRemove(IPath rcFullPath, ICSourceEntry[] entries) {
List<ICSourceEntry> updatedList = null;
int num = 0;
for (ICSourceEntry entrie : entries) {
if(entrie.getFullPath().equals(rcFullPath)){
if(updatedList == null){
updatedList = new ArrayList<ICSourceEntry>(Arrays.asList(entries));
}
updatedList.remove(num);
} else {
num++;
}
}
return updatedList != null ? updatedList.toArray(new ICSourceEntry[updatedList.size()]) : null;
}
public boolean handleResourceMove(IResource fromRc, IResource toRc) {
boolean proceed = true;
IProject fromProject = fromRc.getProject();
IProject toProject = toRc.getProject();
switch(toRc.getType()){
case IResource.PROJECT:{
ICProjectDescription des = fMngr.projectMove(fromProject, toProject);
fRemovedProjects.add(fromProject);
if(des != null)
fProjDesMap.put(toProject, des);
}
break;
case IResource.FOLDER:
case IResource.FILE:
// Only handle move in the same project
// TODO: should we treat this as a remove?
if (!toProject.equals(fromProject))
break;
// If path hasn't changed, nothing to do
if (fromRc.getFullPath().equals(toRc.getFullPath()))
break;
fMovedResources.put(fromRc, toRc);
break;
}
return proceed;
}
private ICProjectDescription getProjectDescription(IResource rc) {
IProject project = rc.getProject();
ICProjectDescription des = fProjDesMap.get(project);
if(des == null && !fProjDesMap.containsKey(project)){
int flags = 0;
flags |= CProjectDescriptionManager.INTERNAL_GET_IGNORE_CLOSE;
flags |= ICProjectDescriptionManager.GET_WRITABLE;
des = fMngr.getProjectDescription(project, flags);
if(des != null)
fProjDesMap.put(project, des);
}
return des;
}
public boolean handleResourceRemove(IResource rc) {
boolean proceed = true;
IProject project = rc.getProject();
switch(rc.getType()){
case IResource.PROJECT:
fMngr.projectClosedRemove(project);
fRemovedProjects.add(project);
proceed = false;
break;
case IResource.FOLDER:
case IResource.FILE:
if (project.isAccessible())
fMovedResources.put(rc, null);
break;
}
return proceed;
}
public void done() {
// If the resource's project was moved / removed, don't consider the path for source entry removal
for (Iterator<IResource> it = fMovedResources.keySet().iterator(); it.hasNext() ; ) {
if (fRemovedProjects.contains(it.next().getProject()))
it.remove();
}
if (fMovedResources.isEmpty() && fProjDesMap.isEmpty())
return;
// Handle moved and removed resources
// - reconciles both source-entry move & remove
// - resource configuration move & remove
// Run it in the Workspace, so we don't trip Bug 311189
CProjectDescriptionManager.runWspModification(new IWorkspaceRunnable(){
public void run(IProgressMonitor monitor) throws CoreException {
for (Map.Entry<IResource, IResource> entry : fMovedResources.entrySet()) {
IResource from = entry.getKey();
IResource to = entry.getValue();
// TODO: don't handle moves to a different project
assert(to == null || to.getProject().equals(from.getProject()));
// Bug 311189 -- if the resource still exists now, don't treat as a remove!
- if (to == null && from.exists())
- continue;
+ if (to == null) {
+ from.refreshLocal(IResource.DEPTH_ZERO, null);
+ if (from.exists())
+ continue;
+ }
ICProjectDescription prjDesc = getProjectDescription(from);
if (prjDesc == null)
continue;
for (ICConfigurationDescription cfg : prjDesc.getConfigurations()) {
try {
// Handle source entry change
if (from instanceof IFolder) {
ICSourceEntry[] entries = cfg.getSourceEntries();
if (to != null)
entries = checkMove(from.getFullPath(), to.getFullPath(), entries);
else
entries = checkRemove(from.getFullPath(), entries);
// Update if there have been any changes
if(entries != null)
cfg.setSourceEntries(entries);
}
// We deliberately don't remove output entries. These directories may not exist when
// the project is created and may be deleted at during a normal project lifecycle
// Handle resource description change
ICResourceDescription rcDescription = cfg.getResourceDescription(from.getProjectRelativePath(), true);
if(rcDescription != null)
if (to != null)
rcDescription.setPath(to.getProjectRelativePath());
else
cfg.removeResourceDescription(rcDescription);
} catch (WriteAccessException e) {
CCorePlugin.log(e);
} catch (CoreException e) {
CCorePlugin.log(e);
}
}
}
fMovedResources.clear();
// Save all the changed project descriptions
for (Entry<IProject, ICProjectDescription> entry : fProjDesMap.entrySet()) {
if(!entry.getKey().isAccessible())
continue;
try {
fMngr.setProjectDescription(entry.getKey(), entry.getValue());
} catch (CoreException e) {
CCorePlugin.log(e);
}
}
}
}, new NullProgressMonitor());
}
}
@Override
protected IResourceMoveHandler createResourceMoveHandler(
IResourceChangeEvent event) {
return new RcMoveHandler();
}
/*
* I S a v e P a r t i c i p a n t
*/
/* (non-Javadoc)
* @see org.eclipse.core.resources.ISaveParticipant#saving(org.eclipse.core.resources.ISaveContext)
*/
public void saving(ISaveContext context) throws CoreException {
//Request a resource delta to be used on next activation.
context.needDelta();
}
/* (non-Javadoc)
* @see org.eclipse.core.resources.ISaveParticipant#doneSaving(org.eclipse.core.resources.ISaveContext)
*/
public void doneSaving(ISaveContext context) {
}
/* (non-Javadoc)
* @see org.eclipse.core.resources.ISaveParticipant#prepareToSave(org.eclipse.core.resources.ISaveContext)
*/
public void prepareToSave(ISaveContext context) throws CoreException {
}
/* (non-Javadoc)
* @see org.eclipse.core.resources.ISaveParticipant#rollback(org.eclipse.core.resources.ISaveContext)
*/
public void rollback(ISaveContext context) {
}
@Override
protected void doHandleResourceMove(IResourceChangeEvent event,
IResourceMoveHandler handler) {
switch(event.getType()){
case IResourceChangeEvent.POST_CHANGE:
IResourceDelta delta = event.getDelta();
if(delta != null){
IResourceDelta projs[] = delta.getAffectedChildren();
for (IResourceDelta proj : projs) {
IResourceDelta projDelta = proj;
if(!shouldVisit((IProject)projDelta.getResource()))
continue;
if((projDelta.getKind() & IResourceDelta.REMOVED) == IResourceDelta.REMOVED)
continue;
IResourceDelta children[] = projDelta.getAffectedChildren();
for (IResourceDelta child : children) {
IResource rc = child.getResource();
if(rc.getType() != IResource.FILE)
continue;
}
}
}
break;
}
super.doHandleResourceMove(event, handler);
}
}
| true | true | public void done() {
// If the resource's project was moved / removed, don't consider the path for source entry removal
for (Iterator<IResource> it = fMovedResources.keySet().iterator(); it.hasNext() ; ) {
if (fRemovedProjects.contains(it.next().getProject()))
it.remove();
}
if (fMovedResources.isEmpty() && fProjDesMap.isEmpty())
return;
// Handle moved and removed resources
// - reconciles both source-entry move & remove
// - resource configuration move & remove
// Run it in the Workspace, so we don't trip Bug 311189
CProjectDescriptionManager.runWspModification(new IWorkspaceRunnable(){
public void run(IProgressMonitor monitor) throws CoreException {
for (Map.Entry<IResource, IResource> entry : fMovedResources.entrySet()) {
IResource from = entry.getKey();
IResource to = entry.getValue();
// TODO: don't handle moves to a different project
assert(to == null || to.getProject().equals(from.getProject()));
// Bug 311189 -- if the resource still exists now, don't treat as a remove!
if (to == null && from.exists())
continue;
ICProjectDescription prjDesc = getProjectDescription(from);
if (prjDesc == null)
continue;
for (ICConfigurationDescription cfg : prjDesc.getConfigurations()) {
try {
// Handle source entry change
if (from instanceof IFolder) {
ICSourceEntry[] entries = cfg.getSourceEntries();
if (to != null)
entries = checkMove(from.getFullPath(), to.getFullPath(), entries);
else
entries = checkRemove(from.getFullPath(), entries);
// Update if there have been any changes
if(entries != null)
cfg.setSourceEntries(entries);
}
// We deliberately don't remove output entries. These directories may not exist when
// the project is created and may be deleted at during a normal project lifecycle
// Handle resource description change
ICResourceDescription rcDescription = cfg.getResourceDescription(from.getProjectRelativePath(), true);
if(rcDescription != null)
if (to != null)
rcDescription.setPath(to.getProjectRelativePath());
else
cfg.removeResourceDescription(rcDescription);
} catch (WriteAccessException e) {
CCorePlugin.log(e);
} catch (CoreException e) {
CCorePlugin.log(e);
}
}
}
fMovedResources.clear();
// Save all the changed project descriptions
for (Entry<IProject, ICProjectDescription> entry : fProjDesMap.entrySet()) {
if(!entry.getKey().isAccessible())
continue;
try {
fMngr.setProjectDescription(entry.getKey(), entry.getValue());
} catch (CoreException e) {
CCorePlugin.log(e);
}
}
}
}, new NullProgressMonitor());
}
| public void done() {
// If the resource's project was moved / removed, don't consider the path for source entry removal
for (Iterator<IResource> it = fMovedResources.keySet().iterator(); it.hasNext() ; ) {
if (fRemovedProjects.contains(it.next().getProject()))
it.remove();
}
if (fMovedResources.isEmpty() && fProjDesMap.isEmpty())
return;
// Handle moved and removed resources
// - reconciles both source-entry move & remove
// - resource configuration move & remove
// Run it in the Workspace, so we don't trip Bug 311189
CProjectDescriptionManager.runWspModification(new IWorkspaceRunnable(){
public void run(IProgressMonitor monitor) throws CoreException {
for (Map.Entry<IResource, IResource> entry : fMovedResources.entrySet()) {
IResource from = entry.getKey();
IResource to = entry.getValue();
// TODO: don't handle moves to a different project
assert(to == null || to.getProject().equals(from.getProject()));
// Bug 311189 -- if the resource still exists now, don't treat as a remove!
if (to == null) {
from.refreshLocal(IResource.DEPTH_ZERO, null);
if (from.exists())
continue;
}
ICProjectDescription prjDesc = getProjectDescription(from);
if (prjDesc == null)
continue;
for (ICConfigurationDescription cfg : prjDesc.getConfigurations()) {
try {
// Handle source entry change
if (from instanceof IFolder) {
ICSourceEntry[] entries = cfg.getSourceEntries();
if (to != null)
entries = checkMove(from.getFullPath(), to.getFullPath(), entries);
else
entries = checkRemove(from.getFullPath(), entries);
// Update if there have been any changes
if(entries != null)
cfg.setSourceEntries(entries);
}
// We deliberately don't remove output entries. These directories may not exist when
// the project is created and may be deleted at during a normal project lifecycle
// Handle resource description change
ICResourceDescription rcDescription = cfg.getResourceDescription(from.getProjectRelativePath(), true);
if(rcDescription != null)
if (to != null)
rcDescription.setPath(to.getProjectRelativePath());
else
cfg.removeResourceDescription(rcDescription);
} catch (WriteAccessException e) {
CCorePlugin.log(e);
} catch (CoreException e) {
CCorePlugin.log(e);
}
}
}
fMovedResources.clear();
// Save all the changed project descriptions
for (Entry<IProject, ICProjectDescription> entry : fProjDesMap.entrySet()) {
if(!entry.getKey().isAccessible())
continue;
try {
fMngr.setProjectDescription(entry.getKey(), entry.getValue());
} catch (CoreException e) {
CCorePlugin.log(e);
}
}
}
}, new NullProgressMonitor());
}
|
diff --git a/jfunk-web/src/main/java/com/mgmtp/jfunk/web/util/WebDriverTool.java b/jfunk-web/src/main/java/com/mgmtp/jfunk/web/util/WebDriverTool.java
index 119f16a..6dff7ae 100644
--- a/jfunk-web/src/main/java/com/mgmtp/jfunk/web/util/WebDriverTool.java
+++ b/jfunk-web/src/main/java/com/mgmtp/jfunk/web/util/WebDriverTool.java
@@ -1,711 +1,711 @@
/*
* Copyright (c) 2013 mgm technology partners GmbH
*
* 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.mgmtp.jfunk.web.util;
import static com.google.common.collect.Iterables.getOnlyElement;
import static com.google.common.collect.Sets.difference;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.UUID;
import javax.inject.Inject;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.NotFoundException;
import org.openqa.selenium.SearchContext;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.Sets.SetView;
import com.mgmtp.jfunk.common.util.JFunkUtils;
import com.mgmtp.jfunk.data.DataSet;
/**
* <p>
* Utility class for enhancing {@link WebDriver} functionality. Uses {@link WebElementFinder} and {@link FormInputHandler}
* internally and thus can handle timeouts implicitly.
* </p>
* <p>
* An script-scoped instance of this class can be retrieve via dependency injection.
* </p>
*
* @author rnaegele
* @since 3.1
*/
public class WebDriverTool implements SearchContext {
protected final Logger logger = LoggerFactory.getLogger(getClass());
private static final String APPEND_OPEN_WINDOW_LINK_SCRIPT_TEMPLATE = "(function() { "
+ "var jFunkAnchorTag = document.createElement('a');"
+ "jFunkAnchorTag.appendChild(document.createTextNode('jfunk-new-window-link'));"
+ "jFunkAnchorTag.setAttribute('id', '%s');"
+ "jFunkAnchorTag.setAttribute('href', '%s');"
+ "jFunkAnchorTag.setAttribute('target', '_blank');"
+ "jFunkAnchorTag.setAttribute('style', 'display:block; z-index: 100000; position: relative;');"
+ "document.getElementsByTagName('body')[0].appendChild(jFunkAnchorTag);"
+ "}());";
private static final String REMOVE_OPEN_WINDOW_LINK_SCRIPT_TEMPLATE = "(function() { "
+ "var jFunkAnchorTag = document.getElementById('%s');"
+ "jFunkAnchorTag.parentNode.removeChild(jFunkAnchorTag);"
+ "}());";
private final WebDriver webDriver;
private final WebElementFinder wef;
private final FormInputHandler fih;
private final Map<String, DataSet> dataSets;
@Inject
WebDriverTool(final WebDriver webDriver, final WebElementFinder wef, final FormInputHandler fih,
final Map<String, DataSet> dataSets) {
this.webDriver = webDriver;
this.wef = wef;
this.fih = fih;
this.dataSets = dataSets;
}
public void get(final String url) {
logger.info("GET {}", url);
webDriver.get(url);
}
/**
* Finds the first element. Uses the internal {@link WebElementFinder}.
*
* @param by
* the {@link By} used to locate the element
* @return the element
* @deprecated Use {@link #findElement(By)} instead
*/
@Deprecated
public WebElement find(final By by) {
return findElement(by);
}
/**
* Finds the first element. Uses the internal {@link WebElementFinder}.
*
* @param by
* the {@link By} used to locate the element
* @return the element
*/
@Override
public WebElement findElement(final By by) {
return wef.by(by).find();
}
/**
* Finds the first element. Uses the internal {@link WebElementFinder}, which tries to apply the specified {@code condition}
* until it times out.
*
* @param by
* the {@link By} used to locate the element
* @param condition
* a condition the found element must meet
* @return the element
* @deprecated Use {@link #findElement(By, Predicate)} instead
*/
@Deprecated
public WebElement find(final By by, final Predicate<WebElement> condition) {
return findElement(by, condition);
}
/**
* Finds the first element. Uses the internal {@link WebElementFinder}, which tries to apply the specified {@code condition}
* until it times out.
*
* @param by
* the {@link By} used to locate the element
* @param condition
* a condition the found element must meet
* @return the element
*/
public WebElement findElement(final By by, final Predicate<WebElement> condition) {
return wef.by(by).condition(condition).find();
}
/**
* Finds all elements. Uses the internal {@link WebElementFinder}.
*
* @param by
* the {@link By} used to locate the elements
* @return the list of elements
* @deprecated Use {@link #findElements(By)} instead
*/
@Deprecated
public List<WebElement> findAll(final By by) {
return findElements(by);
}
/**
* Finds all elements. Uses the internal {@link WebElementFinder}.
*
* @param by
* the {@link By} used to locate the elements
* @return the list of elements
*/
@Override
public List<WebElement> findElements(final By by) {
return wef.by(by).findAll();
}
/**
* Finds all elements. Uses the internal {@link WebElementFinder}, which tries to apply the specified {@code condition} until
* it times out.
*
* @param by
* the {@link By} used to locate the element
* @param condition
* a condition the found elements must meet
* @return the list of elements
* @deprecated Use {@link #findElements(By, Predicate)} instead
*/
@Deprecated
public List<WebElement> findAll(final By by, final Predicate<WebElement> condition) {
return findElements(by, condition);
}
/**
* Finds all elements. Uses the internal {@link WebElementFinder}, which tries to apply the specified {@code condition} until
* it times out.
*
* @param by
* the {@link By} used to locate the element
* @param condition
* a condition the found elements must meet
* @return the list of elements
*/
public List<WebElement> findElements(final By by, final Predicate<WebElement> condition) {
return wef.by(by).condition(condition).findAll();
}
/**
* Repeatedly applies the current {@link WebDriver} instance to the specifed function until one of the following occurs:
* <ol>
* <li>the function returns neither null nor false,</li>
* <li>the function throws an unignored exception,</li>
* <li>the timeout expires,
* <li>the current thread is interrupted</li>
* </ol>
*
* @param function
* the function
* @param <V>
* the function's expected return type
* @return the function's return value if the function returned something different from null or false before the timeout
* expired
* @throws TimeoutException
* if the timeout expires.
*/
public <V> V waitFor(final Function<? super WebDriver, V> function) {
return newWebDriverWait().until(function);
}
/**
* Repeatedly applies the current {@link WebDriver} instance to the specifed function until one of the following occurs:
* <ol>
* <li>the function returns neither null nor false,</li>
* <li>the function throws an unignored exception,</li>
* <li>the timeout expires,
* <li>the current thread is interrupted</li>
* </ol>
*
* @param function
* the function
* @param timeoutSeconds
* the timeout in seconds
* @param <V>
* the function's expected return type
* @return the function's return value if the function returned something different from null or false before the timeout
* expired
* @throws TimeoutException
* if the timeout expires.
*/
public <V> V waitFor(final Function<? super WebDriver, V> function, final long timeoutSeconds) {
return newWebDriverWait(timeoutSeconds).until(function);
}
/**
* Repeatedly applies the current {@link WebDriver} instance to the specifed function until one of the following occurs:
* <ol>
* <li>the function returns neither null nor false,</li>
* <li>the function throws an unignored exception,</li>
* <li>the timeout expires,
* <li>the current thread is interrupted</li>
* </ol>
* The method uses the same timeout and milliseconds to sleep between polls as the internally used default
* {@link WebElementFinder} instance
*
* @param function
* the function
* @param timeoutSeconds
* the timeout in seconds
* @param sleepMillis
* the time in milliseconds to sleep between polls
* @param <V>
* the function's expected return type
* @return the function's return value if the function returned something different from null or false before the timeout
* expired
* @throws TimeoutException
* if the timeout expires.
*/
public <V> V waitFor(final Function<? super WebDriver, V> function, final long timeoutSeconds, final long sleepMillis) {
return newWebDriverWait(timeoutSeconds, sleepMillis).until(function);
}
/**
* Repeatedly applies the current {@link WebDriver} instance to the specified predicate until the timeout expires or the
* predicate evaluates to true.
*
* @param predicate
* the predicate to wait on
* @throws TimeoutException
* if the timeout expires.
*/
public void waitFor(final Predicate<WebDriver> predicate) {
newWebDriverWait().until(predicate);
}
/**
* Repeatedly applies the current {@link WebDriver} instance to the specified predicate until the timeout expires or the
* predicate evaluates to true.
*
* @param predicate
* the predicate to wait on
* @param timeoutSeconds
* the timeout in seconds
* @throws TimeoutException
* if the timeout expires.
*/
public void waitFor(final Predicate<WebDriver> predicate, final long timeoutSeconds) {
newWebDriverWait(timeoutSeconds).until(predicate);
}
/**
* Repeatedly applies the current {@link WebDriver} instance to the specified predicate until the timeout expires or the
* predicate evaluates to true.
*
* @param predicate
* the predicate to wait on
* @param timeoutSeconds
* the timeout in seconds
* @param sleepMillis
* the time in milliseconds to sleep between polls
* @throws TimeoutException
* if the timeout expires.
*/
public void waitFor(final Predicate<WebDriver> predicate, final long timeoutSeconds, final long sleepMillis) {
newWebDriverWait(timeoutSeconds, sleepMillis).until(predicate);
}
/**
* Creates a new {@link WebDriverWait} with the same timeout and milliseconds to sleep between polls as the internally used
* default {@link WebElementFinder} instance.
*
* @return the newly created {@link WebDriverWait} instance
*/
public WebDriverWait newWebDriverWait() {
return wef.getSleepMillis() > 0L
? newWebDriverWait(wef.getTimeoutSeconds(), wef.getSleepMillis())
: newWebDriverWait(wef.getTimeoutSeconds());
}
/**
* Creates a new {@link WebDriverWait} with the specified timeout.
*
* @param timeoutSeconds
* the timeout in seconds
* @return the newly created {@link WebDriverWait} instance
*/
public WebDriverWait newWebDriverWait(final long timeoutSeconds) {
return new LoggingWebDriverWait(webDriver, timeoutSeconds);
}
/**
* Creates a new {@link WebDriverWait} with the specified timeout and milliseconds to sleep between polls.
*
* @param timeoutSeconds
* the timeout in seconds
* @param sleepMillis
* the time in milliseconds to sleep between polls
* @return the newly created {@link WebDriverWait} instance
*/
public WebDriverWait newWebDriverWait(final long timeoutSeconds, final long sleepMillis) {
return new LoggingWebDriverWait(webDriver, timeoutSeconds, sleepMillis);
}
/**
* Tries to find and element and clicks on it if found. Uses a timeout of two seconds.
*
* @param by
* the {@link By} used to locate the element
* @return {@code true} if the element was found and clicked, {@code false} otherwise
*/
public boolean tryClick(final By by) {
logger.info("Trying to click on {}", by);
List<WebElement> elements = wef.timeout(2L).by(by).findAll();
if (elements.size() > 0) {
elements.get(0).click();
logger.info("Click successful");
return true;
}
logger.info("Click not successful");
return false;
}
/**
* Delegates to {@link #findElement(By)} and calls {@link WebElement#sendKeys(CharSequence...) sendKeys(CharSequence...)} on
* the returned element.
*
* @param by
* the {@link By} used to locate the element
* @param keysToSend
* the keys to send
*/
public void sendKeys(final By by, final CharSequence... keysToSend) {
findElement(by).sendKeys(keysToSend);
}
/**
* Delegates to {@link #findElement(By)} and calls {@link WebElement#clear() clear()} on the returned element.
*
* @param by
* the {@link By} used to locate the element
*/
public void clear(final By by) {
findElement(by).clear();
}
/**
* Delegates to {@link #findElement(By)} and calls {@link WebElement#click() click()} on the returned element.
*
* @param by
* the {@link By} used to locate the element
*/
public void click(final By by) {
findElement(by).click();
}
/**
* Delegates to {@link #findElement(By)} and then performs a context-click using the {@link Actions} class.
*
* @param by
* the {@link By} used to locate the element
*/
public void contextClick(final By by) {
WebElement element = findElement(by);
new Actions(webDriver).contextClick(element).perform();
}
/**
* Delegates to {@link #findElement(By)} and then performs a double-click using the {@link Actions} class.
*
* @param by
* the {@link By} used to locate the element
*/
public void doubleClick(final By by) {
WebElement element = findElement(by);
new Actions(webDriver).doubleClick(element).perform();
}
/**
* Delegates to {@link #findElement(By)} and then moves the mouse to the returned element using the {@link Actions} class.
*
* @param by
* the {@link By} used to locate the element
*/
public void hover(final By by) {
WebElement element = findElement(by);
new Actions(webDriver).moveToElement(element).perform();
}
/**
* Delegates to {@link #findElement(By)}, moves the mouse to the returned element using the {@link Actions} class and then
* tries to find and element using {@code byToAppear} with a timeout of 1 seconds, retrying up to ten times because hovers
* sometimes do not work very reliably.
*
* @param by
* the {@link By} used to locate the element
* @param byToAppear
* the {@link By} used to locate the element that is supposed to appear after hovering
*/
public WebElement hover(final By by, final By byToAppear) {
WebElementFinder finder = wef.timeout(1L, 200L).by(byToAppear);
RuntimeException exception = null;
for (int i = 0; i < 10; ++i) {
try {
WebElement element = findElement(by);
new Actions(webDriver).moveToElement(element).perform();
return finder.find();
} catch (NoSuchElementException ex) {
exception = ex;
} catch (TimeoutException ex) {
exception = ex;
} catch (StaleElementReferenceException ex) {
exception = ex;
}
}
throw exception;
}
/**
* Delegates to {@link #findElement(By)} and then calls {@link WebElement#getAttribute(String) getAttribute(String)} on the
* returned element.
*
* @param by
* the {@link By} used to locate the element
* @param attributeName
* the attribute name
* @return the attribute value
*/
public String getAttributeValue(final By by, final String attributeName) {
WebElement element = findElement(by);
return element.getAttribute(attributeName);
}
/**
* Delegates to {@link #findElement(By)} and then calls {@link WebElement#getCssValue(String) getAttribute(String)} on the
* returned element.
*
* @param by
* the {@link By} used to locate the element
* @param propertyName
* the name of the CSS property
* @return The current, computed value of the property.
*/
public String getCssValue(final By by, final String propertyName) {
WebElement element = findElement(by);
return element.getCssValue(propertyName);
}
/**
* Delegates to {@link #findElement(By)} and then calls {@link WebElement#getText() getText()} on the returned element. The
* element's text is passed to {@link JFunkUtils#normalizeSpace(String)}.
*
* @param by
* the {@link By} used to locate the element
* @return the text
*/
public String getElementText(final By by) {
return getElementText(by, true);
}
/**
* Delegates to {@link #findElement(By)} and then calls {@link WebElement#getText() getText()} on the returned element. If
* {@code normalizeSpace} is {@code true}, the element's text is passed to {@link JFunkUtils#normalizeSpace(String)}.
*
* @param by
* the {@link By} used to locate the element
* @param normalizeSpace
* specifies whether whitespace in the element text are to be normalized
* @return the text
*/
public String getElementText(final By by, final boolean normalizeSpace) {
WebElement element = findElement(by);
String text = element.getText();
return normalizeSpace ? JFunkUtils.normalizeSpace(text) : text;
}
/**
* <p>
* Delegates to {@link #findElement(By)} and then calls {@link WebElement#getAttribute(String) getAttribute("innerText")} on
* the returned element. The element's text is passed to {@link JFunkUtils#normalizeSpace(String)}.
* </p>
* <p>
* The difference to {@link #getElementText(By)} is that this method returns the complete inner text of the element, not only
* the visible (i. e. not hidden by CSS) one.
* </p>
*
* @param by
* the {@link By} used to locate the element
* @return the text
*/
public String getInnerText(final By by) {
return getInnerText(by, true);
}
/**
* <p>
* Delegates to {@link #findElement(By)} and then calls {@link WebElement#getAttribute(String) getAttribute("innerText")} on
* the returned element. If {@code normalizeSpace} is {@code true}, the element's text is passed to
* {@link JFunkUtils#normalizeSpace(String)}.
* </p>
* <p>
* The difference to {@link #getElementText(By, boolean)} is that this method returns the complete inner text of the element,
* not only the visible (i. e. not hidden by CSS) one.
* </p>
*
* @param by
* the {@link By} used to locate the element
* @param normalizeSpace
* specifies whether whitespace in the element text are to be normalized
* @return the text
*/
public String getInnerText(final By by, final boolean normalizeSpace) {
WebElement element = findElement(by);
String text = element.getAttribute("innerText");
return normalizeSpace ? JFunkUtils.normalizeSpace(text) : text;
}
/**
* Uses the internal {@link FormInputHandler} to set a form field.
*
* @param by
* the {@link By} used to locate the element representing an HTML input or textarea
* @param dataSetKey
* the data set key
* @param dataKey
* the key used to retrieve the value for the field from the data set with the specifies data set key
*/
public void processField(final By by, final String dataSetKey, final String dataKey) {
fih.by(by).dataSet(dataSets.get(dataSetKey)).dataKey(dataKey).perform();
}
/**
* Uses the internal {@link FormInputHandler} to set an indexed form field.
*
* @param by
* the {@link By} used to locate the element representing an HTML input or textarea
* @param dataSetKey
* the data set key
* @param dataKey
* the key used to retrieve the value for the field from the data set with the specifies data set key
* @param dataIndex
* the index for looking up dat value in the data set
*/
public void processField(final By by, final String dataSetKey, final String dataKey, final Integer dataIndex) {
fih.by(by).dataSet(dataSets.get(dataSetKey)).dataKeyWithIndex(dataKey, dataIndex).perform();
}
/**
* Uses the internal {@link FormInputHandler} to set form field. This method does not use a data set to retrieve the value.
*
* @param by
* the {@link By} used to locate the element representing an HTML input or textarea
* @param value
* the value to set the field to
*/
public void processField(final By by, final String value) {
fih.by(by).value(value).perform();
}
/**
* Opens a new window and switches to it. The window to switch to is determined by diffing the given
* {@code existingWindowHandles} with the current ones. The difference must be exactly one window handle which is then used to
* switch to.
*
* @param openClickBy
* identifies the element to click on in order to open the new window
* @param timeoutSeconds
* the timeout in seconds to wait for the new window to open
* @return the handle of the window that opened the new window
*/
public String openNewWindow(final By openClickBy, final long timeoutSeconds) {
return openNewWindow(new Runnable() {
@Override
public void run() {
click(openClickBy);
}
}, timeoutSeconds);
}
/**
* Opens a new window blank window ({@code about:blank}) and switches to it. The new window is opened by inserting a new link
* with {@code target='_blank'} and {@code href='about:blank'} at the end of the page, which is then clicked and removed again
* afterwards.
*
* @return the handle of the window that opened the new window
*/
public String openNewWindow() {
return openNewWindow("about:blank");
}
/**
* Opens a new window, switches to it, and loads the given URL in the new window. The new window is opened by inserting a new
* link with {@code target='_blank'} and {@code href='about:blank'} at the end of the page, which is then clicked and removed
* again afterwards.
*
* @param url
* the url to open
* @return the handle of the window that opened the new window
*/
public String openNewWindow(final String url) {
String id = UUID.randomUUID().toString();
// add link
((JavascriptExecutor) webDriver).executeScript(String.format(APPEND_OPEN_WINDOW_LINK_SCRIPT_TEMPLATE, id, url));
String oldHandle = openNewWindow(By.id(id), 2L);
String newHandle = webDriver.getWindowHandle();
// remove link again
webDriver.switchTo().window(oldHandle);
((JavascriptExecutor) webDriver).executeScript(String.format(REMOVE_OPEN_WINDOW_LINK_SCRIPT_TEMPLATE, id));
webDriver.switchTo().window(newHandle);
return oldHandle;
}
/**
* Opens a new window and switches to it. The window to switch to is determined by diffing the given
* {@code existingWindowHandles} with the current ones. The difference must be exactly one window handle which is then used to
* switch to.
*
* @param openCommand
* logic for opening the new window
* @param timeoutSeconds
* the timeout in seconds to wait for the new window to open
* @return the handle of the window that opened the new window
*/
public String openNewWindow(final Runnable openCommand, final long timeoutSeconds) {
String oldHandle = webDriver.getWindowHandle();
final Set<String> existingWindowHandles = webDriver.getWindowHandles();
openCommand.run();
Function<WebDriver, String> function = new Function<WebDriver, String>() {
@Override
public String apply(final WebDriver input) {
Set<String> newWindowHandles = webDriver.getWindowHandles();
SetView<String> newWindows = difference(newWindowHandles, existingWindowHandles);
if (newWindows.isEmpty()) {
throw new NotFoundException("No new window found.");
}
return getOnlyElement(newWindows);
}
@Override
public String toString() {
- return "to open new window";
+ return "new window to open";
}
};
String newHandle = waitFor(function);
webDriver.switchTo().window(newHandle);
return oldHandle;
}
}
| true | true | public String openNewWindow(final Runnable openCommand, final long timeoutSeconds) {
String oldHandle = webDriver.getWindowHandle();
final Set<String> existingWindowHandles = webDriver.getWindowHandles();
openCommand.run();
Function<WebDriver, String> function = new Function<WebDriver, String>() {
@Override
public String apply(final WebDriver input) {
Set<String> newWindowHandles = webDriver.getWindowHandles();
SetView<String> newWindows = difference(newWindowHandles, existingWindowHandles);
if (newWindows.isEmpty()) {
throw new NotFoundException("No new window found.");
}
return getOnlyElement(newWindows);
}
@Override
public String toString() {
return "to open new window";
}
};
String newHandle = waitFor(function);
webDriver.switchTo().window(newHandle);
return oldHandle;
}
| public String openNewWindow(final Runnable openCommand, final long timeoutSeconds) {
String oldHandle = webDriver.getWindowHandle();
final Set<String> existingWindowHandles = webDriver.getWindowHandles();
openCommand.run();
Function<WebDriver, String> function = new Function<WebDriver, String>() {
@Override
public String apply(final WebDriver input) {
Set<String> newWindowHandles = webDriver.getWindowHandles();
SetView<String> newWindows = difference(newWindowHandles, existingWindowHandles);
if (newWindows.isEmpty()) {
throw new NotFoundException("No new window found.");
}
return getOnlyElement(newWindows);
}
@Override
public String toString() {
return "new window to open";
}
};
String newHandle = waitFor(function);
webDriver.switchTo().window(newHandle);
return oldHandle;
}
|
diff --git a/baixing_quanleimu/src/com/baixing/view/fragment/PostGoodsFragment.java b/baixing_quanleimu/src/com/baixing/view/fragment/PostGoodsFragment.java
index 1a2d98ba..d9554fda 100644
--- a/baixing_quanleimu/src/com/baixing/view/fragment/PostGoodsFragment.java
+++ b/baixing_quanleimu/src/com/baixing/view/fragment/PostGoodsFragment.java
@@ -1,1373 +1,1374 @@
//[email protected]
package com.baixing.view.fragment;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Message;
import android.text.InputFilter;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import com.baixing.activity.BaseActivity;
import com.baixing.activity.BaseFragment;
import com.baixing.broadcast.CommonIntentAction;
import com.baixing.data.GlobalDataManager;
import com.baixing.entity.BXLocation;
import com.baixing.entity.PostGoodsBean;
import com.baixing.entity.UserBean;
import com.baixing.imageCache.ImageCacheManager;
import com.baixing.imageCache.ImageLoaderManager;
import com.baixing.jsonutil.JsonUtil;
import com.baixing.tracking.TrackConfig.TrackMobile.BxEvent;
import com.baixing.tracking.TrackConfig.TrackMobile.Key;
import com.baixing.tracking.TrackConfig.TrackMobile.PV;
import com.baixing.tracking.Tracker;
import com.baixing.util.ErrorHandler;
import com.baixing.util.PerformEvent.Event;
import com.baixing.util.PerformanceTracker;
import com.baixing.util.Util;
import com.baixing.util.ViewUtil;
import com.baixing.util.post.ImageUploader;
import com.baixing.util.post.ImageUploader.Callback;
import com.baixing.util.post.PostCommonValues;
import com.baixing.util.post.PostLocationService;
import com.baixing.util.post.PostNetworkService;
import com.baixing.util.post.PostNetworkService.PostResultData;
import com.baixing.util.post.PostUtil;
import com.baixing.widget.CustomDialogBuilder;
import com.quanleimu.activity.R;
public class PostGoodsFragment extends BaseFragment implements OnClickListener, Callback{
private static final int MSG_GEOCODING_TIMEOUT = 0x00010011;
static final public String KEY_INIT_CATEGORY = "cateNames";
static final String KEY_LAST_POST_CONTACT_USER = "lastPostContactIsRegisteredUser";
static final String KEY_IS_EDITPOST = "isEditPost";
static final String KEY_CATE_ENGLISHNAME = "cateEnglishName";
static final private String KEY_IMG_BUNDLE = "key_image_bundle";
static final private String FILE_LAST_CATEGORY = "lastCategory";
static final int MSG_POST_SUCCEED = 0xF0000010;
protected String categoryEnglishName = "";
private String categoryName = "";
protected LinearLayout layout_txt;
private LinkedHashMap<String, PostGoodsBean> postList = new LinkedHashMap<String, PostGoodsBean>();
private static final int NONE = 0;
private static final int PHOTORESOULT = 3;
private static final int MSG_CATEGORY_SEL_BACK = 11;
private static final int MSG_DIALOG_BACK_WITH_DATA = 12;
private static final int MSG_UPDATE_IMAGE_LIST = 13;
protected PostParamsHolder params = new PostParamsHolder();
protected boolean editMode = false;
// protected ArrayList<String> listUrl = new ArrayList<String>();
protected Bundle imgSelBundle = null;
private View locationView = null;
private BXLocation detailLocation = null;
protected List<String> bmpUrls = new ArrayList<String>();
private EditText etDescription = null;
private EditText etContact = null;
private PostLocationService postLBS;
private PostNetworkService postNS;
protected ArrayList<String> photoList = new ArrayList<String>();
private Bitmap firstImage = null;
protected boolean isNewPost = true;
private boolean finishRightNow = false;
@Override
public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
if (resultCode == NONE) {
return;
} else if (resultCode == Activity.RESULT_FIRST_USER) {
finishRightNow = true;
return;
}
if (resultCode == Activity.RESULT_OK) {
photoList.clear();
if (data.getExtras().containsKey(CommonIntentAction.EXTRA_IMAGE_LIST)){
ArrayList<String> result = data.getStringArrayListExtra(CommonIntentAction.EXTRA_IMAGE_LIST);
photoList.addAll(result);
}
if (photoList != null && photoList.size() > 0) {
firstImage = ImageUploader.getInstance().getThumbnail(photoList.get(0));
for(int i = 0; i < photoList.size(); ++ i){
ImageUploader.getInstance().registerCallback(photoList.get(i), this);
}
}
else {
firstImage = null;
}
}
handler.sendEmptyMessage(MSG_UPDATE_IMAGE_LIST);
}
private void initWithCategoryNames(String categoryNames) {
if(categoryNames == null || categoryNames.length() == 0){
categoryNames = (String)Util.loadDataFromLocate(this.getActivity(), FILE_LAST_CATEGORY, String.class);
}
if(categoryNames != null && !categoryNames.equals("")){
String[] names = categoryNames.split(",");
if(names.length == 2){
this.categoryEnglishName = names[0];
this.categoryName = names[1];
}else if(names.length == 1){
this.categoryEnglishName = names[0];
}
Util.saveDataToLocate(this.getActivity(), FILE_LAST_CATEGORY, categoryNames);
}
}
@SuppressWarnings("unchecked")
@Override
public void onCreate(Bundle savedInstanceState) {
PerformanceTracker.stamp(Event.E_PGFrag_OnCreate_Start);
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
isNewPost = false;
} else {
isNewPost = !editMode;
}
String categoryNames = this.getArguments().getString(KEY_INIT_CATEGORY);
initWithCategoryNames(categoryNames);
if (savedInstanceState != null){
postList.putAll( (HashMap<String, PostGoodsBean>)savedInstanceState.getSerializable("postList"));
params = (PostParamsHolder) savedInstanceState.getSerializable("params");
// listUrl.addAll((List<String>) savedInstanceState.getSerializable("listUrl"));
photoList.addAll((List<String>) savedInstanceState.getSerializable("listUrl"));
imgHeight = savedInstanceState.getInt("imgHeight");
imgSelBundle = savedInstanceState.getBundle(KEY_IMG_BUNDLE);
}
if(imgSelBundle == null){
imgSelBundle = new Bundle();
}
// if(imgSelDlg == null){ //FIXME: remove
// imgSelDlg = new ImageSelectionDialog(imgSelBundle);
// imgSelDlg.setMsgOutHandler(handler);
// }
String appPhone = GlobalDataManager.getInstance().getPhoneNumber();
if(!editMode && (appPhone == null || appPhone.length() == 0)){
UserBean user = GlobalDataManager.getInstance().getAccountManager().getCurrentUser();
if(user != null && user.getPhone() != null && !user.getPhone().equals("")){
String mobile = user.getPhone();
GlobalDataManager.getInstance().setPhoneNumber(mobile);
}
}
this.postLBS = new PostLocationService(this.handler);
postNS = new PostNetworkService(handler);
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
PostUtil.extractInputData(layout_txt, params);
outState.putSerializable("params", params);
outState.putSerializable("postList", postList);
outState.putSerializable("listUrl", photoList);
outState.putInt("imgHeight", imgHeight);
outState.putBundle(KEY_IMG_BUNDLE, imgSelBundle);
}
private void doClearUpImages() {
//Clear the upload image list.
this.photoList.clear();
this.firstImage = null;
ImageUploader.getInstance().clearAll();
}
@Override
public boolean handleBack() {
// if(imgSelDlg != null)
// if(imgSelDlg.handleBack()){
// return true;
// }
// return super.handleBack();
AlertDialog.Builder builder = new Builder(getActivity());
builder.setMessage("退出发布?");
builder.setNegativeButton("否", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//Do nothing.
}
});
builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
doClearUpImages();
finishFragment();
}
});
builder.create().show();
return true;
}
@Override
public void onResume() {
super.onResume();
isActive = true;
postLBS.start();
if(!editMode) {
this.pv = PV.POST;
Tracker.getInstance()
.pv(this.pv)
.append(Key.SECONDCATENAME, categoryEnglishName)
.end();
}
if (finishRightNow) {
finishRightNow = false;
doClearUpImages();
finishFragment();
}
}
private boolean isActive = false;
@Override
public void onPause() {
postLBS.stop();
PostUtil.extractInputData(layout_txt, params);
setPhoneAndAddress();
isActive = false;
super.onPause();
}
@Override
public void onStackTop(boolean isBack) {
if(isBack){
final ScrollView scroll = (ScrollView) this.getView().findViewById(R.id.goodscontent);
scroll.post(new Runnable() {
@Override
public void run() {
scroll.fullScroll(View.FOCUS_DOWN);
}
});
}
if (isNewPost) {
isNewPost = false;
this.startImgSelDlg(Activity.RESULT_FIRST_USER, "跳过拍照");
}
}
@Override
public void onViewCreated (View view, Bundle savedInstanceState){
super.onViewCreated(view, savedInstanceState);
showPost();
}
@Override
public View onInitializeView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ViewGroup v = (ViewGroup) inflater.inflate(R.layout.postgoodsview, null);
layout_txt = (LinearLayout) v.findViewById(R.id.layout_txt);
Button button = (Button) v.findViewById(R.id.iv_post_finish);
button.setOnClickListener(this);
if (!editMode)
button.setText("立即免费发布");
else
button.setText("立即更新信息");
return v;
}
protected void startImgSelDlg(final int cancelResultCode, String finishActionLabel){
// if(container != null){
// imgSelBundle.putSerializable(ImageSelectionDialog.KEY_IMG_CONTAINER, container);
// }
// imgSelDlg.setMsgOutBundle(imgSelBundle);
// imgSelDlg.show(getFragmentManager(), null);
PerformanceTracker.stamp(Event.E_Send_Camera_Bootup);
Intent backIntent = new Intent();
backIntent.setClass(getActivity(), getActivity().getClass());
Intent goIntent = new Intent();
goIntent.putExtra(CommonIntentAction.EXTRA_COMMON_INTENT, backIntent);
goIntent.setAction(CommonIntentAction.ACTION_IMAGE_CAPTURE);
goIntent.putExtra(CommonIntentAction.EXTRA_COMMON_REQUST_CODE, CommonIntentAction.PhotoReqCode.PHOTOHRAPH);
goIntent.putStringArrayListExtra(CommonIntentAction.EXTRA_IMAGE_LIST, this.photoList);
goIntent.putExtra(CommonIntentAction.EXTRA_FINISH_ACTION_LABEL, finishActionLabel);
goIntent.putExtra(CommonIntentAction.EXTRA_COMMON_FINISH_CODE, cancelResultCode);
// BXLocation loc = GlobalDataManager.getInstance().getLocationManager().getCurrentPosition(true);
// if (loc != null) {
// goIntent.putExtra("location", loc);
// }
getActivity().startActivity(goIntent);
}
private void deployDefaultLayout(){
addCategoryItem();
HashMap<String, PostGoodsBean> pl = new HashMap<String, PostGoodsBean>();
for(int i = 1; i < PostCommonValues.fixedItemNames.length; ++ i){
PostGoodsBean bean = new PostGoodsBean();
bean.setControlType("input");
bean.setDisplayName(PostCommonValues.fixedItemDisplayNames[i]);
bean.setName(PostCommonValues.fixedItemNames[i]);
bean.setUnit("");
if(PostCommonValues.fixedItemNames[i].equals("价格")){
bean.setNumeric(1);//.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED);
bean.setUnit("元");
}
pl.put(PostCommonValues.fixedItemNames[i], bean);
}
buildPostLayout(pl);
}
public void updateNewCategoryLayout(String cateNames){
if(cateNames == null) return;
String[] names = cateNames.split(",");
if(names != null){
if(categoryEnglishName.equals(names[0])) return;
}
initWithCategoryNames(cateNames);
resetData(true);
Util.saveDataToLocate(getActivity(), FILE_LAST_CATEGORY, cateNames);
this.showPost();
}
protected String getCityEnglishName(){
return GlobalDataManager.getInstance().getCityEnglishName();
}
private void showGettingMetaProgress(boolean show){
for(int i = 0; i < layout_txt.getChildCount(); ++ i){
View v = layout_txt.getChildAt(i);
if(v == null) continue;
View progress = v.findViewById(R.id.metaLoadingBar);
if(progress != null){
if(show){
progress.setVisibility(View.VISIBLE);
v.findViewById(R.id.post_next).setVisibility(View.GONE);
}else{
progress.setVisibility(View.GONE);
v.findViewById(R.id.post_next).setVisibility(View.VISIBLE);
}
}
}
}
private void showPost(){
if(this.categoryEnglishName == null || categoryEnglishName.length() == 0){
deployDefaultLayout();
return;
}
String cityEnglishName = getCityEnglishName();
Pair<Long, String> pair = Util.loadJsonAndTimestampFromLocate(this.getActivity(), categoryEnglishName + cityEnglishName);
String json = pair.second;
if (json != null && json.length() > 0) {
if (pair.first + (24 * 3600) >= System.currentTimeMillis()/1000) {
if(postList == null || postList.size() == 0){
postList = JsonUtil.getPostGoodsBean(json);
}
addCategoryItem();
buildPostLayout(postList);
loadCachedData();
return;
}
}
// showSimpleProgress();
showGettingMetaProgress(true);
postNS.retreiveMetaAsync(cityEnglishName, categoryEnglishName);
}
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.iv_post_finish:
Tracker.getInstance()
.event(!editMode ? BxEvent.POST_POSTBTNCONTENTCLICKED:BxEvent.EDITPOST_POSTBTNCONTENTCLICKED)
.append(Key.SECONDCATENAME, categoryEnglishName).end();
this.postAction();
break;
case R.id.location:
Tracker.getInstance().event((!editMode)?BxEvent.POST_INPUTING:BxEvent.EDITPOST_INPUTING).append(Key.ACTION, PostCommonValues.STRING_DETAIL_POSITION).end();
if(this.detailLocation != null && locationView != null){
setDetailLocationControl(detailLocation);
}else if(detailLocation == null){
ViewUtil.showToast(this.getActivity(), "无法获得当前位置", false);
}
break;
case R.id.myImg:
Tracker.getInstance().event((!editMode)?BxEvent.POST_INPUTING:BxEvent.EDITPOST_INPUTING).append(Key.ACTION, "image").end();
// if(!editMode){
startImgSelDlg(Activity.RESULT_CANCELED, "完成");
// }
break;
case R.id.img_description:
final View et = v.findViewById(R.id.description_input);
if(et != null){
et.postDelayed(new Runnable(){
@Override
public void run(){
if (et != null){
Tracker.getInstance().event((!editMode)?BxEvent.POST_INPUTING:BxEvent.EDITPOST_INPUTING).append(Key.ACTION, PostCommonValues.STRING_DESCRIPTION).end();
et.requestFocus();
InputMethodManager inputMgr = (InputMethodManager) et.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
inputMgr.showSoftInput(et, InputMethodManager.SHOW_IMPLICIT);
}
}
}, 100);
}
break;
case R.id.postinputlayout:
final View et2 = v.findViewById(R.id.postinput);
if(et2 != null){
et2.postDelayed(new Runnable(){
@Override
public void run(){
if (et2 != null){
et2.requestFocus();
InputMethodManager inputMgr = (InputMethodManager) et2.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
inputMgr.showSoftInput(et2, InputMethodManager.SHOW_IMPLICIT);
}
}
}, 100);
}
break;
}
}
private void setPhoneAndAddress(){
String phone = params.getData("contact");
if(phone != null && phone.length() > 0 && !editMode){
GlobalDataManager.getInstance().setPhoneNumber(phone);
}
String address = params.getData(PostCommonValues.STRING_DETAIL_POSITION);
if(address != null && address.length() > 0){
GlobalDataManager.getInstance().setAddress(address);
}
}
private void postAction() {
if((this.postList == null || postList.size() == 0)
&& ((this.categoryEnglishName != null && categoryEnglishName.length() > 0)
|| (this.categoryName != null && categoryName.length() > 0))){
return;
}
PostUtil.extractInputData(layout_txt, params);
setPhoneAndAddress();
if(!this.checkInputComplete()){
return;
}
PerformanceTracker.stamp(Event.E_Start_PostAction);
String detailLocationValue = params.getUiData(PostCommonValues.STRING_DETAIL_POSITION);
if(this.detailLocation != null && (detailLocationValue == null || detailLocationValue.length() == 0)){
showProgress(R.string.dialog_title_info, R.string.dialog_message_waiting, false);
PerformanceTracker.stamp(Event.E_PostAction_Direct_Start);
postAd(detailLocation);
}else{
this.sendMessageDelay(MSG_GEOCODING_TIMEOUT, null, 5000);
this.showSimpleProgress();
PerformanceTracker.stamp(Event.E_PostAction_GetLocation_Start);
postLBS.retreiveLocation(GlobalDataManager.getInstance().cityName, getFilledLocation());
}
}
private boolean checkInputComplete() {
if(this.categoryEnglishName == null || this.categoryEnglishName.equals("")){
ViewUtil.showToast(this.getActivity(), "请选择分类", false);
popupCategorySelectionDialog();
return false;
}
for (int i = 0; i < postList.size(); i++) {
String key = (String) postList.keySet().toArray()[i];
PostGoodsBean postGoodsBean = postList.get(key);
if (postGoodsBean.getName().equals(PostCommonValues.STRING_DESCRIPTION) ||
(postGoodsBean.getRequired().endsWith("required") && !PostUtil.inArray(postGoodsBean.getName(), PostCommonValues.hiddenItemNames) && !postGoodsBean.getName().equals("title") && !postGoodsBean.getName().equals(PostCommonValues.STRING_AREA))) {
if(!params.containsKey(postGoodsBean.getName())
|| params.getData(postGoodsBean.getName()).equals("")
|| (postGoodsBean.getUnit() != null && params.getData(postGoodsBean.getName()).equals(postGoodsBean.getUnit()))){
if(postGoodsBean.getName().equals("images"))continue;
postResultFail("please entering " + postGoodsBean.getDisplayName() + "!");
ViewUtil.showToast(this.getActivity(), "请填写" + postGoodsBean.getDisplayName() + "!", false);
this.changeFocusAfterPostError(postGoodsBean.getDisplayName());
return false;
}
}
}
if (ImageUploader.getInstance().hasPendingJob()) {
ViewUtil.showToast(this.getActivity(), "图片上传中", false);
return false;
}
return true;
}
private String getFilledLocation(){
String toRet = "";
for(int m = 0; m < layout_txt.getChildCount(); ++ m){
View v = layout_txt.getChildAt(m);
PostGoodsBean bean = (PostGoodsBean)v.getTag(PostCommonValues.HASH_POST_BEAN);
if(bean == null) continue;
if(bean.getName().equals(PostCommonValues.STRING_DETAIL_POSITION)){
TextView tv = (TextView)v.getTag(PostCommonValues.HASH_CONTROL);
if(tv != null && !tv.getText().toString().equals("")){
toRet = tv.getText().toString();
}
break;
}
}
return toRet;
}
protected void mergeParams(HashMap<String, String> list){}
protected void postAd(BXLocation location){
HashMap<String, String> list = new HashMap<String, String>();
list.put("categoryEnglishName", categoryEnglishName);
list.put("cityEnglishName", GlobalDataManager.getInstance().getCityEnglishName());
HashMap<String, String> mapParams = new HashMap<String, String>();
Iterator<String> ite = params.keyIterator();
while(ite.hasNext()){
String key = ite.next();
String value = params.getData(key);
mapParams.put(key, value);
}
mergeParams(list);
// this.postNS.postAdAsync(mapParams, list, postList, bmpUrls, location, editMode);
bmpUrls.clear();
bmpUrls.addAll(ImageUploader.getInstance().getServerUrlList());
PerformanceTracker.stamp(Event.E_Post_Request_Sent);
this.postNS.postAdAsync(mapParams, list, postList, bmpUrls, location, editMode);
}
private int getLineCount() {
return etDescription != null ? etDescription.getLineCount() : 1;
}
private int getDescLength() {
return etDescription != null ? etDescription.getText().length() : 0;
}
private int getContactLength() {
return etContact != null ? etContact.getText().length() : 0;
}
private int getImgCount() {
int imgCount = 0;
for (int i = 0; i < bmpUrls.size(); i++) {
if(bmpUrls.get(i) != null && bmpUrls.get(i).contains("http:")){
imgCount++;
}
}
return imgCount;
}
private void postResultSuccess() {
BxEvent event = editMode ? BxEvent.EDITPOST_POSTRESULT : BxEvent.POST_POSTRESULT;
Tracker.getInstance().event(event)
.append(Key.SECONDCATENAME, categoryEnglishName)
.append(Key.POSTSTATUS, 1)
.append(Key.POSTPICSCOUNT, getImgCount())
.append(Key.POSTDESCRIPTIONLINECOUNT, getLineCount())
.append(Key.POSTDESCRIPTIONTEXTCOUNT, getDescLength())
.append(Key.POSTCONTACTTEXTCOUNT, getContactLength()).end();
}
private void postResultFail(String errorMsg) {
BxEvent event = editMode ? BxEvent.EDITPOST_POSTRESULT : BxEvent.POST_POSTRESULT;
Tracker.getInstance().event(event)
.append(Key.SECONDCATENAME, categoryEnglishName)
.append(Key.POSTSTATUS, 0)
.append(Key.POSTFAILREASON, errorMsg)
.append(Key.POSTPICSCOUNT, getImgCount())
.append(Key.POSTDESCRIPTIONLINECOUNT, getLineCount())
.append(Key.POSTDESCRIPTIONTEXTCOUNT, getDescLength())
.append(Key.POSTCONTACTTEXTCOUNT, getContactLength()).end();
}
private void loadCachedData(){
if(params.size() == 0) return;
Iterator<String> it = params.keyIterator();
while (it.hasNext()){
String name = it.next();
for (int i=0; i<layout_txt.getChildCount(); i++)
{
View v = layout_txt.getChildAt(i);
PostGoodsBean bean = (PostGoodsBean)v.getTag(PostCommonValues.HASH_POST_BEAN);
if(bean == null ||
!bean.getName().equals(name)//check display name
) continue;
View control = (View)v.getTag(PostCommonValues.HASH_CONTROL);
String displayValue = params.getUiData(name);
if(control instanceof CheckBox){
if(displayValue.contains(((CheckBox)control).getText())){
((CheckBox)control).setChecked(true);
}
else{
((CheckBox)control).setChecked(false);
}
}else if(control instanceof TextView){
((TextView)control).setText(displayValue);
}
}
}
}
private void clearCategoryParameters(){//keep fixed(common) parameters there
Iterator<String> ite = params.keyIterator();
while(ite.hasNext()){
String key = ite.next();
if(!PostUtil.inArray(key, PostCommonValues.fixedItemNames)){
params.remove(key);
ite = params.keyIterator();
}
}
}
private void resetData(boolean clearImgs){
if(this.layout_txt != null){
View desView = layout_txt.findViewById(R.id.img_description);
View catView = layout_txt.findViewById(R.id.categoryItem);
layout_txt.removeAllViews();
layout_txt.addView(desView);
if(catView != null){
layout_txt.addView(catView);
}
}
postList.clear();
if(null != Util.loadDataFromLocate(getActivity(), FILE_LAST_CATEGORY, String.class)){
clearCategoryParameters();
if(clearImgs){
// listUrl.clear();
this.doClearUpImages();
this.bmpUrls.clear();
layout_txt.findViewById(R.id.imgCout).setVisibility(View.INVISIBLE);
params.remove(PostCommonValues.STRING_DESCRIPTION);
params.remove("价格");
}
}
}
private void handleBackWithData(int message, Object obj) {
if(message == MSG_CATEGORY_SEL_BACK && obj != null){
String[] names = ((String)obj).split(",");
if(names.length == 2){
if(names[0].equals(this.categoryEnglishName)){
return;
}
this.categoryEnglishName = names[0];
this.categoryName = names[1];
}else if(names.length == 1){
if(names[0].equals(this.categoryEnglishName)){
return;
}
this.categoryEnglishName = names[0];
}
resetData(false);
Util.saveDataToLocate(getActivity(), FILE_LAST_CATEGORY, obj);
this.showPost();
}
PostUtil.fetchResultFromViewBack(message, obj, layout_txt, params);
}
@Override
public void onFragmentBackWithData(int message, Object obj){
handleBackWithData(message, obj);
}
protected String getAdContact(){
return "";
}
private void appendBeanToLayout(PostGoodsBean postBean){
UserBean user = GlobalDataManager.getInstance().getAccountManager().getCurrentUser();
if (postBean.getName().equals("contact") &&
(postBean.getValues() == null || postBean.getValues().isEmpty()) &&
(user != null && user.getPhone() != null && user.getPhone().length() > 0)){
List<String> valueList = new ArrayList<String>(1);
valueList.add(user.getPhone());
postBean.setValues(valueList);
postBean.setLabels(valueList);
}
ViewGroup layout = createItemByPostBean(postBean);//FIXME:
if(layout != null && layout.findViewById(R.id.postinputlayout) != null){
layout.setClickable(true);
layout.setOnClickListener(this);
}
if(layout != null && !postBean.getName().equals(PostCommonValues.STRING_DETAIL_POSITION)){
ViewGroup.LayoutParams lp = layout.getLayoutParams();
lp.height = getResources().getDimensionPixelOffset(R.dimen.post_item_height);
layout.setLayoutParams(lp);
}
if(postBean.getName().equals(PostCommonValues.STRING_DETAIL_POSITION)){
layout.findViewById(R.id.location).setOnClickListener(this);
((TextView)layout.findViewById(R.id.postinput)).setHint("填写或点击按钮定位");
locationView = layout;
String address = GlobalDataManager.getInstance().getAddress();
if(address != null && address.length() > 0){
((TextView)layout.findViewById(R.id.postinput)).setText(address);
}
}else if(postBean.getName().equals("contact") && layout != null){
etContact = ((EditText)layout.getTag(PostCommonValues.HASH_CONTROL));
((TextView)layout.findViewById(R.id.postinput)).setHint("手机或座机");
etContact.setFilters(new InputFilter[]{new InputFilter.LengthFilter(15)});
String phone = GlobalDataManager.getInstance().getPhoneNumber();
if(editMode){
etContact.setText(getAdContact());
}else{
if(phone != null && phone.length() > 0){
etContact.setText(phone);
}
}
}else if (postBean.getName().equals(PostCommonValues.STRING_DESCRIPTION) && layout != null){
etDescription = (EditText) layout.getTag(PostCommonValues.HASH_CONTROL);
}else if(postBean.getName().equals("价格")){
((TextView)layout.findViewById(R.id.postinput)).setHint("越便宜成交越快");
}else if(postBean.getName().equals("faburen")){
List<String> labels = postBean.getLabels();
List<String> values = postBean.getValues();
if(labels != null){
for(int i = 0; i < labels.size(); ++ i){
if(labels.get(i).equals("个人")){
((TextView)layout.findViewById(R.id.posthint)).setText(labels.get(i));
params.put(postBean.getName(), labels.get(i), values.get(i));
}
}
}
//
}
if(layout != null){
layout_txt.addView(layout);
}
}
private void popupCategorySelectionDialog(){
Bundle bundle = createArguments(null, null);
bundle.putSerializable("items", (Serializable) Arrays.asList(PostCommonValues.mainCategories));
bundle.putInt("maxLevel", 1);
bundle.putInt(ARG_COMMON_REQ_CODE, MSG_CATEGORY_SEL_BACK);
if(categoryEnglishName != null && !categoryEnglishName.equals("") && categoryName != null) {
bundle.putString("selectedValue", categoryName);
}
PostUtil.extractInputData(layout_txt, params);
CustomDialogBuilder cdb = new CustomDialogBuilder(getActivity(), PostGoodsFragment.this.getHandler(), bundle);
cdb.start();
}
private void addCategoryItem(){
Activity activity = getActivity();
if(layout_txt != null){
if(layout_txt.findViewById(R.id.arrow_down) != null) return;
}
// LayoutInflater inflater = LayoutInflater.from(activity);
// View categoryItem = inflater.inflate(R.layout.item_post_category, null);
View categoryItem = layout_txt.findViewById(R.id.categoryItem);
if(editMode){
layout_txt.removeView(categoryItem);
return;
}
categoryItem.setTag(PostCommonValues.HASH_CONTROL, categoryItem.findViewById(R.id.posthint));//tag
((TextView)categoryItem.findViewById(R.id.postshow)).setText("分类");
categoryItem.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
Tracker.getInstance().event(BxEvent.POST_INPUTING).append(Key.ACTION, "类目").end();
popupCategorySelectionDialog();
}
});//categoryItem.setOnClickListener
if(categoryEnglishName != null && !categoryEnglishName.equals("") && categoryName != null){
((TextView)categoryItem.findViewById(R.id.posthint)).setText(categoryName);
}else{
((TextView)categoryItem.findViewById(R.id.posthint)).setText("请选择分类");
}
PostUtil.adjustMarginBottomAndHeight(categoryItem);
// layout_txt.addView(categoryItem);
}
private void buildFixedPostLayout(HashMap<String, PostGoodsBean> pl){
if(pl == null || pl.size() == 0) return;
HashMap<String, PostGoodsBean> pm = new HashMap<String, PostGoodsBean>();
Object[] postListKeySetArray = pl.keySet().toArray();
for(int i = 0; i < pl.size(); ++ i){
for(int j = 0; j < PostCommonValues.fixedItemNames.length; ++ j){
PostGoodsBean bean = pl.get(postListKeySetArray[i]);
if(bean.getName().equals(PostCommonValues.fixedItemNames[j])){
pm.put(PostCommonValues.fixedItemNames[j], bean);
break;
}
}
}
if(pm.containsKey(PostCommonValues.STRING_DESCRIPTION)){
PostGoodsBean bean = pm.get(PostCommonValues.STRING_DESCRIPTION);
if(bean != null){
View v = layout_txt.findViewById(R.id.img_description);
EditText text = (EditText)v.findViewById(R.id.description_input);
text.setText("");
text.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
Tracker.getInstance().event((editMode)?BxEvent.POST_INPUTING:BxEvent.EDITPOST_INPUTING).append(Key.ACTION, PostCommonValues.STRING_DESCRIPTION).end();
}
return false;
}
});
text.setOnFocusChangeListener(new PostUtil.BorderChangeListener(this.getActivity(), v));
text.setHint("请输入" + bean.getDisplayName());
v.setTag(PostCommonValues.HASH_POST_BEAN, bean);
v.setTag(PostCommonValues.HASH_CONTROL, text);
v.setOnClickListener(this);
v.findViewById(R.id.myImg).setOnClickListener(this);
((ImageView)v.findViewById(R.id.myImg)).setImageBitmap(ImageCacheManager.getInstance().loadBitmapFromResource(R.drawable.btn_add_picture));
this.updateImageInfo(layout_txt);
}
}
for(int i = 0; i < PostCommonValues.fixedItemNames.length; ++ i){
if(pm.containsKey(PostCommonValues.fixedItemNames[i]) && !PostCommonValues.fixedItemNames[i].equals(PostCommonValues.STRING_DESCRIPTION)){
this.appendBeanToLayout(pm.get(PostCommonValues.fixedItemNames[i]));
}else if(!pm.containsKey(PostCommonValues.fixedItemNames[i])){
params.remove(PostCommonValues.fixedItemNames[i]);
}
}
}
private void addHiddenItemsToParams(){
if (postList == null || postList.isEmpty())
return ;
Set<String> keySet = postList.keySet();
for (String key : keySet){
PostGoodsBean bean = postList.get(key);
for (int i = 0; i< PostCommonValues.hiddenItemNames.length; i++){
if (bean.getName().equals(PostCommonValues.hiddenItemNames[i])){
String defaultValue = bean.getDefaultValue();
if (defaultValue != null && defaultValue.length() > 0) {
this.params.put(bean.getName(), defaultValue, defaultValue);
} else {
this.params.put(bean.getName(), bean.getLabels().get(0), bean.getValues().get(0));
}
break;
}
}
}
}
protected void buildPostLayout(HashMap<String, PostGoodsBean> pl){
this.getView().findViewById(R.id.goodscontent).setVisibility(View.VISIBLE);
this.getView().findViewById(R.id.networkErrorView).setVisibility(View.GONE);
this.reCreateTitle();
this.refreshHeader();
if(pl == null || pl.size() == 0){
return;
}
buildFixedPostLayout(pl);
addHiddenItemsToParams();
Object[] postListKeySetArray = pl.keySet().toArray();
for (int i = 0; i < pl.size(); i++) {
String key = (String) postListKeySetArray[i];
PostGoodsBean postBean = pl.get(key);
if(PostUtil.inArray(postBean.getName(), PostCommonValues.fixedItemNames) || postBean.getName().equals("title") || PostUtil.inArray(postBean.getName(), PostCommonValues.hiddenItemNames))
continue;
if(postBean.getName().equals(PostCommonValues.STRING_AREA)){
continue;
}
this.appendBeanToLayout(postBean);
}
}
private void showInputMethod() {
final View root = this.getView();
if (root != null) {
root.postDelayed(new Runnable() {
public void run() {
EditText ed = (EditText) root.findViewById(R.id.description_input);
if (ed != null && ed.getText().length() == 0) {
ed.requestFocus();
InputMethodManager mgr = (InputMethodManager) root.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.showSoftInput(ed, InputMethodManager.SHOW_IMPLICIT);
}
}
}, 200);
}
}
private void updateImageInfo(View rootView) {
if(rootView != null){
ImageView iv = (ImageView)rootView.findViewById(R.id.myImg);
if (iv != null && firstImage != null) {
iv.setImageBitmap(this.firstImage);
}
else if (iv != null) {
iv.setImageBitmap(ImageCacheManager.getInstance().loadBitmapFromResource(R.drawable.btn_add_picture));
}
TextView tv = (TextView) rootView.findViewById(R.id.imgCout);
if(tv != null){
int containerCount = photoList == null ? 0 : photoList.size();
if(containerCount > 0){
tv.setText(String.valueOf(containerCount));
tv.setVisibility(View.VISIBLE);
}else{
tv.setVisibility(View.INVISIBLE);
}
}
}
}
@SuppressWarnings("unchecked")
@Override
protected void handleMessage(Message msg, final Activity activity, final View rootView) {
hideProgress();
switch (msg.what) {
case MSG_DIALOG_BACK_WITH_DATA:{
Bundle bundle = (Bundle)msg.obj;
handleBackWithData(bundle.getInt(ARG_COMMON_REQ_CODE), bundle.getSerializable("lastChoise"));
break;
}
case MSG_UPDATE_IMAGE_LIST:{
updateImageInfo(rootView);
showInputMethod();
break;
}
case PostCommonValues.MSG_GET_META_SUCCEED:{
Button button = (Button) layout_txt.getRootView().findViewById(R.id.iv_post_finish);
if(button != null){
button.setEnabled(true);
}
postList = (LinkedHashMap<String, PostGoodsBean>)msg.obj;
addCategoryItem();
buildPostLayout(postList);
loadCachedData();
this.showGettingMetaProgress(false);
break;
}
case PostCommonValues.MSG_GET_META_FAIL:
hideProgress();
Button button = (Button) layout_txt.getRootView().findViewById(R.id.iv_post_finish);
if(button != null){
button.setEnabled(false);
}
addCategoryItem();
if(msg.obj != null){
ViewUtil.showToast(activity, (String)msg.obj, false);
}
this.showGettingMetaProgress(false);
break;
case PostCommonValues.MSG_POST_SUCCEED:
PerformanceTracker.stamp(Event.E_POST_SUCCEEDED);
hideProgress();
doClearUpImages();
String id = ((PostResultData)msg.obj).id;
boolean isRegisteredUser = ((PostResultData)msg.obj).isRegisteredUser;
String message = ((PostResultData)msg.obj).message;
int code = ((PostResultData)msg.obj).error;
if (!id.equals("") && code == 0) {
postResultSuccess();
ViewUtil.showToast(activity, message, false);
final Bundle args = createArguments(null, null);
args.putInt("forceUpdate", 1);
if(!editMode || (editMode && isActive)){
resetData(!editMode);
Util.deleteDataFromLocate(this.getActivity(), FILE_LAST_CATEGORY);
categoryEnglishName = "";
categoryName = "";
}
// showPost();
if(!editMode){
showPost();
String lp = getArguments().getString("lastPost");
if(lp != null && !lp.equals("")){
lp += "," + id;
}else{
lp = id;
}
args.putString("lastPost", lp);
args.putString("cateEnglishName", categoryEnglishName);
args.putBoolean(KEY_IS_EDITPOST, editMode);
args.putBoolean(KEY_LAST_POST_CONTACT_USER, isRegisteredUser);
if(activity != null){
args.putInt(MyAdFragment.TYPE_KEY, MyAdFragment.TYPE_MYPOST);
Intent intent = new Intent(CommonIntentAction.ACTION_BROADCAST_POST_FINISH);
intent.putExtras(args);
PerformanceTracker.stamp(Event.E_Post_Send_Success_Broadcast);
activity.sendBroadcast(intent);
}
doClearUpImages();
// finishFragment();
}else{
// showPost();
PostGoodsFragment.this.finishFragment(PostGoodsFragment.MSG_POST_SUCCEED, null);
}
}else{
postResultFail(message);
if(msg.obj != null){
handlePostFail((PostResultData)msg.obj);
}
}
break;
case PostCommonValues.MSG_POST_FAIL:
hideProgress();
if(msg.obj != null){
if(msg.obj instanceof String){
ViewUtil.showToast(activity, (String)msg.obj, false);
this.changeFocusAfterPostError((String)msg.obj);
+ postResultFail((String)msg.obj);
}else if(msg.obj instanceof PostResultData){
handlePostFail((PostResultData)msg.obj);
postResultFail(((PostResultData)msg.obj).message);
}
}
break;
case PostCommonValues.MSG_POST_EXCEPTION:
hideProgress();
ViewUtil.showToast(activity, "网络连接异常", false);
break;
case ErrorHandler.ERROR_SERVICE_UNAVAILABLE:
hideProgress();
ErrorHandler.getInstance().handleMessage(msg);
// this.getView().findViewById(R.id.goodscontent).setVisibility(View.GONE);
// this.getView().findViewById(R.id.networkErrorView).setVisibility(View.VISIBLE);
// this.reCreateTitle();
// this.refreshHeader();
break;
case MSG_GEOCODING_TIMEOUT:
case PostCommonValues.MSG_GEOCODING_FETCHED:
Event evt = msg.what == MSG_GEOCODING_TIMEOUT ? Event.E_GeoCoding_Timeout : Event.E_GeoCoding_Fetched;
PerformanceTracker.stamp(evt);
showSimpleProgress();
handler.removeMessages(MSG_GEOCODING_TIMEOUT);
handler.removeMessages(PostCommonValues.MSG_GEOCODING_FETCHED);
postAd(msg.obj == null ? null : (BXLocation)msg.obj);
break;
case PostCommonValues.MSG_GPS_LOC_FETCHED:
detailLocation = (BXLocation)msg.obj;
break;
}
}
private void changeFocusAfterPostError(String errMsg){
if(postList == null) return;
Set<String> keys = postList.keySet();
if(keys == null) return;
for(String key : keys){
PostGoodsBean bean = postList.get(key);
if(errMsg.contains(bean.getDisplayName())){
for(int j = 0; j < layout_txt.getChildCount(); ++ j){
final View child = layout_txt.getChildAt(j);
if(child != null){
PostGoodsBean tag = (PostGoodsBean)child.getTag(PostCommonValues.HASH_POST_BEAN);
if(tag != null && tag.getName().equals(postList.get(key).getName())){
View et = child.findViewById(R.id.postinput);
if(et == null){
et = child.findViewById(R.id.description_input);
}
if(et != null){
final View inputView = et;
inputView.postDelayed(new Runnable(){
@Override
public void run(){
inputView.requestFocus();
InputMethodManager inputMgr =
(InputMethodManager) inputView.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
inputMgr.showSoftInput(inputView, InputMethodManager.SHOW_IMPLICIT);
}
}, 100);
}
return;
}
}
}
}
}
}
private void handlePostFail(final PostResultData result){
if(result == null) return;
if(result.error == 505){
AlertDialog.Builder bd = new AlertDialog.Builder(this.getActivity());
bd.setTitle("")
.setMessage(result.message)
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
if(getActivity() != null){
resetData(true);
showPost();
Bundle args = createArguments(null, null);
args.putInt(MyAdFragment.TYPE_KEY, MyAdFragment.TYPE_MYPOST);
Intent intent = new Intent(CommonIntentAction.ACTION_BROADCAST_POST_FINISH);
intent.putExtras(args);
getActivity().sendBroadcast(intent);
}
}
});
AlertDialog alert = bd.create();
alert.show();
}
}
private int imgHeight = 0;
////to fix stupid system error. all text area will be the same content after app is brought to front when activity not remain is checked
private void setInputContent(){
if(layout_txt == null) return;
for(int i = 0; i < layout_txt.getChildCount(); ++ i){
View v = layout_txt.getChildAt(i);
PostGoodsBean bean = (PostGoodsBean)v.getTag(PostCommonValues.HASH_POST_BEAN);
if(bean == null) continue;
View control = (View)v.getTag(PostCommonValues.HASH_CONTROL);
if(control != null && control instanceof TextView){
if(params != null && params.containsKey(bean.getName())){
String value = params.getUiData(bean.getName());
if(value == null){
value = params.getUiData(bean.getName());
}
if(bean.getName().equals("contact")){
if(editMode){
((TextView)control).setText(getAdContact());
}else{
String phone = GlobalDataManager.getInstance().getPhoneNumber();
if(phone != null && phone.length() > 0){
((TextView)control).setText(phone);
continue;
}
}
}
((TextView)control).setText(value);
}
}
}
}
@Override
public void onStart(){
super.onStart();
setInputContent();
}
@Override
public void initTitle(TitleDef title){
title.m_visible = true;
title.m_leftActionHint = "返回";
title.m_leftActionImage = R.drawable.icon_close;
title.m_title = "免费发布";
}
private ViewGroup createItemByPostBean(PostGoodsBean postBean){
Activity activity = getActivity();
ViewGroup layout = PostUtil.createItemByPostBean(postBean, activity);
if (layout == null)
return null;
if(postBean.getControlType().equals("select") || postBean.getControlType().equals("checkbox")){
final String actionName = ((PostGoodsBean)layout.getTag(PostCommonValues.HASH_POST_BEAN)).getDisplayName();
layout.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Tracker.getInstance().event((!editMode) ? BxEvent.POST_INPUTING:BxEvent.EDITPOST_INPUTING).append(Key.ACTION, actionName).end();
PostGoodsBean postBean = (PostGoodsBean) v.getTag(PostCommonValues.HASH_POST_BEAN);
if (postBean.getControlType().equals("select") || postBean.getControlType().equals("tableSelect")) {
if(postBean.getLevelCount() > 0){
ArrayList<MultiLevelSelectionFragment.MultiLevelItem> items =
new ArrayList<MultiLevelSelectionFragment.MultiLevelItem>();
for(int i = 0; i < postBean.getLabels().size(); ++ i){
MultiLevelSelectionFragment.MultiLevelItem t = new MultiLevelSelectionFragment.MultiLevelItem();
t.txt = postBean.getLabels().get(i);
t.id = postBean.getValues().get(i);
items.add(t);
}
Bundle bundle = createArguments(null, null);
bundle.putInt(ARG_COMMON_REQ_CODE, postBean.getName().hashCode());
bundle.putSerializable("items", items);
bundle.putInt("maxLevel", postBean.getLevelCount() - 1);
String selectedValue = null;
selectedValue = params.getData(postBean.getName());
if (selectedValue != null)
bundle.putString("selectedValue", selectedValue);
PostUtil.extractInputData(layout_txt, params);
CustomDialogBuilder cdb = new CustomDialogBuilder(getActivity(), getHandler(), bundle);
cdb.start();
}else{
Bundle bundle = createArguments(postBean.getDisplayName(), null);
bundle.putInt(ARG_COMMON_REQ_CODE, postBean.getName().hashCode());
bundle.putBoolean("singleSelection", false);
bundle.putSerializable("properties",(ArrayList<String>) postBean.getLabels());
TextView txview = (TextView)v.getTag(PostCommonValues.HASH_CONTROL);
if (txview != null)
{
bundle.putString("selected", txview.getText().toString());
}
((BaseActivity)getActivity()).pushFragment(new OtherPropertiesFragment(), bundle, false);
}//postBean.getLevelCount() <= 0
}else if(postBean.getControlType().equals("checkbox")){
if(postBean.getLabels().size() > 1){
Bundle bundle = createArguments(postBean.getDisplayName(), null);
bundle.putInt(ARG_COMMON_REQ_CODE, postBean.getName().hashCode());
bundle.putBoolean("singleSelection", false);
bundle.putSerializable("properties",(ArrayList<String>) postBean.getLabels());
TextView txview = (TextView)v.getTag(PostCommonValues.HASH_CONTROL);
if (txview != null){
bundle.putString("selected", txview.getText().toString());
}
((BaseActivity)getActivity()).pushFragment(new OtherPropertiesFragment(), bundle, false);
}
else{
View checkV = v.findViewById(R.id.checkitem);
if(checkV != null && checkV instanceof CheckBox){
((CheckBox)checkV).setChecked(!((CheckBox)checkV).isChecked());
}
}
}
}
});//layout.setOnClickListener:select or checkbox
} else {//not select or checkbox
final String actionName = ((PostGoodsBean)layout.getTag(PostCommonValues.HASH_POST_BEAN)).getDisplayName();
((View)layout.getTag(PostCommonValues.HASH_CONTROL)).setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
Tracker.getInstance().event((!editMode) ? BxEvent.POST_INPUTING:BxEvent.EDITPOST_INPUTING).append(Key.ACTION, actionName).end();
}
return false;
}
});
layout.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
View ctrl = (View) v.getTag(PostCommonValues.HASH_CONTROL);
ctrl.requestFocus();
InputMethodManager inputMgr = (InputMethodManager) ctrl.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
inputMgr.showSoftInput(ctrl, InputMethodManager.SHOW_IMPLICIT);
}
});
}
PostUtil.adjustMarginBottomAndHeight(layout);
return layout;
}
private void setDetailLocationControl(BXLocation location){
if(location == null) return;
if(locationView != null && locationView.findViewById(R.id.postinput) != null){
String address = (location.detailAddress == null || location.detailAddress.equals("")) ?
((location.subCityName == null || location.subCityName.equals("")) ?
""
: location.subCityName)
: location.detailAddress;
if(address == null || address.length() == 0) return;
if(location.adminArea != null && location.adminArea.length() > 0){
address = address.replaceFirst(location.adminArea, "");
}
if(location.cityName != null && location.cityName.length() > 0){
address = address.replaceFirst(location.cityName, "");
}
((TextView)locationView.findViewById(R.id.postinput)).setText(address);
}
}
public boolean hasGlobalTab() {
return false;
}
@Override
public void onUploadDone(String imagePath, String serverUrl,
Bitmap thumbnail) {
// TODO Auto-generated method stub
}
@Override
public void onUploading(String imagePath, Bitmap thumbnail) {
// TODO Auto-generated method stub
}
@Override
public void onUploadFail(String imagePath, Bitmap thumbnail) {
// TODO Auto-generated method stub
firstImage = ImageCacheManager.getInstance().loadBitmapFromResource(R.drawable.icon_load_fail);
if(getView() != null && getView().getRootView() != null){
getActivity().runOnUiThread(new Runnable(){
@Override
public void run(){
updateImageInfo(getView().getRootView());
}
});
}
}
}
| true | true | protected void handleMessage(Message msg, final Activity activity, final View rootView) {
hideProgress();
switch (msg.what) {
case MSG_DIALOG_BACK_WITH_DATA:{
Bundle bundle = (Bundle)msg.obj;
handleBackWithData(bundle.getInt(ARG_COMMON_REQ_CODE), bundle.getSerializable("lastChoise"));
break;
}
case MSG_UPDATE_IMAGE_LIST:{
updateImageInfo(rootView);
showInputMethod();
break;
}
case PostCommonValues.MSG_GET_META_SUCCEED:{
Button button = (Button) layout_txt.getRootView().findViewById(R.id.iv_post_finish);
if(button != null){
button.setEnabled(true);
}
postList = (LinkedHashMap<String, PostGoodsBean>)msg.obj;
addCategoryItem();
buildPostLayout(postList);
loadCachedData();
this.showGettingMetaProgress(false);
break;
}
case PostCommonValues.MSG_GET_META_FAIL:
hideProgress();
Button button = (Button) layout_txt.getRootView().findViewById(R.id.iv_post_finish);
if(button != null){
button.setEnabled(false);
}
addCategoryItem();
if(msg.obj != null){
ViewUtil.showToast(activity, (String)msg.obj, false);
}
this.showGettingMetaProgress(false);
break;
case PostCommonValues.MSG_POST_SUCCEED:
PerformanceTracker.stamp(Event.E_POST_SUCCEEDED);
hideProgress();
doClearUpImages();
String id = ((PostResultData)msg.obj).id;
boolean isRegisteredUser = ((PostResultData)msg.obj).isRegisteredUser;
String message = ((PostResultData)msg.obj).message;
int code = ((PostResultData)msg.obj).error;
if (!id.equals("") && code == 0) {
postResultSuccess();
ViewUtil.showToast(activity, message, false);
final Bundle args = createArguments(null, null);
args.putInt("forceUpdate", 1);
if(!editMode || (editMode && isActive)){
resetData(!editMode);
Util.deleteDataFromLocate(this.getActivity(), FILE_LAST_CATEGORY);
categoryEnglishName = "";
categoryName = "";
}
// showPost();
if(!editMode){
showPost();
String lp = getArguments().getString("lastPost");
if(lp != null && !lp.equals("")){
lp += "," + id;
}else{
lp = id;
}
args.putString("lastPost", lp);
args.putString("cateEnglishName", categoryEnglishName);
args.putBoolean(KEY_IS_EDITPOST, editMode);
args.putBoolean(KEY_LAST_POST_CONTACT_USER, isRegisteredUser);
if(activity != null){
args.putInt(MyAdFragment.TYPE_KEY, MyAdFragment.TYPE_MYPOST);
Intent intent = new Intent(CommonIntentAction.ACTION_BROADCAST_POST_FINISH);
intent.putExtras(args);
PerformanceTracker.stamp(Event.E_Post_Send_Success_Broadcast);
activity.sendBroadcast(intent);
}
doClearUpImages();
// finishFragment();
}else{
// showPost();
PostGoodsFragment.this.finishFragment(PostGoodsFragment.MSG_POST_SUCCEED, null);
}
}else{
postResultFail(message);
if(msg.obj != null){
handlePostFail((PostResultData)msg.obj);
}
}
break;
case PostCommonValues.MSG_POST_FAIL:
hideProgress();
if(msg.obj != null){
if(msg.obj instanceof String){
ViewUtil.showToast(activity, (String)msg.obj, false);
this.changeFocusAfterPostError((String)msg.obj);
}else if(msg.obj instanceof PostResultData){
handlePostFail((PostResultData)msg.obj);
postResultFail(((PostResultData)msg.obj).message);
}
}
break;
case PostCommonValues.MSG_POST_EXCEPTION:
hideProgress();
ViewUtil.showToast(activity, "网络连接异常", false);
break;
case ErrorHandler.ERROR_SERVICE_UNAVAILABLE:
hideProgress();
ErrorHandler.getInstance().handleMessage(msg);
// this.getView().findViewById(R.id.goodscontent).setVisibility(View.GONE);
// this.getView().findViewById(R.id.networkErrorView).setVisibility(View.VISIBLE);
// this.reCreateTitle();
// this.refreshHeader();
break;
case MSG_GEOCODING_TIMEOUT:
case PostCommonValues.MSG_GEOCODING_FETCHED:
Event evt = msg.what == MSG_GEOCODING_TIMEOUT ? Event.E_GeoCoding_Timeout : Event.E_GeoCoding_Fetched;
PerformanceTracker.stamp(evt);
showSimpleProgress();
handler.removeMessages(MSG_GEOCODING_TIMEOUT);
handler.removeMessages(PostCommonValues.MSG_GEOCODING_FETCHED);
postAd(msg.obj == null ? null : (BXLocation)msg.obj);
break;
case PostCommonValues.MSG_GPS_LOC_FETCHED:
detailLocation = (BXLocation)msg.obj;
break;
}
}
| protected void handleMessage(Message msg, final Activity activity, final View rootView) {
hideProgress();
switch (msg.what) {
case MSG_DIALOG_BACK_WITH_DATA:{
Bundle bundle = (Bundle)msg.obj;
handleBackWithData(bundle.getInt(ARG_COMMON_REQ_CODE), bundle.getSerializable("lastChoise"));
break;
}
case MSG_UPDATE_IMAGE_LIST:{
updateImageInfo(rootView);
showInputMethod();
break;
}
case PostCommonValues.MSG_GET_META_SUCCEED:{
Button button = (Button) layout_txt.getRootView().findViewById(R.id.iv_post_finish);
if(button != null){
button.setEnabled(true);
}
postList = (LinkedHashMap<String, PostGoodsBean>)msg.obj;
addCategoryItem();
buildPostLayout(postList);
loadCachedData();
this.showGettingMetaProgress(false);
break;
}
case PostCommonValues.MSG_GET_META_FAIL:
hideProgress();
Button button = (Button) layout_txt.getRootView().findViewById(R.id.iv_post_finish);
if(button != null){
button.setEnabled(false);
}
addCategoryItem();
if(msg.obj != null){
ViewUtil.showToast(activity, (String)msg.obj, false);
}
this.showGettingMetaProgress(false);
break;
case PostCommonValues.MSG_POST_SUCCEED:
PerformanceTracker.stamp(Event.E_POST_SUCCEEDED);
hideProgress();
doClearUpImages();
String id = ((PostResultData)msg.obj).id;
boolean isRegisteredUser = ((PostResultData)msg.obj).isRegisteredUser;
String message = ((PostResultData)msg.obj).message;
int code = ((PostResultData)msg.obj).error;
if (!id.equals("") && code == 0) {
postResultSuccess();
ViewUtil.showToast(activity, message, false);
final Bundle args = createArguments(null, null);
args.putInt("forceUpdate", 1);
if(!editMode || (editMode && isActive)){
resetData(!editMode);
Util.deleteDataFromLocate(this.getActivity(), FILE_LAST_CATEGORY);
categoryEnglishName = "";
categoryName = "";
}
// showPost();
if(!editMode){
showPost();
String lp = getArguments().getString("lastPost");
if(lp != null && !lp.equals("")){
lp += "," + id;
}else{
lp = id;
}
args.putString("lastPost", lp);
args.putString("cateEnglishName", categoryEnglishName);
args.putBoolean(KEY_IS_EDITPOST, editMode);
args.putBoolean(KEY_LAST_POST_CONTACT_USER, isRegisteredUser);
if(activity != null){
args.putInt(MyAdFragment.TYPE_KEY, MyAdFragment.TYPE_MYPOST);
Intent intent = new Intent(CommonIntentAction.ACTION_BROADCAST_POST_FINISH);
intent.putExtras(args);
PerformanceTracker.stamp(Event.E_Post_Send_Success_Broadcast);
activity.sendBroadcast(intent);
}
doClearUpImages();
// finishFragment();
}else{
// showPost();
PostGoodsFragment.this.finishFragment(PostGoodsFragment.MSG_POST_SUCCEED, null);
}
}else{
postResultFail(message);
if(msg.obj != null){
handlePostFail((PostResultData)msg.obj);
}
}
break;
case PostCommonValues.MSG_POST_FAIL:
hideProgress();
if(msg.obj != null){
if(msg.obj instanceof String){
ViewUtil.showToast(activity, (String)msg.obj, false);
this.changeFocusAfterPostError((String)msg.obj);
postResultFail((String)msg.obj);
}else if(msg.obj instanceof PostResultData){
handlePostFail((PostResultData)msg.obj);
postResultFail(((PostResultData)msg.obj).message);
}
}
break;
case PostCommonValues.MSG_POST_EXCEPTION:
hideProgress();
ViewUtil.showToast(activity, "网络连接异常", false);
break;
case ErrorHandler.ERROR_SERVICE_UNAVAILABLE:
hideProgress();
ErrorHandler.getInstance().handleMessage(msg);
// this.getView().findViewById(R.id.goodscontent).setVisibility(View.GONE);
// this.getView().findViewById(R.id.networkErrorView).setVisibility(View.VISIBLE);
// this.reCreateTitle();
// this.refreshHeader();
break;
case MSG_GEOCODING_TIMEOUT:
case PostCommonValues.MSG_GEOCODING_FETCHED:
Event evt = msg.what == MSG_GEOCODING_TIMEOUT ? Event.E_GeoCoding_Timeout : Event.E_GeoCoding_Fetched;
PerformanceTracker.stamp(evt);
showSimpleProgress();
handler.removeMessages(MSG_GEOCODING_TIMEOUT);
handler.removeMessages(PostCommonValues.MSG_GEOCODING_FETCHED);
postAd(msg.obj == null ? null : (BXLocation)msg.obj);
break;
case PostCommonValues.MSG_GPS_LOC_FETCHED:
detailLocation = (BXLocation)msg.obj;
break;
}
}
|
diff --git a/src/share/classes/com/sun/tools/javafx/comp/JavafxAbstractTranslation.java b/src/share/classes/com/sun/tools/javafx/comp/JavafxAbstractTranslation.java
index 59e2dde2d..ead35c5c7 100644
--- a/src/share/classes/com/sun/tools/javafx/comp/JavafxAbstractTranslation.java
+++ b/src/share/classes/com/sun/tools/javafx/comp/JavafxAbstractTranslation.java
@@ -1,2439 +1,2439 @@
/*
* Copyright 2009 Sun Microsystems, Inc. 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.
*
* 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package com.sun.tools.javafx.comp;
import com.sun.javafx.api.JavafxBindStatus;
import com.sun.javafx.api.tree.Tree.JavaFXKind;
import com.sun.tools.mjavac.code.Flags;
import com.sun.tools.mjavac.code.Kinds;
import com.sun.tools.mjavac.code.Symbol;
import com.sun.tools.mjavac.code.Symbol.ClassSymbol;
import com.sun.tools.mjavac.code.Symbol.MethodSymbol;
import com.sun.tools.mjavac.code.Symbol.VarSymbol;
import com.sun.tools.mjavac.code.Type;
import com.sun.tools.mjavac.code.TypeTags;
import com.sun.tools.mjavac.tree.JCTree;
import com.sun.tools.mjavac.tree.JCTree.*;
import com.sun.tools.mjavac.util.Context;
import com.sun.tools.mjavac.util.List;
import com.sun.tools.mjavac.util.ListBuffer;
import com.sun.tools.mjavac.util.Name;
import com.sun.tools.mjavac.util.JCDiagnostic.DiagnosticPosition;
import com.sun.tools.javafx.code.FunctionType;
import com.sun.tools.javafx.code.JavafxFlags;
import com.sun.tools.javafx.comp.JavafxInitializationBuilder.LiteralInitClassMap;
import com.sun.tools.javafx.comp.JavafxInitializationBuilder.LiteralInitVarMap;
import com.sun.tools.javafx.comp.JavafxTypeMorpher.TypeMorphInfo;
import com.sun.tools.javafx.comp.JavafxTypeMorpher.VarMorphInfo;
import com.sun.tools.javafx.tree.*;
import com.sun.tools.mjavac.code.Type.MethodType;
import com.sun.tools.mjavac.jvm.Target;
import com.sun.tools.mjavac.tree.JCTree.JCFieldAccess;
import com.sun.tools.mjavac.tree.TreeInfo;
import com.sun.tools.mjavac.tree.TreeTranslator;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.lang.model.type.TypeKind;
import static com.sun.tools.javafx.comp.JavafxAbstractTranslation.Yield.*;
/**
*
* @author Robert Field
*/
public abstract class JavafxAbstractTranslation<R extends JavafxAbstractTranslation.Result>
extends JavafxTranslationSupport
implements JavafxVisitor {
/*
* the result of translating a tree by a visit method
*/
R result;
final JavafxOptimizationStatistics optStat;
final Target target;
Type targetType;
Yield yieldKind;
ReceiverContext inInstanceContext = ReceiverContext.Oops;
private JavafxToJava toJava; //TODO: this should go away
protected JavafxAbstractTranslation(Context context, JavafxToJava toJava) {
super(context);
this.optStat = JavafxOptimizationStatistics.instance(context);
this.toJava = toJava; //TODO: temp hack
this.target = Target.instance(context);
}
/********** translation state tracking types and methods **********/
enum ReceiverContext {
// In a script function or script var init, implemented as a static method
ScriptAsStatic,
// In an instance function or instance var init, implemented as static
InstanceAsStatic,
// In an instance function or instance var init, implemented as an instance method
InstanceAsInstance,
// Should not see code in this state
Oops
}
enum Yield {
ToExpression,
ToStatement
}
Yield yield() {
return yieldKind;
}
JFXClassDeclaration currentClass() {
return getAttrEnv().enclClass;
}
void setCurrentClass(JFXClassDeclaration tree) {
getAttrEnv().enclClass = tree;
}
protected JavafxEnv<JavafxAttrContext> getAttrEnv() {
return toJava.getAttrEnv();
}
/********** Utility routines **********/
public static class NotYetImplementedException extends RuntimeException {
NotYetImplementedException(String msg) {
super(msg);
}
}
JCExpression TODO(String msg) {
throw new NotYetImplementedException("Not yet implemented: " + msg);
}
/**
* @return the substitutionMap
*/
Map<Symbol, Name> getSubstitutionMap() {
return toJava.getSubstitutionMap();
}
/**
* Class symbols for classes that need a reference to the outer class.
*/
Set<ClassSymbol> getHasOuters() {
return toJava.getHasOuters();
}
/**
* @return the literalInitClassMap
*/
LiteralInitClassMap getLiteralInitClassMap() {
return toJava.getLiteralInitClassMap();
}
/**
* Return the list of local variables accessed, but not defined within the FX expression.
* @param expr
* @return
*/
List<VarSymbol> localVars(JFXTree expr) {
final ListBuffer<VarSymbol> lb = ListBuffer.<VarSymbol>lb();
final Set<VarSymbol> exclude = new HashSet<VarSymbol>();
new JavafxTreeScanner() {
@Override
public void visitVar(JFXVar tree) {
exclude.add(tree.sym);
super.visitVar(tree);
}
}.scan(expr);
new JavafxTreeScanner() {
@Override
public void visitIdent(JFXIdent tree) {
if (tree.sym instanceof VarSymbol) {
VarSymbol vsym = (VarSymbol) (tree.sym);
if (vsym.owner.kind != Kinds.TYP && !exclude.contains(vsym)) {
// Local variable we haven't seen before, include it
lb.append(vsym);
exclude.add(vsym);
}
}
}
}.scan(expr);
return lb.toList();
}
/** Box up a single primitive expression. */
JCExpression makeBox(DiagnosticPosition diagPos, JCExpression translatedExpr, Type primitiveType) {
make.at(translatedExpr.pos());
Type boxedType = types.boxedTypeOrType(primitiveType);
JCExpression box;
if (target.boxWithConstructors()) {
Symbol ctor = lookupConstructor(translatedExpr.pos(),
boxedType,
List.<Type>nil().prepend(primitiveType));
box = make.Create(ctor, List.of(translatedExpr));
} else {
Symbol valueOfSym = lookupMethod(translatedExpr.pos(),
names.valueOf,
boxedType,
List.<Type>nil().prepend(primitiveType));
// JCExpression meth =makeIdentifier(valueOfSym.owner.type.toString() + "." + valueOfSym.name.toString());
JCExpression meth = make.Select(makeType(diagPos, valueOfSym.owner.type), valueOfSym.name);
TreeInfo.setSymbol(meth, valueOfSym);
meth.type = valueOfSym.type;
box = make.App(meth, List.of(translatedExpr));
}
return box;
}
/** Look up a method in a given scope.
*/
private MethodSymbol lookupMethod(DiagnosticPosition pos, Name name, Type qual, List<Type> args) {
return rs.resolveInternalMethod(pos, getAttrEnv(), qual, name, args, null);
}
//where
/** Look up a constructor.
*/
private MethodSymbol lookupConstructor(DiagnosticPosition pos, Type qual, List<Type> args) {
return rs.resolveInternalConstructor(pos, getAttrEnv(), qual, args, null);
}
ExpressionResult convertTranslated(ExpressionResult res, DiagnosticPosition diagPos, Type targettedType) {
return (targettedType == null || targettedType == syms.voidType) ?
res
: new ExpressionResult(
diagPos,
res.statements(),
new TypeConversionTranslator(diagPos, res.expr(), res.resultType, targettedType).doitExpr(),
res.bindees,
res.interClass,
targettedType);
}
JCExpression convertTranslated(JCExpression translated, DiagnosticPosition diagPos,
Type sourceType, Type targettedType) {
return (targettedType == null || targettedType == syms.voidType) ?
translated
: new TypeConversionTranslator(diagPos, translated, sourceType, targettedType).doitExpr();
}
/**
* Special handling for Strings and Durations. If a value assigned to one of these is null,
* the default value for the type must be substituted.
* inExpr is the input expression. outType is the desired result type.
* expr is the result value to use in the normal case.
* This doesn't handle the case var ss: String = if (true) null else "Hi there, sailor"
* But it does handle nulls coming in from Java method returns, and variables.
*/
protected JCExpression convertNullability(final DiagnosticPosition diagPos, final JCExpression expr,
final JFXExpression inExpr, final Type outType) {
return (new Translator(diagPos) {
Result doit() {
throw new IllegalArgumentException();
}
JCExpression doitExpr() {
if (outType != syms.stringType && outType != syms.javafx_DurationType) {
return expr;
}
final Type inType = inExpr.type;
if (inType == syms.botType || inExpr.getJavaFXKind() == JavaFXKind.NULL_LITERAL) {
return makeDefaultValue(diagPos, outType);
}
if (!types.isSameType(inType, outType) || isValueFromJava(inExpr)) {
JCVariableDecl daVar = makeTmpVar(outType, expr);
JCExpression toTest = id(daVar.name);
JCExpression cond = makeNotNullCheck(toTest);
JCExpression ret = m().Conditional(
cond,
id(daVar.name),
makeDefaultValue(diagPos, outType));
return makeBlockExpression(List.<JCStatement>of(daVar), ret);
}
return expr;
}
}).doitExpr();
}
JCExpression castFromObject (JCExpression arg, Type castType) {
return make.TypeCast(makeType(arg.pos(), types.boxedTypeOrType(castType)), arg);
}
/********** Result types **********/
public static abstract class Result {
final DiagnosticPosition diagPos;
Result(DiagnosticPosition diagPos) {
this.diagPos = diagPos;
}
abstract List<JCTree> trees();
}
public static abstract class AbstractStatementsResult extends Result {
private final List<JCStatement> stmts;
AbstractStatementsResult(DiagnosticPosition diagPos, List<JCStatement> stmts) {
super(diagPos);
this.stmts = stmts;
}
List<JCStatement> statements() {
return stmts;
}
List<JCTree> trees() {
ListBuffer<JCTree> ts = ListBuffer.lb();
for (JCTree t : stmts) {
ts.append(t);
}
return ts.toList();
}
}
public static class StatementsResult extends AbstractStatementsResult {
StatementsResult(DiagnosticPosition diagPos, List<JCStatement> stmts) {
super(diagPos, stmts);
}
StatementsResult(DiagnosticPosition diagPos, ListBuffer<JCStatement> buf) {
super(diagPos, buf.toList());
}
StatementsResult(JCStatement stmt) {
super(stmt.pos(), List.of(stmt));
}
}
public static class ExpressionResult extends AbstractStatementsResult {
public static class DependentPair {
public final VarSymbol instanceSym;
public final Symbol referencedSym;
DependentPair(VarSymbol instanceSym, Symbol referencedSym) {
this.instanceSym = instanceSym;
this.referencedSym = referencedSym;
}
}
private final JCExpression value;
private final List<VarSymbol> bindees;
private final List<DependentPair> interClass;
private final Type resultType;
ExpressionResult(DiagnosticPosition diagPos, List<JCStatement> stmts, JCExpression value, List<VarSymbol> bindees, List<DependentPair> interClass, Type resultType) {
super(diagPos, stmts);
this.value = value;
this.bindees = bindees;
this.interClass = interClass;
this.resultType = resultType;
}
ExpressionResult(DiagnosticPosition diagPos, ListBuffer<JCStatement> buf, JCExpression value, ListBuffer<VarSymbol> bindees, ListBuffer<DependentPair> interClass, Type resultType) {
this(diagPos, buf.toList(), value, bindees.toList(), interClass.toList(), resultType);
}
ExpressionResult(JCExpression value, List<VarSymbol> bindees, Type resultType) {
this(value.pos(), List.<JCStatement>nil(), value, bindees, List.<DependentPair>nil(), resultType);
}
ExpressionResult(JCExpression value, Type resultType) {
this(value, List.<VarSymbol>nil(), resultType);
}
JCExpression expr() {
return value;
}
List<VarSymbol> bindees() {
return bindees;
}
List<DependentPair> interClass() {
return interClass;
}
@Override
List<JCTree> trees() {
List<JCTree> ts = super.trees();
return value==null? ts : ts.append(value);
}
}
public static class SpecialResult extends Result {
private final JCTree tree;
SpecialResult(JCTree tree) {
super(tree.pos());
this.tree = tree;
}
JCTree tree() {
return tree;
}
@Override
public String toString() {
return "SpecialResult-" + tree.getClass() + " = " + tree;
}
List<JCTree> trees() {
return tree==null? List.<JCTree>nil() : List.<JCTree>of(tree);
}
}
/********** translation support **********/
private void translateCore(JFXTree expr, Type targettedType, Yield yield) {
JFXTree prevWhere = getAttrEnv().where;
Yield prevYield = yield();
Type prevTargetType = targetType;
getAttrEnv().where = expr;
yieldKind = yield;
targetType = targettedType;
expr.accept(this);
yieldKind = prevYield;
targetType = prevTargetType;
getAttrEnv().where = prevWhere;
}
ExpressionResult translateToExpressionResult(JFXExpression expr, Type targettedType) {
if (expr == null) {
return null;
} else {
translateCore(expr, targettedType, ToExpression);
ExpressionResult ret = (ExpressionResult)this.result;
this.result = null;
return convertTranslated(ret, expr.pos(), targettedType);
}
}
StatementsResult translateToStatementsResult(JFXExpression expr, Type targettedType) {
if (expr == null) {
return null;
} else {
translateCore(expr, targettedType, ToStatement);
Result ret = this.result;
this.result = null;
if (ret instanceof StatementsResult) {
return (StatementsResult) ret; // already converted
} else if (ret instanceof ExpressionResult) {
return new StatementsResult(expr.pos(), asStatements((ExpressionResult) ret, targettedType));
} else {
throw new RuntimeException(ret.toString());
}
}
}
class JCConverter extends JavaTreeBuilder {
private final AbstractStatementsResult res;
private final Type type;
JCConverter(AbstractStatementsResult res, Type type) {
super(res.diagPos);
this.res = res;
this.type = type;
}
List<JCStatement> asStatements() {
int typeTag = type.tag; // Blow up if we are passed null as the type of statements
List<JCStatement> stmts = res.statements();
if (res instanceof ExpressionResult) {
ExpressionResult eres = (ExpressionResult) res;
JCExpression expr = eres.expr();
if (expr != null) {
stmts = stmts.append(makeStatement(convertedExpression(eres), type));
}
}
return stmts;
}
JCStatement asStatement() {
List<JCStatement> stmts = asStatements();
if (stmts.length() == 1) {
return stmts.head;
} else {
return asBlock();
}
}
JCBlock asBlock() {
List<JCStatement> stmts = asStatements();
return m().Block(0L, stmts);
}
JCExpression asExpression() {
if (res instanceof ExpressionResult) {
ExpressionResult er = (ExpressionResult) res;
if (er.statements().nonEmpty()) {
BlockExprJCBlockExpression bexpr = new BlockExprJCBlockExpression(0L, er.statements(), convertedExpression(er));
bexpr.pos = er.expr().pos;
return bexpr;
} else {
return convertedExpression(er);
}
} else {
throw new IllegalArgumentException("must be ExpressionResult -- was: " + res);
}
}
private JCExpression convertedExpression(ExpressionResult eres) {
return convertTranslated(eres.expr(), diagPos, eres.resultType, type);
}
}
JCBlock asBlock(AbstractStatementsResult res, Type targettedType) {
return new JCConverter(res, targettedType).asBlock();
}
JCStatement asStatement(AbstractStatementsResult res, Type targettedType) {
return new JCConverter(res, targettedType).asStatement();
}
List<JCStatement> asStatements(AbstractStatementsResult res, Type targettedType) {
return new JCConverter(res, targettedType).asStatements();
}
JCExpression asExpression(AbstractStatementsResult res, Type targettedType) {
return new JCConverter(res, targettedType).asExpression();
}
JCExpression translateToExpression(JFXExpression expr, Type targettedType) {
return asExpression(translateToExpressionResult(expr, targettedType), targettedType);
}
JCStatement translateToStatement(JFXExpression expr, Type targettedType) {
return asStatement(translateToStatementsResult(expr, targettedType), targettedType);
}
JCBlock translateToBlock(JFXExpression expr, Type targettedType) {
if (expr == null) {
return null;
} else {
return asBlock(translateToStatementsResult(expr, targettedType), targettedType);
}
}
JCTree translateFunction(JFXFunctionDefinition tree, boolean maintainContext) {
return new FunctionTranslator(tree, maintainContext).doit().tree();
}
JCExpression translateLiteral(JFXLiteral tree) {
if (tree.typetag == TypeTags.BOT && types.isSequence(tree.type)) {
Type elemType = types.boxedElementType(tree.type);
JCExpression expr = accessEmptySequence(tree.pos(), elemType);
return castFromObject(expr, syms.javafx_SequenceTypeErasure);
} else {
return make.at(tree.pos).Literal(tree.typetag, tree.value);
}
}
/** Translate a single tree.
*/
SpecialResult translateToSpecialResult(JFXTree tree) {
SpecialResult ret;
if (tree == null) {
ret = null;
} else {
JFXTree prevWhere = getAttrEnv().where;
getAttrEnv().where = tree;
tree.accept(this);
getAttrEnv().where = prevWhere;
ret = (SpecialResult)this.result;
this.result = null;
}
return ret;
}
/********** Translators **********/
abstract class Translator extends JavaTreeBuilder {
Translator(DiagnosticPosition diagPos) {
super(diagPos);
}
abstract Result doit();
JavafxTreeMaker fxm() {
return fxmake.at(diagPos);
}
JCVariableDecl convertParam(JFXVar param) {
return makeParam(param.type, param.name);
}
/**
* Make a receiver expression that will reference the provided symbol.
* Return null if no receiver needed.
*/
JCExpression makeReceiver(Symbol sym) {
return makeReceiver(sym, true);
}
/**
* Make a receiver expression that will reference the provided symbol.
* Build the AST for accessing the outer member.
* The accessors might be chained if the member accessed is more than one level up in the outer chain.
* */
JCExpression makeReceiver(Symbol sym, boolean nullForThis) {
final Symbol owner = sym==null? null : sym.owner;
final Symbol siteOwner = currentClass().sym;
final JCExpression thisExpr = select(makeType(siteOwner.type), names._this);
JCExpression ret = types.isMixin(owner) ?
id(defs.receiverName) : // referenced member is a mixin member, access it through receiver var
thisExpr;
// check if it is in the chain
if (owner != null && siteOwner != null && siteOwner != owner) {
Symbol siteCursor = siteOwner;
boolean foundOwner = false;
int numOfOuters = 0;
ownerSearch:
while (siteCursor.kind != Kinds.PCK) {
ListBuffer<Type> supertypes = ListBuffer.lb();
Set<Type> superSet = new HashSet<Type>();
if (siteCursor.type != null) {
supertypes.append(siteCursor.type);
superSet.add(siteCursor.type);
}
if (siteCursor.kind == Kinds.TYP) {
types.getSupertypes(siteCursor, supertypes, superSet);
}
for (Type supType : supertypes) {
if (types.isSameType(supType, owner.type)) {
foundOwner = true;
break ownerSearch;
}
}
if (siteCursor.kind == Kinds.TYP) {
numOfOuters++;
}
siteCursor = siteCursor.owner;
}
if (foundOwner) {
// site was found up the outer class chain, add the chaining accessors
siteCursor = siteOwner;
while (numOfOuters > 0) {
if (siteCursor.kind == Kinds.TYP) {
ret = call(ret, defs.outerAccessorName);
}
if (siteCursor.kind == Kinds.TYP) {
numOfOuters--;
}
siteCursor = siteCursor.owner;
}
}
}
return (nullForThis && ret == thisExpr) ? null : ret;
}
}
abstract class ExpressionTranslator extends Translator {
private final ListBuffer<JCStatement> stmts = ListBuffer.lb();
private final ListBuffer<VarSymbol> bindees = ListBuffer.lb();
private final ListBuffer<ExpressionResult.DependentPair> interClass = ListBuffer.lb();
ExpressionTranslator(DiagnosticPosition diagPos) {
super(diagPos);
}
JCExpression translateExpr(JFXExpression expr, Type type) {
ExpressionResult res = translateToExpressionResult(expr, type);
stmts.appendList(res.statements());
bindees.appendList(res.bindees());
return res.expr();
}
List<JCExpression> translateExprs(List<JFXExpression> list) {
ListBuffer<JCExpression> trans = ListBuffer.lb();
for (List<JFXExpression> l = list; l.nonEmpty(); l = l.tail) {
JCExpression res = translateExpr(l.head, null);
if (res != null) {
trans.append(res);
}
}
return trans.toList();
}
void translateStmt(JFXExpression expr, Type targettedType) {
StatementsResult res = translateToStatementsResult(expr, targettedType);
stmts.appendList(res.statements());
}
void addPreface(JCStatement stmt) {
stmts.append(stmt);
}
void addPreface(List<JCStatement> list) {
stmts.appendList(list);
}
void addBindee(VarSymbol sym) {
if (!bindees.contains(sym)) {
bindees.append(sym);
}
}
void addBindees(List<VarSymbol> syms) {
for (VarSymbol sym : syms) {
addBindee(sym);
}
}
void addInterClassBindee(VarSymbol instanceSym, Symbol referencedSym) {
interClass.append(new ExpressionResult.DependentPair( instanceSym, referencedSym));
}
ExpressionResult toResult(JCExpression translated, Type resultType) {
return new ExpressionResult(diagPos, stmts, translated, bindees, interClass, resultType);
}
StatementsResult toStatementResult(JCExpression translated, Type resultType, Type targettedType) {
return toStatementResult(
(targettedType == null || targettedType == syms.voidType) ?
makeExec(translated)
: makeReturn(
convertTranslated(translated, diagPos, resultType, targettedType)));
}
StatementsResult toStatementResult(JCStatement translated) {
assert bindees.length() == 0;
return new StatementsResult(diagPos, stmts.append(translated));
}
List<JCStatement> statements() {
return stmts.toList();
}
List<VarSymbol> bindees() {
return bindees.toList();
}
abstract protected AbstractStatementsResult doit();
}
class StringExpressionTranslator extends ExpressionTranslator {
private final JFXStringExpression tree;
StringExpressionTranslator(JFXStringExpression tree) {
super(tree.pos());
this.tree = tree;
}
protected ExpressionResult doit() {
StringBuffer sb = new StringBuffer();
List<JFXExpression> parts = tree.getParts();
ListBuffer<JCExpression> values = new ListBuffer<JCExpression>();
JFXLiteral lit = (JFXLiteral) (parts.head); // "...{
sb.append((String) lit.value);
parts = parts.tail;
boolean containsDateTimeFormat = false;
while (parts.nonEmpty()) {
lit = (JFXLiteral) (parts.head); // optional format (or null)
String format = (String) lit.value;
if ((!containsDateTimeFormat) && format.length() > 0
&& JavafxDefs.DATETIME_FORMAT_PATTERN.matcher(format).find()) {
containsDateTimeFormat = true;
}
parts = parts.tail;
JFXExpression exp = parts.head;
JCExpression texp;
if (exp != null && types.isSameType(exp.type, syms.javafx_DurationType)) {
texp = call(translateExpr(exp, syms.javafx_DurationType), names.fromString("toMillis"));
texp = typeCast(diagPos, syms.javafx_LongType, syms.javafx_DoubleType, texp);
sb.append(format.length() == 0 ? "%dms" : format);
} else {
texp = translateExpr(exp, null);
sb.append(format.length() == 0 ? "%s" : format);
}
values.append(texp);
parts = parts.tail;
lit = (JFXLiteral) (parts.head); // }...{ or }..."
String part = (String)lit.value;
sb.append(part.replace("%", "%%")); // escape percent signs
parts = parts.tail;
}
JCLiteral formatLiteral = m().Literal(TypeTags.CLASS, sb.toString());
values.prepend(formatLiteral);
String formatMethod;
if (tree.translationKey != null) {
formatMethod = "com.sun.javafx.runtime.util.StringLocalization.getLocalizedString";
if (tree.translationKey.length() == 0) {
values.prepend(makeNull());
} else {
values.prepend(m().Literal(TypeTags.CLASS, tree.translationKey));
}
String resourceName =
currentClass().sym.flatname.toString().replace('.', '/').replaceAll("\\$.*", "");
values.prepend(m().Literal(TypeTags.CLASS, resourceName));
} else if (containsDateTimeFormat) {
formatMethod = "com.sun.javafx.runtime.util.FXFormatter.sprintf";
} else {
formatMethod = "java.lang.String.format";
}
JCExpression formatter = makeQualifiedTree(diagPos, formatMethod);
return toResult(m().Apply(null, formatter, values.toList()), syms.stringType);
}
}
abstract class MemberReferenceTranslator extends ExpressionTranslator {
protected MemberReferenceTranslator(DiagnosticPosition diagPos) {
super(diagPos);
}
JCExpression staticReference(Symbol sym) {
Symbol owner = sym.owner;
Symbol encl = currentClass().sym;
if (encl.name.endsWith(defs.scriptClassSuffixName) && owner == encl.owner) {
return null;
} else {
//TODO: see init builder getStaticContext() for a better implementation
Type classType = types.erasure(owner.type);
JCExpression expr = makeType(classType, false);
if (types.isJFXClass(owner)) {
Name simpleName;
switch (expr.getTag()) {
case JCTree.IDENT:
simpleName = ((JCIdent)expr).name;
break;
case JCTree.SELECT:
simpleName = ((JCFieldAccess)expr).name;
break;
default:
throw new RuntimeException("should not get here -- type name should be identifier or select");
}
// make X.X$Script
if (!JavafxInitializationBuilder.SCRIPT_LEVEL_AT_TOP) {
expr = select(expr, simpleName.append(defs.scriptClassSuffixName));
}
}
return expr;
}
}
JCExpression convertVariableReference(JCExpression varRef, Symbol sym) {
JCExpression expr = varRef;
if (sym instanceof VarSymbol) {
final VarSymbol vsym = (VarSymbol) sym;
VarMorphInfo vmi = typeMorpher.varMorphInfo(vsym);
boolean isFXMemberVar = vmi.isFXMemberVariable();
if (isFXMemberVar) {
// this is a reference to a JavaFX class variable, use getter
JCExpression instance;
// find referenced instance, null for current
switch (expr.getTag()) {
case JCTree.IDENT:
// if we are in a mixin class reference variables through the receiver
instance = currentClass().isMixinClass()?
id(defs.receiverName)
: null;
break;
case JCTree.SELECT:
instance = ((JCFieldAccess) varRef).getExpression();
break;
default:
throw new AssertionError();
}
expr = call(instance, attributeGetterName(vsym));
}
}
return expr;
}
}
abstract class NullCheckTranslator extends MemberReferenceTranslator {
protected final Symbol refSym;
protected final Type fullType;
protected final Type resultType;
protected final boolean staticReference;
NullCheckTranslator(DiagnosticPosition diagPos, Symbol sym, Type fullType) {
super(diagPos);
this.refSym = sym;
this.fullType = fullType;
this.resultType = targetType==null? fullType : targetType; // use targetType, if any
this.staticReference = refSym.isStatic();
}
abstract JFXExpression getToCheck();
abstract JCExpression fullExpression(JCExpression mungedToCheckTranslated);
boolean needNullCheck() {
return getToCheck() != null && !staticReference && !getToCheck().type.isPrimitive() && possiblyNull(getToCheck());
}
protected JCExpression preserveSideEffects(Type type, JFXExpression expr, JCExpression trans) {
if (needNullCheck() && expr!=null && hasSideEffects(expr)) {
// if there is going to be a null check (which thus could keep expr
// from being evaluated), and expr has side-effects, then eval
// it first and put it in a temp var.
return addTempVar(type, trans);
} else {
// no side-effects, just pass-through
return trans;
}
}
protected JCExpression addTempVar(Type varType, JCExpression trans) {
JCVariableDecl tmpVar = makeTmpVar("pse", varType, trans);
addPreface(tmpVar);
return id(tmpVar);
}
/**
* Translate the 'toCheck' of 'toCheck.name'.
* Override to specialize the translation.
* Note: 'toCheck' may or may not be in a LHS but in either
* event the selector is a value expression
*/
JCExpression translateToCheck(JFXExpression expr) {
if (staticReference) {
return staticReference(refSym);
} else if (expr == null) {
if (refSym != null && refSym.owner.kind == Kinds.TYP) {
// it is a non-static attribute or function class member
// reference it through the receiver
return makeReceiver(refSym);
}
return null;
}
Symbol selectorSym = expressionSymbol(expr);
// If this is OuterClass.memberName or MixinClass.memberName, then
// we want to create expression to get the proper receiver.
if (selectorSym != null && selectorSym.kind == Kinds.TYP) {
return makeReceiver(refSym);
}
Type exprType = expr.type;
// translate normally, preserving side-effects if need be
JCExpression tExpr = preserveSideEffects(exprType, expr, translateExpr(expr, exprType));
// if expr is primitve, box it
// expr.type is null for package symbols.
if (exprType != null && exprType.isPrimitive()) {
return makeBox(diagPos, tExpr, exprType);
}
return tExpr;
}
protected AbstractStatementsResult doit() {
JCExpression tToCheck = translateToCheck(getToCheck());
JCExpression full = fullExpression(tToCheck);
full = convertTranslated(full, diagPos, fullType, resultType);
if (!needNullCheck()) {
// no null check needed just return the translation
return toResult(full, resultType);
}
// Make an expression to use in null test.
// If translated toCheck is an identifier (tmp var or not), just make a new identifier.
// Otherwise, retranslate.
JCExpression toTest = (tToCheck instanceof JCIdent) ?
id(((JCIdent)tToCheck).name)
: translateToCheck(getToCheck());
// Do a null check
// we have a testable guard for null, test before the invoke (boxed conversions don't need a test)
JCExpression cond = makeNotNullCheck(toTest);
JCExpression defaultExpr = makeDefaultValue(diagPos, resultType);
if (yield() == ToStatement) {
// a statement is the desired result of the translation, return the If-statement
JCStatement nullAction = null;
if (resultType != null && resultType != syms.voidType) {
nullAction = makeStatement(defaultExpr, resultType);
}
return toStatementResult(
m().If(cond, makeStatement(full, resultType), nullAction));
} else {
// an expression is the desired result of the translation, convert it to a conditional expression
// if it would dereference null, then the full expression instead yields the default value
return toResult(
m().Conditional(cond, full, defaultExpr),
resultType);
}
}
private boolean possiblyNull(JFXExpression expr) {
if (expr == null) {
return true;
}
switch (expr.getFXTag()) {
case ASSIGN:
return possiblyNull(((JFXAssign)expr).getExpression());
case APPLY:
return true;
case BLOCK_EXPRESSION:
return possiblyNull(((JFXBlock)expr).getValue());
case IDENT: {
if (((JFXIdent)expr).sym instanceof VarSymbol) {
Symbol sym = ((JFXIdent)expr).sym;
return sym.name != names._this && sym.name != names._super;
} else {
return false;
}
}
case CONDEXPR:
return possiblyNull(((JFXIfExpression)expr).getTrueExpression()) || possiblyNull(((JFXIfExpression)expr).getFalseExpression());
case LITERAL:
return expr.getJavaFXKind() == JavaFXKind.NULL_LITERAL;
case PARENS:
return possiblyNull(((JFXParens)expr).getExpression());
case SELECT:
return ((JFXSelect)expr).sym instanceof VarSymbol;
case SEQUENCE_INDEXED:
return true;
case TYPECAST:
return possiblyNull(((JFXTypeCast)expr).getExpression());
case VAR_DEF:
return possiblyNull(((JFXVar)expr).getInitializer());
default:
return false;
}
}
}
class SelectTranslator extends NullCheckTranslator {
protected final JFXSelect tree;
protected final boolean isFunctionReference;
protected final Name name;
protected SelectTranslator(JFXSelect tree) {
super(tree.pos(), tree.sym, tree.type);
this.tree = tree;
this.isFunctionReference = tree.type instanceof FunctionType && refSym.type instanceof MethodType;
this.name = tree.getIdentifier();
}
@Override
JFXExpression getToCheck() {
return tree.getExpression();
}
@Override
JCExpression fullExpression(JCExpression tToCheck) {
if (isFunctionReference) {
MethodType mtype = (MethodType) refSym.type;
JCExpression translated = select(tToCheck, name);
return new FunctionValueTranslator(translated, null, diagPos, mtype, fullType).doitExpr();
} else {
JCExpression translated = select(tToCheck, name);
return convertVariableReference(translated, refSym);
}
}
}
class FunctionCallTranslator extends NullCheckTranslator {
// Function determination
protected final JFXExpression meth;
protected final JFXExpression selector;
protected final boolean thisCall;
protected final boolean superCall;
protected final MethodSymbol msym;
protected final Symbol selectorSym;
protected final boolean renameToThis;
protected final boolean renameToSuper;
protected final boolean superToStatic;
protected final boolean useInvoke;
protected final boolean callBound;
protected final boolean magicIsInitializedFunction;
// Call info
protected final List<JFXExpression> typeargs;
protected final List<JFXExpression> args;
// Null Checking control
protected final boolean knownNonNull;
FunctionCallTranslator(final JFXFunctionInvocation tree) {
super(tree.pos(), expressionSymbol(tree.meth), tree.type);
// Function determination
meth = tree.meth;
JFXSelect fieldAccess = meth.getFXTag() == JavafxTag.SELECT ? (JFXSelect) meth : null;
selector = fieldAccess != null ? fieldAccess.getExpression() : null;
msym = (refSym instanceof MethodSymbol) ? (MethodSymbol) refSym : null;
Name selectorIdName = (selector != null && selector.getFXTag() == JavafxTag.IDENT) ? ((JFXIdent) selector).getName() : null;
thisCall = selectorIdName == names._this;
superCall = selectorIdName == names._super;
ClassSymbol csym = currentClass().sym;
useInvoke = meth.type instanceof FunctionType;
selectorSym = selector != null? expressionSymbol(selector) : null;
boolean namedSuperCall =
msym != null && !msym.isStatic() &&
selectorSym instanceof ClassSymbol &&
// FIXME should also allow other enclosing classes:
types.isSuperType(selectorSym.type, csym);
boolean isMixinSuper = namedSuperCall && (selectorSym.flags_field & JavafxFlags.MIXIN) != 0;
boolean canRename = namedSuperCall && !isMixinSuper;
renameToThis = canRename && selectorSym == csym;
renameToSuper = canRename && selectorSym != csym;
superToStatic = (superCall || namedSuperCall) && isMixinSuper;
callBound = msym != null && !useInvoke &&
((msym.flags() & JavafxFlags.BOUND) != 0);
magicIsInitializedFunction = (msym != null) &&
(msym.flags_field & JavafxFlags.FUNC_IS_INITIALIZED) != 0;
// Call info
this.typeargs = tree.getTypeArguments();
this.args = tree.getArguments();
// Null Checking control
boolean selectorImmutable =
msym == null ||
msym.isStatic() ||
selector == null ||
selector.type.isPrimitive() ||
namedSuperCall ||
superCall ||
thisCall;
knownNonNull = selectorImmutable && !useInvoke;
}
@Override
JCExpression translateToCheck(JFXExpression expr) {
if (renameToSuper || superCall) {
return id(names._super);
} else if (renameToThis || thisCall) {
return id(names._this);
} else if (superToStatic) {
return staticReference(msym);
} else {
return super.translateToCheck(expr);
}
}
@Override
JCExpression fullExpression(JCExpression mungedToCheckTranslated) {
JCExpression tMeth = select(mungedToCheckTranslated, methodName());
JCMethodInvocation app = m().Apply(translateExprs(typeargs), tMeth, determineArgs());
JCExpression full = callBound ? makeBoundCall(app) : app;
if (useInvoke) {
if (resultType != syms.voidType) {
full = castFromObject(full, resultType);
}
}
return full;
}
Name methodName() {
return useInvoke? defs.invokeName : functionName(msym, superToStatic, callBound);
}
// This is for calls from non-bound contexts (code for true bound calls is in JavafxToBound)
JCExpression makeBoundCall(JCExpression applyExpression) {
return TODO("makeBoundCall");
}
@Override
JFXExpression getToCheck() {
return useInvoke? meth : selector;
}
@Override
boolean needNullCheck() {
return !knownNonNull && super.needNullCheck();
}
/**
* Compute the translated arguments.
*/
List<JCExpression> determineArgs() {
final List<Type> formals = meth.type.getParameterTypes();
final boolean usesVarArgs = args != null && msym != null &&
(msym.flags() & Flags.VARARGS) != 0 &&
(formals.size() != args.size() ||
types.isConvertible(args.last().type,
types.elemtype(formals.last())));
ListBuffer<JCExpression> targs = ListBuffer.lb();
// if this is a super.foo(x) call, "super" will be translated to referenced class,
// so we add a receiver arg to make a direct call to the implementing method MyClass.foo(receiver$, x)
if (superToStatic) {
targs.append(id(defs.receiverName));
}
if (callBound) {
//TODO: this code looks completely messed-up
/**
* If this is a bound call, use left-hand side references for arguments consisting
* solely of a var or attribute reference, or function call, otherwise, wrap it
* in an expression location
*/
List<Type> formal = formals;
for (JFXExpression arg : args) {
switch (arg.getFXTag()) {
case IDENT:
case SELECT:
case APPLY:
// This arg expression is one that will translate into a Location;
// since that is needed for a this into Location, do so.
// However, if the types need to by changed (subclass), this won't
// directly work.
// Also, if this is a mismatched sequence type, we will need
// to do some different
//TODO: never actually gets here
if (arg.type.equals(formal.head) ||
types.isSequence(formal.head) ||
formal.head == syms.objectType // don't add conversion for parameter type of java.lang.Object: doing so breaks the Pointer trick to obtain the original location (JFC-826)
) {
throw new RuntimeException("bogus bound call code");
//break;
}
//TODO: handle sequence subclasses
//TODO: use more efficient mechanism (use currently apears rare)
//System.err.println("Not match: " + arg.type + " vs " + formal.head);
// Otherwise, fall-through, presumably a conversion will work.
default: {
targs.append(translateExpr(arg, arg.type));
}
}
formal = formal.tail;
}
} else {
boolean handlingVarargs = false;
Type formal = null;
List<Type> t = formals;
for (List<JFXExpression> l = args; l.nonEmpty(); l = l.tail) {
JFXExpression arg = l.head;
if (!handlingVarargs) {
formal = t.head;
t = t.tail;
if (usesVarArgs && t.isEmpty()) {
formal = types.elemtype(formal);
handlingVarargs = true;
}
}
JCExpression targ;
if (magicIsInitializedFunction) {
//TODO: in theory, this could have side-effects (but only in theory)
//TODO: Lombard
targ = translateExpr(arg, formal);
} else {
targ = translateArg(arg, formal);
}
targs.append(targ);
}
}
return targs.toList();
}
JCExpression translateArg(JFXExpression arg, Type formal) {
return preserveSideEffects(formal, arg, translateExpr(arg, formal));
}
}
class TimeLiteralTranslator extends ExpressionTranslator {
JFXExpression value;
TimeLiteralTranslator(JFXTimeLiteral tree) {
super(tree.pos());
this.value = tree.value;
}
protected ExpressionResult doit() {
return toResult(
makeDurationLiteral(diagPos, translateExpr(value, syms.doubleType)),
syms.javafx_DurationType);
}
}
class FunctionTranslator extends Translator {
final JFXFunctionDefinition tree;
final boolean maintainContext;
final MethodType mtype;
final MethodSymbol sym;
final Symbol owner;
final Name name;
final boolean isBound;
final boolean isRunMethod;
final boolean isAbstract;
final boolean isStatic;
final boolean isSynthetic;
final boolean isInstanceFunction;
final boolean isInstanceFunctionAsStaticMethod;
final boolean isMixinClass;
FunctionTranslator(JFXFunctionDefinition tree, boolean maintainContext) {
super(tree.pos());
this.tree = tree;
this.maintainContext = maintainContext;
this.mtype = (MethodType) tree.type;
this.sym = (MethodSymbol) tree.sym;
this.owner = sym.owner;
this.name = tree.name;
this.isBound = (sym.flags() & JavafxFlags.BOUND) != 0;
this.isRunMethod = syms.isRunMethod(tree.sym);
this.isMixinClass = currentClass().isMixinClass();
long originalFlags = tree.mods.flags;
this.isAbstract = (originalFlags & Flags.ABSTRACT) != 0L;
this.isSynthetic = (originalFlags & Flags.SYNTHETIC) != 0L;
this.isStatic = (originalFlags & Flags.STATIC) != 0L;
this.isInstanceFunction = !isAbstract && !isStatic && !isSynthetic;
this.isInstanceFunctionAsStaticMethod = isInstanceFunction && isMixinClass;
}
private JCBlock makeRunMethodBody(JFXBlock bexpr) {
final JFXExpression value = bexpr.value;
JCBlock block;
if (value == null || value.type == syms.voidType) {
// the block has no value: translate as simple statement and add a null return
block = translateToBlock(bexpr, syms.voidType);
block.stats = block.stats.append(makeReturn(makeNull()));
} else {
// block has a value, return it
block = translateToBlock(bexpr, value.type);
final Type valueType = value.type;
if (valueType != null && valueType.isPrimitive()) {
// box up any primitives returns so they return Object -- the return type of the run method
new TreeTranslator() {
@Override
public void visitReturn(JCReturn tree) {
tree.expr = makeBox(tree.expr.pos(), tree.expr, valueType);
result = tree;
}
// do not descend into inner classes
@Override
public void visitClassDef(JCClassDecl tree) {
result = tree;
}
}.translate(block);
}
}
return block;
}
private long methodFlags() {
long methodFlags = tree.mods.flags;
methodFlags &= ~Flags.PROTECTED;
methodFlags &= ~Flags.SYNTHETIC;
methodFlags |= Flags.PUBLIC;
if (isInstanceFunctionAsStaticMethod) {
methodFlags |= Flags.STATIC;
}
return methodFlags;
}
private List<JCVariableDecl> methodParameters() {
ListBuffer<JCVariableDecl> params = ListBuffer.lb();
if (isInstanceFunctionAsStaticMethod) {
// if we are converting a standard instance function (to a static method), the first parameter becomes a reference to the receiver
params.prepend(makeReceiverParam(currentClass()));
}
for (JFXVar fxVar : tree.getParams()) {
params.append(convertParam(fxVar));
}
return params.toList();
}
private JCBlock methodBody() {
// construct the body of the translated function
JFXBlock bexpr = tree.getBodyExpression();
JCBlock body;
if (bexpr == null) {
body = null; // null if no block expression
} else if (isBound) {
TODO("bound function building"); body = null;
} else if (isRunMethod) {
// it is a module level run method, do special translation
body = makeRunMethodBody(bexpr);
} else {
// the "normal" case
ListBuffer<JCStatement> stmts = ListBuffer.lb();
for (JFXVar fxVar : tree.getParams()) {
if (types.isSequence(fxVar.sym.type)) {
setDiagPos(fxVar);
stmts.append(callStmt(id(fxVar.getName()), defs.incrementSharingMethodName));
}
}
setDiagPos(bexpr);
stmts.appendList(translateToStatementsResult(bexpr, mtype.getReturnType()).statements());
body = m().Block(0L, stmts.toList());
}
if (isInstanceFunction && !isMixinClass) {
//TODO: unfortunately, some generated code still expects a receiver$ to always be present.
// In the instance as instance case, there is no receiver param, so allow generated code
// to function by adding: var receiver = this;
//TODO: this should go away
body.stats = body.stats.prepend( m().VarDef(
m().Modifiers(Flags.FINAL),
defs.receiverName,
id(interfaceName(currentClass())),
id(names._this)));
}
return body;
}
private JCMethodDecl makeMethod(long flags, JCBlock body, List<JCVariableDecl> params) {
JCMethodDecl meth = m().MethodDef(
addAccessAnnotationModifiers(diagPos, tree.mods.flags, m().Modifiers(flags)),
functionName(sym, isInstanceFunctionAsStaticMethod, isBound),
makeReturnTypeTree(diagPos, sym, isBound),
m().TypeParams(mtype.getTypeArguments()),
params,
m().Types(mtype.getThrownTypes()), // makeThrows(diagPos), //
body,
null);
meth.sym = sym;
meth.type = tree.type;
return meth;
}
protected SpecialResult doit() {
JFXTree prevWhere = getAttrEnv().where;
Yield prevYield = yield();
Type prevTargetType = targetType;
getAttrEnv().where = tree;
yieldKind = ToStatement;
targetType = null;
ReceiverContext prevContext = inInstanceContext;
if (!maintainContext) {
inInstanceContext = isStatic ?
ReceiverContext.ScriptAsStatic :
isInstanceFunctionAsStaticMethod ?
ReceiverContext.InstanceAsStatic :
ReceiverContext.InstanceAsInstance;
}
try {
return new SpecialResult(makeMethod(methodFlags(), methodBody(), methodParameters()));
} finally {
inInstanceContext = prevContext;
yieldKind = prevYield;
targetType = prevTargetType;
getAttrEnv().where = prevWhere;
}
}
}
class IdentTranslator extends MemberReferenceTranslator {
JFXIdent tree;
IdentTranslator(JFXIdent tree) {
super(tree.pos());
this.tree = tree;
}
protected ExpressionResult doit() {
return toResult(doitExpr(), tree.type);
}
protected JCExpression doitExpr() {
if (tree.name == names._this) {
// in the static implementation method, "this" becomes "receiver$"
return makeReceiver(tree.sym, false);
} else if (tree.name == names._super) {
if (types.isMixin(tree.type.tsym)) {
// "super" becomes just the class where the static implementation method is defined
// the rest of the implementation is in visitFunctionInvocation
return id(tree.type.tsym.name);
} else {
// Just use super.
return id(tree.name);
}
}
int kind = tree.sym.kind;
if (kind == Kinds.TYP) {
// This is a class name, replace it with the full name (no generics)
return makeType(types.erasure(tree.sym.type), false);
}
// if this is an instance reference to an attribute or function, it needs to go the the "receiver$" arg,
// and possible outer access methods
JCExpression convert;
boolean isStatic = tree.sym.isStatic();
if (isStatic) {
// make class-based direct static reference: Foo.x
convert = select(staticReference(tree.sym), tree.name);
} else {
if ((kind == Kinds.VAR || kind == Kinds.MTH) &&
tree.sym.owner.kind == Kinds.TYP) {
// it is a non-static attribute or function class member
// reference it through the receiver
convert = select(makeReceiver(tree.sym), tree.name);
} else {
convert = id(tree.name);
}
}
if (tree.type instanceof FunctionType && tree.sym.type instanceof MethodType) {
MethodType mtype = (MethodType) tree.sym.type;
JFXFunctionDefinition def = null; // FIXME
return new FunctionValueTranslator(convert, def, tree.pos(), mtype, tree.type).doitExpr();
}
return convertVariableReference(convert, tree.sym);
}
}
abstract class AssignTranslator extends NullCheckTranslator {
protected final JFXExpression lhs;
protected final JFXExpression rhs;
protected final JFXExpression selector;
protected final JCExpression rhsTranslated;
private final JCExpression rhsTranslatedPreserved;
protected final boolean useSetters;
AssignTranslator(final DiagnosticPosition diagPos, final JFXExpression lhs, final JFXExpression rhs) {
super(diagPos, expressionSymbol(lhs), lhs.type);
this.lhs = lhs;
this.rhs = rhs;
this.selector = (lhs instanceof JFXSelect) ? ((JFXSelect) lhs).getExpression() : null;
this.rhsTranslated = convertNullability(diagPos, translateExpr(rhs, rhsType()), rhs, rhsType());
this.rhsTranslatedPreserved = preserveSideEffects(lhs.type, rhs, rhsTranslated);
this.useSetters = refSym==null? false : typeMorpher.varMorphInfo(refSym).useAccessors();
}
abstract JCExpression defaultFullExpression(JCExpression lhsTranslated, JCExpression rhsTranslated);
abstract JCExpression buildRHS(JCExpression rhsTranslated);
@Override
JFXExpression getToCheck() {
return selector;
}
@Override
boolean needNullCheck() {
return selector != null && super.needNullCheck();
}
@Override
JCExpression fullExpression(JCExpression tToCheck) {
if (lhs.getFXTag() == JavafxTag.SEQUENCE_INDEXED) {
// set of a sequence element -- s[i]=8, call the sequence set method
JFXSequenceIndexed si = (JFXSequenceIndexed) lhs;
JFXExpression seq = si.getSequence();
JCExpression index = translateExpr(si.getIndex(), syms.intType);
if (seq.type.tag == TypeTags.ARRAY) {
JCExpression tseq = translateExpr(seq, null); //FIXME
return m().Assign(m().Indexed(tseq, index), buildRHS(rhsTranslated));
} else {
JCExpression tseq = translateExpr(seq, null); //FIXME
return call(tseq, defs.setMethodName, index, buildRHS(rhsTranslated));
}
} else {
if (useSetters) {
return postProcessExpression(buildSetter(tToCheck, buildRHS(rhsTranslatedPreserved)));
} else {
return defaultFullExpression(translateExpr(lhs, null), rhsTranslated);
}
}
}
/**
* Override to change the translation type of the right-hand side
*/
protected Type rhsType() {
return refSym == null ? lhs.type : refSym.type; // Handle type inferencing not reseting the ident type
}
/**
* Override to change result in the non-default case.
*/
protected JCExpression postProcessExpression(JCExpression built) {
return built;
}
JCExpression buildSetter(JCExpression tc, JCExpression rhsComplete) {
return call(tc, attributeSetterName(refSym), rhsComplete);
}
}
class UnaryOperationTranslator extends ExpressionTranslator {
private final JFXUnary tree;
private final JFXExpression expr;
private final JCExpression transExpr;
UnaryOperationTranslator(JFXUnary tree) {
super(tree.pos());
this.tree = tree;
this.expr = tree.getExpression();
this.transExpr = translateExpr(expr, expr.type);
}
JCExpression translateSizeof(JFXExpression expr, JCExpression transExpr) {
return runtime(diagPos, defs.Sequences_size, List.of(transExpr));
}
private ExpressionResult doIncDec(final int binaryOp, final boolean postfix) {
return (ExpressionResult) new AssignTranslator(diagPos, expr, fxm().Literal(1)) {
JCExpression translateExpression(JFXExpression expr, Type type) {
return UnaryOperationTranslator.this.translateExpr(expr, type);
}
private JCExpression castIfNeeded(JCExpression transExpr) {
int ttag = expr.type.tag;
if (ttag == TypeTags.BYTE || ttag == TypeTags.SHORT) {
return m().TypeCast(expr.type, transExpr);
}
return transExpr;
}
@Override
JCExpression buildRHS(JCExpression rhsTranslated) {
return castIfNeeded(makeBinary(binaryOp, transExpr, rhsTranslated));
}
@Override
JCExpression defaultFullExpression(JCExpression lhsTranslated, JCExpression rhsTranslated) {
return m().Unary(tree.getOperatorTag(), lhsTranslated);
}
@Override
protected JCExpression postProcessExpression(JCExpression built) {
if (postfix) {
// this is a postfix operation, undo the value (not the variable) change
return castIfNeeded(makeBinary(binaryOp, (JCExpression) built, m().Literal(-1)));
} else {
// prefix operation
return built;
}
}
}.doit();
}
protected ExpressionResult doit() {
switch (tree.getFXTag()) {
case SIZEOF:
if (expr.type.tag == TypeTags.ARRAY) {
return toResult(select(transExpr, defs.lengthName), syms.intType);
}
return toResult(translateSizeof(expr, transExpr), syms.intType);
case REVERSE:
if (types.isSequence(expr.type)) {
// call runtime reverse of a sequence
return toResult(
call(
makeQualifiedTree(diagPos, "com.sun.javafx.runtime.sequence.Sequences"),
"reverse", transExpr),
expr.type);
} else {
// this isn't a sequence, just make it a sequence
return toResult(convertTranslated(transExpr, diagPos, expr.type, targetType), targetType);
}
case PREINC:
return doIncDec(JCTree.PLUS, false);
case PREDEC:
return doIncDec(JCTree.MINUS, false);
case POSTINC:
return doIncDec(JCTree.PLUS, true);
case POSTDEC:
return doIncDec(JCTree.MINUS, true);
case NEG:
if (types.isSameType(tree.type, syms.javafx_DurationType)) {
return toResult(
call(translateExpr(tree.arg, tree.arg.type), names.fromString("negate")),
syms.javafx_DurationType);
}
default:
return toResult(
makeUnary(tree.getOperatorTag(), transExpr),
tree.type);
}
}
}
class BinaryOperationTranslator extends ExpressionTranslator {
final JFXBinary tree;
final Type lhsType;
final Type rhsType;
BinaryOperationTranslator(DiagnosticPosition diagPos, final JFXBinary tree) {
super(diagPos);
this.tree = tree;
this.lhsType = tree.lhs.type;
this.rhsType = tree.rhs.type;
}
JCExpression lhs(Type type) {
return translateExpr(tree.lhs, type);
}
JCExpression lhs() {
return lhs(null);
}
JCExpression rhs(Type type) {
return translateExpr(tree.rhs, type);
}
JCExpression rhs() {
return rhs(null);
}
//TODO: after type system is figured out, this needs to be revisited
/**
* Check if a primitive has the default value for its type.
*/
private JCExpression makePrimitiveNullCheck(Type argType, JCExpression arg) {
TypeMorphInfo tmi = typeMorpher.typeMorphInfo(argType);
JCExpression defaultValue = makeLit(diagPos, tmi.getRealType(), tmi.getDefaultValue());
return makeEqual(arg, defaultValue);
}
/**
* Check if a non-primitive has the default value for its type.
*/
private JCExpression makeObjectNullCheck(Type argType, JCExpression arg) {
TypeMorphInfo tmi = typeMorpher.typeMorphInfo(argType);
if (tmi.isSequence() || tmi.getRealType() == syms.javafx_StringType) {
return callRuntime(JavafxDefs.isNullMethodString, List.of(arg));
} else {
return makeNullCheck(arg);
}
}
private JCExpression callRuntime(String methNameString, List<JCExpression> args) {
JCExpression meth = makeQualifiedTree(diagPos, methNameString);
List<JCExpression> typeArgs = List.nil();
return m().Apply(typeArgs, meth, args);
}
/**
* Make a .equals() comparison with a null check on the receiver
*/
private JCExpression makeFullCheck(JCExpression lhs, JCExpression rhs) {
return callRuntime(JavafxDefs.equalsMethodString, List.of(lhs, rhs));
}
/**
* Return the translation for a == comparision
*/
private JCExpression translateEqualsEquals() {
final boolean reqSeq = types.isSequence(lhsType) ||
types.isSequence(rhsType);
Type expected = tree.operator.type.getParameterTypes().head;
if (reqSeq) {
Type left = types.isSequence(lhsType) ? types.elementType(lhsType) : lhsType;
Type right = types.isSequence(rhsType) ? types.elementType(rhsType) : rhsType;
if (left.isPrimitive() && right.isPrimitive() && left == right) {
expected = left;
}
}
Type req = reqSeq ? types.sequenceType(expected) : null;
// this is an x == y
if (lhsType.getKind() == TypeKind.NULL) {
if (rhsType.getKind() == TypeKind.NULL) {
// both are known to be null
return m().Literal(TypeTags.BOOLEAN, 1);
} else if (rhsType.isPrimitive()) {
// lhs is null, rhs is primitive, do default check
return makePrimitiveNullCheck(rhsType, rhs(req));
} else {
// lhs is null, rhs is non-primitive, figure out what check to do
return makeObjectNullCheck(rhsType, rhs(req));
}
} else if (lhsType.isPrimitive()) {
if (rhsType.getKind() == TypeKind.NULL) {
// lhs is primitive, rhs is null, do default check on lhs
return makePrimitiveNullCheck(lhsType, lhs(req));
} else if (rhsType.isPrimitive()) {
// both are primitive, use ==
return makeEqual(lhs(req), rhs(req));
} else {
// lhs is primitive, rhs is non-primitive, use equals(), but switch them
JCVariableDecl sl = makeTmpVar(req!=null? req : lhsType, lhs(req)); // eval first to keep the order correct
return makeBlockExpression(List.<JCStatement>of(sl), makeFullCheck(rhs(req), id(sl.name)));
}
} else {
if (rhsType.getKind() == TypeKind.NULL) {
// lhs is non-primitive, rhs is null, figure out what check to do
return makeObjectNullCheck(lhsType, lhs(req));
} else {
// lhs is non-primitive, use equals()
return makeFullCheck(lhs(req), rhs(req));
}
}
}
JCExpression op(JCExpression leftSide, Name methodName, JCExpression rightSide) {
return call(leftSide, methodName, rightSide);
}
boolean isDuration(Type type) {
return types.isSameType(type, syms.javafx_DurationType);
}
final Type durationNumericType = syms.javafx_NumberType;
JCExpression durationOp() {
switch (tree.getFXTag()) {
case PLUS:
return op(lhs(), defs.durOpAdd, rhs());
case MINUS:
return op(lhs(), defs.durOpSub, rhs());
case DIV:
return op(lhs(), defs.durOpDiv, rhs(isDuration(rhsType)? null : durationNumericType));
case MUL: {
// lhs.mul(rhs);
JCExpression rcvr;
JCExpression arg;
if (isDuration(lhsType)) {
rcvr = lhs();
arg = rhs(durationNumericType);
} else {
//TODO: This may get side-effects out-of-order.
// A simple fix is to use a static Duration.mul(double,Duration).
// Another is to use a Block and a temporary.
rcvr = rhs();
arg = lhs(durationNumericType);
}
return op(rcvr, defs.durOpMul, arg);
}
case LT:
return op(lhs(), defs.durOpLT, rhs());
case LE:
return op(lhs(), defs.durOpLE, rhs());
case GT:
return op(lhs(), defs.durOpGT, rhs());
case GE:
return op(lhs(), defs.durOpGE, rhs());
}
throw new RuntimeException("Internal Error: bad Duration operation");
}
/**
* Translate a binary expressions
*/
protected ExpressionResult doit() {
return toResult(doitExpr(), tree.type);
}
JCExpression doitExpr() {
//TODO: handle <>
if (tree.getFXTag() == JavafxTag.EQ) {
return translateEqualsEquals();
} else if (tree.getFXTag() == JavafxTag.NE) {
return makeNot(translateEqualsEquals());
} else {
// anything other than == or !=
// Duration type operator overloading
if ((isDuration(lhsType) || isDuration(rhsType)) &&
tree.operator == null) { // operator check is to try to get a decent error message by falling through if the Duration method isn't matched
return durationOp();
}
return makeBinary(tree.getOperatorTag(), lhs(), rhs());
}
}
}
class TypeConversionTranslator extends ExpressionTranslator {
final JCExpression translated;
final Type sourceType;
final Type targettedType;
final boolean sourceIsSequence;
final boolean targetIsSequence;
final boolean sourceIsArray;
final boolean targetIsArray;
TypeConversionTranslator(DiagnosticPosition diagPos, JCExpression translated, Type sourceType, Type targettedType) {
super(diagPos);
this.translated = translated;
this.sourceType = sourceType;
this.targettedType = targettedType;
this.sourceIsSequence = types.isSequence(sourceType);
this.targetIsSequence = types.isSequence(targettedType);
this.sourceIsArray = types.isArray(sourceType);
this.targetIsArray = types.isArray(targettedType);
}
private JCExpression convertNumericSequence(final DiagnosticPosition diagPos,
final JCExpression expr, final Type inElementType, final Type targetElementType) {
JCExpression inTypeInfo = makeTypeInfo(diagPos, inElementType);
JCExpression targetTypeInfo = makeTypeInfo(diagPos, targetElementType);
return runtime(diagPos,
defs.Sequences_convertNumberSequence,
List.of(targetTypeInfo, inTypeInfo, expr));
}
protected ExpressionResult doit() {
return toResult(doitExpr(), targettedType);
}
JCExpression doitExpr() {
assert sourceType != null;
assert targettedType != null;
if (targettedType.tag == TypeTags.UNKNOWN) {
//TODO: this is bad attribution
return translated;
}
if (types.isSameType(targettedType, sourceType)) {
return translated;
}
if (targetIsArray) {
Type elemType = types.elemtype(targettedType);
if (sourceIsSequence) {
if (elemType.isPrimitive()) {
String mname;
if (elemType == syms.byteType) {
mname = "toByteArray";
} else if (elemType == syms.shortType) {
mname = "toShortArray";
} else if (elemType == syms.intType) {
mname = "toIntArray";
} else if (elemType == syms.longType) {
mname = "toLongArray";
} else if (elemType == syms.floatType) {
mname = "toFloatArray";
} else if (elemType == syms.doubleType) {
mname = "toDoubleArray";
} else if (elemType == syms.booleanType) {
mname = "toBooleanArray";
} else {
mname = "toArray";
}
return call(makeType(syms.javafx_SequencesType, false),
mname, translated);
}
ListBuffer<JCStatement> stats = ListBuffer.lb();
JCVariableDecl tmpVar = makeTmpVar(sourceType, translated);
stats.append(tmpVar);
JCVariableDecl sizeVar = makeTmpVar(syms.intType, call(id(tmpVar.name), "size"));
stats.append(sizeVar);
JCVariableDecl arrVar = makeTmpVar("arr", targettedType, make.at(diagPos).NewArray(
makeType(elemType, true),
List.<JCExpression>of(id(sizeVar.name)),
null));
stats.append(arrVar);
stats.append(callStmt(id(tmpVar.name), "toArray", List.of(
makeInt(0),
id(sizeVar),
id(arrVar),
makeInt(0))));
return makeBlockExpression(stats, id(arrVar));
} else {
//TODO: conversion may be needed here, but this is better than what we had
return translated;
}
} else if (sourceIsArray && targetIsSequence) {
Type sourceElemType = types.elemtype(sourceType);
List<JCExpression> args;
if (sourceElemType.isPrimitive()) {
args = List.of(translated);
} else {
args = List.of(makeTypeInfo(diagPos, sourceElemType), translated);
}
JCExpression cSequences = makeType(syms.javafx_SequencesType, false);
return call(cSequences, "fromArray", args);
}
if (targetIsSequence && !sourceIsSequence) {
//if (sourceType.tag == TypeTags.BOT) {
// // it is a null, convert to empty sequence
// //TODO: should we leave this null?
// Type elemType = types.elemtype(type);
// return makeEmptySequenceCreator(diagPos, elemType);
//}
Type targetElemType = types.elementType(targettedType);
JCExpression cSequences = makeType(syms.javafx_SequencesType, false);
JCExpression expr = convertTranslated(translated, diagPos, sourceType, targetElemType);
// This would be redundant, if convertTranslated did a cast if needed.
expr = makeTypeCast(diagPos, targetElemType, sourceType, expr);
return call(
cSequences,
"singleton",
makeTypeInfo(diagPos, targetElemType), expr);
}
if (targetIsSequence && sourceIsSequence) {
Type sourceElementType = types.elementType(sourceType);
Type targetElementType = types.elementType(targettedType);
if (!types.isSameType(sourceElementType, targetElementType) &&
types.isNumeric(sourceElementType) && types.isNumeric(targetElementType)) {
return convertNumericSequence(diagPos,
translated,
sourceElementType,
targetElementType);
}
}
// Convert primitive/Object types
Type unboxedTargetType = targettedType.isPrimitive() ? targettedType : types.unboxedType(targettedType);
Type unboxedSourceType = sourceType.isPrimitive() ? sourceType : types.unboxedType(sourceType);
JCExpression res = translated;
Type curType = sourceType;
if (unboxedTargetType != Type.noType && unboxedSourceType != Type.noType) {
// (boxed or unboxed) primitive to (boxed or unboxed) primitive
if (!curType.isPrimitive()) {
// unboxed source if sourceboxed
res = make.at(diagPos).TypeCast(unboxedSourceType, res);
curType = unboxedSourceType;
}
if (unboxedSourceType != unboxedTargetType) {
// convert as primitive types
- res = make.at(diagPos).TypeCast(unboxedTargetType, res);
+ res = make.at(diagPos).TypeCast(unboxedTargetType, make.at(diagPos).TypeCast(unboxedSourceType, res));
curType = unboxedTargetType;
}
if (!targettedType.isPrimitive()) {
// box target if target boxed
res = make.at(diagPos).TypeCast(makeType(targettedType, false), res);
curType = targettedType;
}
} else {
if (curType.isCompound() || curType.isPrimitive()) {
res = make.at(diagPos).TypeCast(makeType(types.erasure(targettedType), true), res);
}
}
// We should add a cast "when needed". Then visitTypeCast would just
// call this function, and not need to call makeTypeCast on the result.
// However, getting that to work is a pain - giving up for now. FIXME
return res;
}
}
class FunctionValueTranslator extends ExpressionTranslator {
private final JCExpression meth;
private final JFXFunctionDefinition def;
private final MethodType mtype;
private final Type resultType;
FunctionValueTranslator(JCExpression meth, JFXFunctionDefinition def, DiagnosticPosition diagPos, MethodType mtype, Type resultType) {
super(diagPos);
this.meth = meth;
this.def = def;
this.mtype = mtype;
this.resultType = resultType;
}
protected ExpressionResult doit() {
return toResult(doitExpr(), resultType);
}
JCExpression doitExpr() {
ListBuffer<JCTree> members = new ListBuffer<JCTree>();
if (def != null) {
// Translate the definition, maintaining the current inInstanceContext
members.append(translateFunction(def, true));
}
JCExpression encl = null;
int nargs = mtype.argtypes.size();
Type ftype = syms.javafx_FunctionTypes[nargs];
JCExpression t = makeQualifiedTree(null, ftype.tsym.getQualifiedName().toString());
ListBuffer<JCExpression> typeargs = new ListBuffer<JCExpression>();
Type rtype = types.boxedTypeOrType(mtype.restype);
typeargs.append(makeType(rtype));
ListBuffer<JCVariableDecl> params = new ListBuffer<JCVariableDecl>();
ListBuffer<JCExpression> margs = new ListBuffer<JCExpression>();
int i = 0;
for (List<Type> l = mtype.argtypes; l.nonEmpty(); l = l.tail) {
Name pname = make.paramName(i++);
Type ptype = types.boxedTypeOrType(l.head);
JCVariableDecl param = makeParam(ptype, pname);
params.append(param);
JCExpression marg = id(pname);
margs.append(marg);
typeargs.append(makeType(ptype));
}
// The backend's Attr skips SYNTHETIC methods when looking for a matching method.
long flags = Flags.PUBLIC | Flags.BRIDGE; // | SYNTHETIC;
JCExpression call = make.Apply(null, meth, margs.toList());
List<JCStatement> stats;
if (mtype.restype == syms.voidType) {
stats = List.of(makeExec(call), makeReturn(makeNull()));
} else {
if (mtype.restype.isPrimitive()) {
call = makeBox(diagPos, call, mtype.restype);
}
stats = List.<JCStatement>of(makeReturn(call));
}
JCMethodDecl bridgeDef = m().MethodDef(
m().Modifiers(flags),
defs.invokeName,
makeType(rtype),
List.<JCTypeParameter>nil(),
params.toList(),
m().Types(mtype.getThrownTypes()),
m().Block(0, stats),
null);
members.append(bridgeDef);
JCClassDecl cl = m().AnonymousClassDef(m().Modifiers(0), members.toList());
List<JCExpression> nilArgs = List.nil();
return m().NewClass(encl, nilArgs, make.TypeApply(t, typeargs.toList()), nilArgs, cl);
}
}
abstract class NewInstanceTranslator extends ExpressionTranslator {
// Statements to set symbols with initial values.
protected ListBuffer<JCStatement> varInits = ListBuffer.lb();
// Symbols corresponding to caseStats.
protected ListBuffer<VarSymbol> varSyms = ListBuffer.lb();
NewInstanceTranslator(DiagnosticPosition diagPos) {
super(diagPos);
}
/**
* Initialize the instance variables of the instance
* @param instName
*/
protected abstract void initInstanceVariables(Name instName);
/**
* @return the constructor args -- translating any supplied args
*/
protected abstract List<JCExpression> completeTranslatedConstructorArgs();
protected JCExpression translateInstanceVariableInit(JFXExpression init, JavafxBindStatus bindStatus, VarSymbol vsym) {
JCExpression trans = translateToExpression(init, vsym.type);
return convertNullability(init.pos(), trans, init, vsym.type);
}
void setInstanceVariable(DiagnosticPosition diagPos, Name instanceName, JavafxBindStatus bindStatus, VarSymbol vsym, JCExpression transInit) {
JCExpression tc = instanceName == null ? null : id(instanceName);
varInits.append(callStmt(tc, attributeBeName(vsym), transInit));
varSyms.append(vsym);
}
void setInstanceVariable(Name instName, JavafxBindStatus bindStatus, VarSymbol vsym, JFXExpression init) {
DiagnosticPosition initPos = init.pos();
JCExpression transInit = translateInstanceVariableInit(init, bindStatus, vsym);
setInstanceVariable(initPos, instName, bindStatus, vsym, transInit);
}
void makeInitSupportCall(Name methName, Name receiverName) {
addPreface(callStmt(id(receiverName), methName));
}
void makeInitApplyDefaults(Type classType, Name receiverName) {
ClassSymbol classSym = (ClassSymbol)classType.tsym;
int count = varSyms.size();
JCVariableDecl loopVar = makeTmpLoopVar(diagPos, 0);
Name loopName = loopVar.name;
JCExpression loopLimit = call(id(receiverName), defs.attributeCountMethodName);
JCVariableDecl loopLimitVar = makeTmpVar("count", syms.intType, loopLimit);
addPreface(loopLimitVar);
JCExpression loopTest = makeBinary(JCTree.LT, id(loopName), id(loopLimitVar.name));
List<JCExpressionStatement> loopStep = List.of(m().Exec(m().Assignop(JCTree.PLUS_ASG, id(loopName), makeInt(1))));
JCStatement loopBody;
List<JCExpression> args = List.<JCExpression>of(id(loopName));
JCStatement applyDefaultsExpr = callStmt(id(receiverName), defs.attributeApplyDefaultsPrefixMethodName, args);
if (1 < count) {
// final short[] jfx$0map = GETMAP$X();
JCExpression getmapExpr = call(varGetMapName(classSym));
JCVariableDecl mapVar = makeTmpVar("map", syms.javafx_ShortArray, getmapExpr);
addPreface(mapVar);
LiteralInitVarMap varMap = getLiteralInitClassMap().getVarMap(classSym);
int[] tags = new int[count];
int index = 0;
for (VarSymbol varSym : varSyms) {
tags[index++] = varMap.addVar(varSym);
}
ListBuffer<JCCase> cases = ListBuffer.lb();
index = 0;
for (JCStatement varInit : varInits) {
cases.append(m().Case(makeInt(tags[index++]), List.<JCStatement>of(varInit, m().Break(null))));
}
cases.append(m().Case(null, List.<JCStatement>of(applyDefaultsExpr, m().Break(null))));
JCExpression mapExpr = m().Indexed(id(mapVar), id(loopName));
loopBody = m().Switch(mapExpr, cases.toList());
} else {
VarSymbol varSym = varSyms.first();
JCExpression varOffsetExpr = select(makeType(classType, false), attributeOffsetName(varSym)); //FIXME: script-level access
JCVariableDecl offsetVar = makeTmpVar("off", syms.intType, varOffsetExpr);
addPreface(offsetVar);
JCExpression condition = makeEqual(id(loopName), id(offsetVar));
loopBody = m().If(condition, varInits.first(), applyDefaultsExpr);
}
addPreface(m().ForLoop(List.<JCStatement>of(loopVar), loopTest, loopStep, loopBody));
}
/**
* Return the instance building expression
* @param declaredType
* @param cdef
* @param isFX
* @return
*/
protected ExpressionResult buildInstance(Type declaredType, JFXClassDeclaration cdef, boolean isFX) {
Type type;
if (cdef == null) {
type = declaredType;
} else {
translateStmt(cdef, syms.voidType);
type = cdef.type;
}
JCExpression classTypeExpr = makeType(type, false);
List<JCExpression> newClassArgs = completeTranslatedConstructorArgs();
Name tmpVarName = getSyntheticName("objlit");
initInstanceVariables(tmpVarName); // Must preceed varSyms.nonEmpty() test
JCExpression instExpression;
if (varSyms.nonEmpty() || (isFX && newClassArgs.nonEmpty()) || cdef != null) {
// it is a instanciation of a JavaFX class which has instance variable initializers
// (or is anonymous, or has an outer class argument)
//
// {
// final X jfx$0objlit = new X(true);
// final short[] jfx$0map = GETMAP$X();
//
// for (int jfx$0initloop = 0; i < X.$VAR_COUNT; i++) {
// if (!isInitialized(jfx$0initloop) {
// switch (jfx$0map[jfx$0initloop]) {
// 1: jfx$0objlit.set$a(0); break;
// 2: jfx$0objlit.set$b(0); break;
// ...
// n: jfx$0objlit.set$z(0); break;
// default: jfx$0objlit.applyDefaults$(jfx$0initloop);
// }
// }
// }
//
// jfx$0objlit.complete$();
// jfx$0objlit
// }
// Use the JavaFX constructor by adding a marker argument. The "true" in:
// ... new X(true);
newClassArgs = newClassArgs.append(makeBoolean(true));
// Create the new instance, placing it in a temporary variable "jfx$0objlit"
// final X jfx$0objlit = new X(true);
addPreface(makeVar(
type,
tmpVarName,
m().NewClass(null, null, classTypeExpr, newClassArgs, null)));
// Apply defaults to the instance variables
//
// final short[] jfx$0map = GETMAP$X();
// for (int jfx$0initloop = 0; i < X.$VAR_COUNT; i++) {
// ...
// }
if (varSyms.nonEmpty()) {
makeInitApplyDefaults(type, tmpVarName);
} else {
makeInitSupportCall(defs.attributeApplyDefaultsPrefixMethodName, tmpVarName);
}
// Call complete$ to do user's init and postinit blocks
// jfx$0objlit.complete$();
makeInitSupportCall(defs.completeName, tmpVarName);
// Return the instance from the block expressions
// jfx$0objlit
instExpression = id(tmpVarName);
} else {
// this is a Java class or has no instance variable initializers, just instanciate it
instExpression = m().NewClass(null, null, classTypeExpr, newClassArgs, null);
}
return toResult(instExpression, type);
}
}
/**
* Translator for object literals
*/
abstract class InstanciateTranslator extends NewInstanceTranslator {
protected final JFXInstanciate tree;
private final Symbol idSym;
InstanciateTranslator(final JFXInstanciate tree) {
super(tree.pos());
this.tree = tree;
this.idSym = JavafxTreeInfo.symbol(tree.getIdentifier());
}
abstract protected void processLocalVar(JFXVar var);
protected void initInstanceVariables(Name instName) {
if (tree.varDefinedByThis != null) {
getSubstitutionMap().put(tree.varDefinedByThis, instName);
}
for (JFXObjectLiteralPart olpart : tree.getParts()) {
diagPos = olpart.pos(); // overwrite diagPos (must restore)
JavafxBindStatus bindStatus = olpart.getBindStatus();
JFXExpression init = olpart.getExpression();
VarSymbol vsym = (VarSymbol) olpart.sym;
setInstanceVariable(instName, bindStatus, vsym, init);
}
if (tree.varDefinedByThis != null) {
getSubstitutionMap().remove(tree.varDefinedByThis);
}
diagPos = tree.pos();
}
protected List<JCExpression> translatedConstructorArgs() {
List<JFXExpression> args = tree.getArgs();
Symbol sym = tree.constructor;
if (sym != null && sym.type != null) {
ListBuffer<JCExpression> translated = ListBuffer.lb();
List<Type> formals = sym.type.asMethodType().getParameterTypes();
boolean usesVarArgs = (sym.flags() & Flags.VARARGS) != 0L &&
(formals.size() != args.size() ||
types.isConvertible(args.last().type, types.elemtype(formals.last())));
boolean handlingVarargs = false;
Type formal = null;
List<Type> t = formals;
for (List<JFXExpression> l = args; l.nonEmpty(); l = l.tail) {
if (!handlingVarargs) {
formal = t.head;
t = t.tail;
if (usesVarArgs && t.isEmpty()) {
formal = types.elemtype(formal);
handlingVarargs = true;
}
}
JCExpression targ = translateExpr(l.head, formal);
if (targ != null) {
translated.append(targ);
}
}
return translated.toList();
} else {
return translateExprs(args);
}
}
@Override
protected List<JCExpression> completeTranslatedConstructorArgs() {
List<JCExpression> translated = translatedConstructorArgs();
if (tree.getClassBody() != null &&
tree.getClassBody().sym != null && getHasOuters().contains(tree.getClassBody().sym) ||
idSym != null && getHasOuters().contains(idSym)) {
JCIdent thisIdent = id(defs.receiverName);
translated = translated.prepend(thisIdent);
}
return translated;
}
protected ExpressionResult doit() {
for (JFXVar var : tree.getLocalvars()) {
// add the variable before the class definition or object litersl assignment
processLocalVar(var);
}
return buildInstance(tree.type, tree.getClassBody(), types.isJFXClass(idSym));
}
}
/********** goofy visitors, alpha order -- many of which should go away **********/
public void visitCatch(JFXCatch tree) {
assert false : "should be processed by parent tree";
}
public void visitErroneous(JFXErroneous tree) {
assert false : "erroneous nodes shouldn't have gotten this far";
}
public void visitForExpressionInClause(JFXForExpressionInClause that) {
assert false : "should be processed by parent tree";
}
public void visitInitDefinition(JFXInitDefinition tree) {
assert false : "should be processed by class tree";
}
public void visitImport(JFXImport tree) {
assert false : "should be processed by parent tree";
}
public void visitModifiers(JFXModifiers tree) {
assert false : "should be processed by parent tree";
}
public void visitObjectLiteralPart(JFXObjectLiteralPart that) {
assert false : "should be processed by parent tree";
}
public void visitOnReplace(JFXOnReplace tree) {
assert false : "should be processed by parent tree";
}
public void visitOverrideClassVar(JFXOverrideClassVar tree) {
assert false : "should be processed by parent tree";
}
public void visitPostInitDefinition(JFXPostInitDefinition tree) {
assert false : "should be processed by class tree";
}
public void visitTree(JFXTree that) {
assert false : "Should not be here!!!";
}
public void visitTypeAny(JFXTypeAny that) {
assert false : "should be processed by parent tree";
}
public void visitTypeClass(JFXTypeClass that) {
assert false : "should be processed by parent tree";
}
public void visitTypeFunctional(JFXTypeFunctional that) {
assert false : "should be processed by parent tree";
}
public void visitTypeArray(JFXTypeArray tree) {
assert false : "should be processed by parent tree";
}
public void visitTypeUnknown(JFXTypeUnknown that) {
assert false : "should be processed by parent tree";
}
}
| true | true | JCExpression doitExpr() {
assert sourceType != null;
assert targettedType != null;
if (targettedType.tag == TypeTags.UNKNOWN) {
//TODO: this is bad attribution
return translated;
}
if (types.isSameType(targettedType, sourceType)) {
return translated;
}
if (targetIsArray) {
Type elemType = types.elemtype(targettedType);
if (sourceIsSequence) {
if (elemType.isPrimitive()) {
String mname;
if (elemType == syms.byteType) {
mname = "toByteArray";
} else if (elemType == syms.shortType) {
mname = "toShortArray";
} else if (elemType == syms.intType) {
mname = "toIntArray";
} else if (elemType == syms.longType) {
mname = "toLongArray";
} else if (elemType == syms.floatType) {
mname = "toFloatArray";
} else if (elemType == syms.doubleType) {
mname = "toDoubleArray";
} else if (elemType == syms.booleanType) {
mname = "toBooleanArray";
} else {
mname = "toArray";
}
return call(makeType(syms.javafx_SequencesType, false),
mname, translated);
}
ListBuffer<JCStatement> stats = ListBuffer.lb();
JCVariableDecl tmpVar = makeTmpVar(sourceType, translated);
stats.append(tmpVar);
JCVariableDecl sizeVar = makeTmpVar(syms.intType, call(id(tmpVar.name), "size"));
stats.append(sizeVar);
JCVariableDecl arrVar = makeTmpVar("arr", targettedType, make.at(diagPos).NewArray(
makeType(elemType, true),
List.<JCExpression>of(id(sizeVar.name)),
null));
stats.append(arrVar);
stats.append(callStmt(id(tmpVar.name), "toArray", List.of(
makeInt(0),
id(sizeVar),
id(arrVar),
makeInt(0))));
return makeBlockExpression(stats, id(arrVar));
} else {
//TODO: conversion may be needed here, but this is better than what we had
return translated;
}
} else if (sourceIsArray && targetIsSequence) {
Type sourceElemType = types.elemtype(sourceType);
List<JCExpression> args;
if (sourceElemType.isPrimitive()) {
args = List.of(translated);
} else {
args = List.of(makeTypeInfo(diagPos, sourceElemType), translated);
}
JCExpression cSequences = makeType(syms.javafx_SequencesType, false);
return call(cSequences, "fromArray", args);
}
if (targetIsSequence && !sourceIsSequence) {
//if (sourceType.tag == TypeTags.BOT) {
// // it is a null, convert to empty sequence
// //TODO: should we leave this null?
// Type elemType = types.elemtype(type);
// return makeEmptySequenceCreator(diagPos, elemType);
//}
Type targetElemType = types.elementType(targettedType);
JCExpression cSequences = makeType(syms.javafx_SequencesType, false);
JCExpression expr = convertTranslated(translated, diagPos, sourceType, targetElemType);
// This would be redundant, if convertTranslated did a cast if needed.
expr = makeTypeCast(diagPos, targetElemType, sourceType, expr);
return call(
cSequences,
"singleton",
makeTypeInfo(diagPos, targetElemType), expr);
}
if (targetIsSequence && sourceIsSequence) {
Type sourceElementType = types.elementType(sourceType);
Type targetElementType = types.elementType(targettedType);
if (!types.isSameType(sourceElementType, targetElementType) &&
types.isNumeric(sourceElementType) && types.isNumeric(targetElementType)) {
return convertNumericSequence(diagPos,
translated,
sourceElementType,
targetElementType);
}
}
// Convert primitive/Object types
Type unboxedTargetType = targettedType.isPrimitive() ? targettedType : types.unboxedType(targettedType);
Type unboxedSourceType = sourceType.isPrimitive() ? sourceType : types.unboxedType(sourceType);
JCExpression res = translated;
Type curType = sourceType;
if (unboxedTargetType != Type.noType && unboxedSourceType != Type.noType) {
// (boxed or unboxed) primitive to (boxed or unboxed) primitive
if (!curType.isPrimitive()) {
// unboxed source if sourceboxed
res = make.at(diagPos).TypeCast(unboxedSourceType, res);
curType = unboxedSourceType;
}
if (unboxedSourceType != unboxedTargetType) {
// convert as primitive types
res = make.at(diagPos).TypeCast(unboxedTargetType, res);
curType = unboxedTargetType;
}
if (!targettedType.isPrimitive()) {
// box target if target boxed
res = make.at(diagPos).TypeCast(makeType(targettedType, false), res);
curType = targettedType;
}
} else {
if (curType.isCompound() || curType.isPrimitive()) {
res = make.at(diagPos).TypeCast(makeType(types.erasure(targettedType), true), res);
}
}
// We should add a cast "when needed". Then visitTypeCast would just
// call this function, and not need to call makeTypeCast on the result.
// However, getting that to work is a pain - giving up for now. FIXME
return res;
}
| JCExpression doitExpr() {
assert sourceType != null;
assert targettedType != null;
if (targettedType.tag == TypeTags.UNKNOWN) {
//TODO: this is bad attribution
return translated;
}
if (types.isSameType(targettedType, sourceType)) {
return translated;
}
if (targetIsArray) {
Type elemType = types.elemtype(targettedType);
if (sourceIsSequence) {
if (elemType.isPrimitive()) {
String mname;
if (elemType == syms.byteType) {
mname = "toByteArray";
} else if (elemType == syms.shortType) {
mname = "toShortArray";
} else if (elemType == syms.intType) {
mname = "toIntArray";
} else if (elemType == syms.longType) {
mname = "toLongArray";
} else if (elemType == syms.floatType) {
mname = "toFloatArray";
} else if (elemType == syms.doubleType) {
mname = "toDoubleArray";
} else if (elemType == syms.booleanType) {
mname = "toBooleanArray";
} else {
mname = "toArray";
}
return call(makeType(syms.javafx_SequencesType, false),
mname, translated);
}
ListBuffer<JCStatement> stats = ListBuffer.lb();
JCVariableDecl tmpVar = makeTmpVar(sourceType, translated);
stats.append(tmpVar);
JCVariableDecl sizeVar = makeTmpVar(syms.intType, call(id(tmpVar.name), "size"));
stats.append(sizeVar);
JCVariableDecl arrVar = makeTmpVar("arr", targettedType, make.at(diagPos).NewArray(
makeType(elemType, true),
List.<JCExpression>of(id(sizeVar.name)),
null));
stats.append(arrVar);
stats.append(callStmt(id(tmpVar.name), "toArray", List.of(
makeInt(0),
id(sizeVar),
id(arrVar),
makeInt(0))));
return makeBlockExpression(stats, id(arrVar));
} else {
//TODO: conversion may be needed here, but this is better than what we had
return translated;
}
} else if (sourceIsArray && targetIsSequence) {
Type sourceElemType = types.elemtype(sourceType);
List<JCExpression> args;
if (sourceElemType.isPrimitive()) {
args = List.of(translated);
} else {
args = List.of(makeTypeInfo(diagPos, sourceElemType), translated);
}
JCExpression cSequences = makeType(syms.javafx_SequencesType, false);
return call(cSequences, "fromArray", args);
}
if (targetIsSequence && !sourceIsSequence) {
//if (sourceType.tag == TypeTags.BOT) {
// // it is a null, convert to empty sequence
// //TODO: should we leave this null?
// Type elemType = types.elemtype(type);
// return makeEmptySequenceCreator(diagPos, elemType);
//}
Type targetElemType = types.elementType(targettedType);
JCExpression cSequences = makeType(syms.javafx_SequencesType, false);
JCExpression expr = convertTranslated(translated, diagPos, sourceType, targetElemType);
// This would be redundant, if convertTranslated did a cast if needed.
expr = makeTypeCast(diagPos, targetElemType, sourceType, expr);
return call(
cSequences,
"singleton",
makeTypeInfo(diagPos, targetElemType), expr);
}
if (targetIsSequence && sourceIsSequence) {
Type sourceElementType = types.elementType(sourceType);
Type targetElementType = types.elementType(targettedType);
if (!types.isSameType(sourceElementType, targetElementType) &&
types.isNumeric(sourceElementType) && types.isNumeric(targetElementType)) {
return convertNumericSequence(diagPos,
translated,
sourceElementType,
targetElementType);
}
}
// Convert primitive/Object types
Type unboxedTargetType = targettedType.isPrimitive() ? targettedType : types.unboxedType(targettedType);
Type unboxedSourceType = sourceType.isPrimitive() ? sourceType : types.unboxedType(sourceType);
JCExpression res = translated;
Type curType = sourceType;
if (unboxedTargetType != Type.noType && unboxedSourceType != Type.noType) {
// (boxed or unboxed) primitive to (boxed or unboxed) primitive
if (!curType.isPrimitive()) {
// unboxed source if sourceboxed
res = make.at(diagPos).TypeCast(unboxedSourceType, res);
curType = unboxedSourceType;
}
if (unboxedSourceType != unboxedTargetType) {
// convert as primitive types
res = make.at(diagPos).TypeCast(unboxedTargetType, make.at(diagPos).TypeCast(unboxedSourceType, res));
curType = unboxedTargetType;
}
if (!targettedType.isPrimitive()) {
// box target if target boxed
res = make.at(diagPos).TypeCast(makeType(targettedType, false), res);
curType = targettedType;
}
} else {
if (curType.isCompound() || curType.isPrimitive()) {
res = make.at(diagPos).TypeCast(makeType(types.erasure(targettedType), true), res);
}
}
// We should add a cast "when needed". Then visitTypeCast would just
// call this function, and not need to call makeTypeCast on the result.
// However, getting that to work is a pain - giving up for now. FIXME
return res;
}
|
diff --git a/components/bio-formats/src/loci/formats/in/IvisionReader.java b/components/bio-formats/src/loci/formats/in/IvisionReader.java
index d1315b4d2..e68f131cc 100644
--- a/components/bio-formats/src/loci/formats/in/IvisionReader.java
+++ b/components/bio-formats/src/loci/formats/in/IvisionReader.java
@@ -1,343 +1,348 @@
//
// IvisionReader.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 loci.common.DateTools;
import loci.common.RandomAccessInputStream;
import loci.common.xml.XMLTools;
import loci.formats.FormatException;
import loci.formats.FormatReader;
import loci.formats.FormatTools;
import loci.formats.MetadataTools;
import loci.formats.meta.MetadataStore;
import ome.xml.model.primitives.PositiveInteger;
import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;
/**
* IvisionReader is the file format reader for IVision (.IPM) files.
*
* <dl><dt><b>Source code:</b></dt>
* <dd><a href="http://trac.openmicroscopy.org.uk/ome/browser/bioformats.git/components/bio-formats/src/loci/formats/in/IvisionReader.java">Trac</a>,
* <a href="http://git.openmicroscopy.org/?p=bioformats.git;a=blob;f=components/bio-formats/src/loci/formats/in/IvisionReader.java;hb=HEAD">Gitweb</a></dd></dl>
*
* @author Melissa Linkert melissa at glencoesoftware.com
*/
public class IvisionReader extends FormatReader {
// -- Constants --
public static final String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";
// -- Fields --
private boolean color16;
private boolean squareRoot;
private byte[] lut;
private long imageOffset;
private String binX, binY;
private String creationDate;
private String exposureTime;
private String gain, offset;
private String deltaT;
private Integer magnification;
private Double lensNA, refractiveIndex;
private String wavelength;
// -- Constructor --
/** Constructs a new Ivision reader. */
public IvisionReader() {
super("IVision", "ipm");
suffixSufficient = false;
suffixNecessary = false;
domains = new String[] {FormatTools.UNKNOWN_DOMAIN};
}
// -- IFormatReader API methods --
/* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */
public boolean isThisType(RandomAccessInputStream stream) throws IOException {
final int blockCheckLen = 3;
if (!FormatTools.validStream(stream, blockCheckLen, true)) return false;
String version = stream.readString(3);
try {
Double.parseDouble(version);
return version.indexOf(".") != -1 && version.indexOf("-") == -1;
}
catch (NumberFormatException e) { }
return false;
}
/**
* @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 planeSize = getSizeX() * getSizeY() * getSizeC();
if (color16) planeSize = 2 * (planeSize / 3);
else if (squareRoot) planeSize *= 2;
else planeSize *= FormatTools.getBytesPerPixel(getPixelType());
in.seek(imageOffset + planeSize * no);
if (color16) {
// TODO
throw new FormatException("16-bit color iVision files are not supported");
}
else if (squareRoot) {
// TODO
throw new FormatException("Square-root iVision files are not supported");
}
else readPlane(in, x, y, w, h, buf);
return buf;
}
/* @see loci.formats.IFormatReader#close(boolean) */
public void close(boolean fileOnly) throws IOException {
super.close(fileOnly);
if (!fileOnly) {
color16 = false;
squareRoot = false;
lut = null;
imageOffset = 0;
binX = binY = null;
creationDate = null;
exposureTime = null;
gain = offset = null;
deltaT = null;
magnification = null;
lensNA = refractiveIndex = null;
wavelength = null;
}
}
// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
protected void initFile(String id) throws FormatException, IOException {
super.initFile(id);
in = new RandomAccessInputStream(id);
LOGGER.info("Populating metadata");
String version = in.readString(4);
addGlobalMeta("Version", version);
int fileFormat = in.read();
int dataType = in.read();
core[0].sizeC = 1;
switch (dataType) {
case 0:
core[0].pixelType = FormatTools.UINT8;
break;
case 1:
core[0].pixelType = FormatTools.INT16;
break;
case 2:
core[0].pixelType = FormatTools.INT32;
break;
case 3:
core[0].pixelType = FormatTools.FLOAT;
break;
case 4:
core[0].pixelType = FormatTools.UINT8;
core[0].sizeC = 3;
color16 = true;
break;
case 5:
core[0].pixelType = FormatTools.UINT8;
core[0].sizeC = 4;
break;
case 6:
core[0].pixelType = FormatTools.UINT16;
break;
case 7:
core[0].pixelType = FormatTools.FLOAT;
squareRoot = true;
break;
case 8:
core[0].pixelType = FormatTools.UINT16;
core[0].sizeC = 3;
break;
}
core[0].sizeX = in.readInt();
core[0].sizeY = in.readInt();
in.skipBytes(6);
core[0].sizeZ = in.readShort();
in.skipBytes(50);
core[0].sizeT = 1;
if (getSizeX() > 1 && getSizeY() > 1) {
lut = new byte[2048];
in.read(lut);
}
imageOffset = in.getFilePointer();
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
in.skipBytes(getSizeZ() * getSizeC() * getSizeT() * getSizeX() *
getSizeY() * FormatTools.getBytesPerPixel(getPixelType()));
// look for block of XML data
LOGGER.info("Looking for XML metadata");
in.findString(false, "<?xml");
if (in.getFilePointer() < in.length()) {
in.seek(in.getFilePointer() - 5);
String xml = in.readString((int) (in.length() - in.getFilePointer()));
- xml = xml.substring(xml.indexOf("<"), xml.lastIndexOf(">") + 1);
+ xml = xml.substring(xml.indexOf("<"), xml.lastIndexOf("plist>") + 6);
IvisionHandler handler = new IvisionHandler();
- XMLTools.parseXML(xml, handler);
+ try {
+ XMLTools.parseXML(xml, handler);
+ }
+ catch (IOException e) {
+ LOGGER.debug("", e);
+ }
}
else LOGGER.debug("XML metadata not found");
}
LOGGER.info("Populating core metadata");
core[0].rgb = getSizeC() > 1;
core[0].dimensionOrder = "XYCZT";
core[0].littleEndian = false;
core[0].interleaved = true;
core[0].indexed = false;
core[0].imageCount = getSizeZ() * getSizeT();
LOGGER.info("Populating MetadataStore");
MetadataStore store = makeFilterMetadata();
MetadataTools.populatePixels(store, this, true);
if (creationDate != null) {
String date = DateTools.formatDate(creationDate, DATE_FORMAT);
store.setImageAcquiredDate(date, 0);
}
else MetadataTools.setDefaultCreationDate(store, currentId, 0);
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
String instrumentID = MetadataTools.createLSID("Instrument", 0);
store.setInstrumentID(instrumentID, 0);
store.setImageInstrumentRef(instrumentID, 0);
if (deltaT != null) {
store.setPixelsTimeIncrement(new Double(deltaT), 0);
}
String objectiveID = MetadataTools.createLSID("Objective", 0, 0);
store.setObjectiveID(objectiveID, 0, 0);
store.setImageObjectiveSettingsID(objectiveID, 0);
store.setObjectiveCorrection(getCorrection("Other"), 0, 0);
store.setObjectiveImmersion(getImmersion("Other"), 0, 0);
if (lensNA != null) store.setObjectiveLensNA(lensNA, 0, 0);
if (magnification != null) {
store.setObjectiveNominalMagnification(
new PositiveInteger(magnification), 0, 0);
}
if (refractiveIndex != null) {
store.setImageObjectiveSettingsRefractiveIndex(refractiveIndex, 0);
}
String detectorID = MetadataTools.createLSID("Detector", 0, 0);
store.setDetectorID(detectorID, 0, 0);
store.setDetectorSettingsID(detectorID, 0, 0);
store.setDetectorType(getDetectorType("Other"), 0, 0);
store.setDetectorSettingsBinning(getBinning(binX + "x" + binY), 0, 0);
if (gain != null) {
store.setDetectorSettingsGain(new Double(gain), 0, 0);
}
}
}
// -- Helper class --
class IvisionHandler extends DefaultHandler {
// -- Fields --
private String key, value;
private String currentElement;
// -- DefaultHandler API methods --
public void endElement(String uri, String localName, String qName) {
addGlobalMeta(key, value);
if ("iplab:Bin_X".equals(key)) binX = value;
else if ("iplab:Bin_Y".equals(key)) binY = value;
else if ("iplab:Capture_Date".equals(key)) creationDate = value;
else if ("iplab:Exposure".equals(key)) exposureTime = value;
else if ("iplab:Gain".equals(key)) gain = value;
else if ("iplab:Offset".equals(key)) offset = value;
else if ("iplab:Interval_T".equals(key)) deltaT = value;
else if ("iplab:Objective_Mag".equals(key)) {
try {
magnification = new Integer((int) Double.parseDouble(value));
}
catch (NumberFormatException e) { }
}
else if ("iplab:Objective_NA".equals(key)) {
try {
lensNA = new Double(value);
}
catch (NumberFormatException e) { }
}
else if ("iplab:Objective_RI".equals(key)) {
try {
refractiveIndex = new Double(value);
}
catch (NumberFormatException e) { }
}
else if ("iplab:Wavelength".equals(key)) wavelength = value;
}
public void characters(char[] ch, int start, int length) {
String v = new String(ch, start, length);
if ("key".equals(currentElement)) {
key = v;
}
else value = v;
}
public void startElement(String uri, String localName, String qName,
Attributes attributes)
{
currentElement = qName;
}
}
}
| false | true | protected void initFile(String id) throws FormatException, IOException {
super.initFile(id);
in = new RandomAccessInputStream(id);
LOGGER.info("Populating metadata");
String version = in.readString(4);
addGlobalMeta("Version", version);
int fileFormat = in.read();
int dataType = in.read();
core[0].sizeC = 1;
switch (dataType) {
case 0:
core[0].pixelType = FormatTools.UINT8;
break;
case 1:
core[0].pixelType = FormatTools.INT16;
break;
case 2:
core[0].pixelType = FormatTools.INT32;
break;
case 3:
core[0].pixelType = FormatTools.FLOAT;
break;
case 4:
core[0].pixelType = FormatTools.UINT8;
core[0].sizeC = 3;
color16 = true;
break;
case 5:
core[0].pixelType = FormatTools.UINT8;
core[0].sizeC = 4;
break;
case 6:
core[0].pixelType = FormatTools.UINT16;
break;
case 7:
core[0].pixelType = FormatTools.FLOAT;
squareRoot = true;
break;
case 8:
core[0].pixelType = FormatTools.UINT16;
core[0].sizeC = 3;
break;
}
core[0].sizeX = in.readInt();
core[0].sizeY = in.readInt();
in.skipBytes(6);
core[0].sizeZ = in.readShort();
in.skipBytes(50);
core[0].sizeT = 1;
if (getSizeX() > 1 && getSizeY() > 1) {
lut = new byte[2048];
in.read(lut);
}
imageOffset = in.getFilePointer();
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
in.skipBytes(getSizeZ() * getSizeC() * getSizeT() * getSizeX() *
getSizeY() * FormatTools.getBytesPerPixel(getPixelType()));
// look for block of XML data
LOGGER.info("Looking for XML metadata");
in.findString(false, "<?xml");
if (in.getFilePointer() < in.length()) {
in.seek(in.getFilePointer() - 5);
String xml = in.readString((int) (in.length() - in.getFilePointer()));
xml = xml.substring(xml.indexOf("<"), xml.lastIndexOf(">") + 1);
IvisionHandler handler = new IvisionHandler();
XMLTools.parseXML(xml, handler);
}
else LOGGER.debug("XML metadata not found");
}
LOGGER.info("Populating core metadata");
core[0].rgb = getSizeC() > 1;
core[0].dimensionOrder = "XYCZT";
core[0].littleEndian = false;
core[0].interleaved = true;
core[0].indexed = false;
core[0].imageCount = getSizeZ() * getSizeT();
LOGGER.info("Populating MetadataStore");
MetadataStore store = makeFilterMetadata();
MetadataTools.populatePixels(store, this, true);
if (creationDate != null) {
String date = DateTools.formatDate(creationDate, DATE_FORMAT);
store.setImageAcquiredDate(date, 0);
}
else MetadataTools.setDefaultCreationDate(store, currentId, 0);
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
String instrumentID = MetadataTools.createLSID("Instrument", 0);
store.setInstrumentID(instrumentID, 0);
store.setImageInstrumentRef(instrumentID, 0);
if (deltaT != null) {
store.setPixelsTimeIncrement(new Double(deltaT), 0);
}
String objectiveID = MetadataTools.createLSID("Objective", 0, 0);
store.setObjectiveID(objectiveID, 0, 0);
store.setImageObjectiveSettingsID(objectiveID, 0);
store.setObjectiveCorrection(getCorrection("Other"), 0, 0);
store.setObjectiveImmersion(getImmersion("Other"), 0, 0);
if (lensNA != null) store.setObjectiveLensNA(lensNA, 0, 0);
if (magnification != null) {
store.setObjectiveNominalMagnification(
new PositiveInteger(magnification), 0, 0);
}
if (refractiveIndex != null) {
store.setImageObjectiveSettingsRefractiveIndex(refractiveIndex, 0);
}
String detectorID = MetadataTools.createLSID("Detector", 0, 0);
store.setDetectorID(detectorID, 0, 0);
store.setDetectorSettingsID(detectorID, 0, 0);
store.setDetectorType(getDetectorType("Other"), 0, 0);
store.setDetectorSettingsBinning(getBinning(binX + "x" + binY), 0, 0);
if (gain != null) {
store.setDetectorSettingsGain(new Double(gain), 0, 0);
}
}
}
| protected void initFile(String id) throws FormatException, IOException {
super.initFile(id);
in = new RandomAccessInputStream(id);
LOGGER.info("Populating metadata");
String version = in.readString(4);
addGlobalMeta("Version", version);
int fileFormat = in.read();
int dataType = in.read();
core[0].sizeC = 1;
switch (dataType) {
case 0:
core[0].pixelType = FormatTools.UINT8;
break;
case 1:
core[0].pixelType = FormatTools.INT16;
break;
case 2:
core[0].pixelType = FormatTools.INT32;
break;
case 3:
core[0].pixelType = FormatTools.FLOAT;
break;
case 4:
core[0].pixelType = FormatTools.UINT8;
core[0].sizeC = 3;
color16 = true;
break;
case 5:
core[0].pixelType = FormatTools.UINT8;
core[0].sizeC = 4;
break;
case 6:
core[0].pixelType = FormatTools.UINT16;
break;
case 7:
core[0].pixelType = FormatTools.FLOAT;
squareRoot = true;
break;
case 8:
core[0].pixelType = FormatTools.UINT16;
core[0].sizeC = 3;
break;
}
core[0].sizeX = in.readInt();
core[0].sizeY = in.readInt();
in.skipBytes(6);
core[0].sizeZ = in.readShort();
in.skipBytes(50);
core[0].sizeT = 1;
if (getSizeX() > 1 && getSizeY() > 1) {
lut = new byte[2048];
in.read(lut);
}
imageOffset = in.getFilePointer();
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
in.skipBytes(getSizeZ() * getSizeC() * getSizeT() * getSizeX() *
getSizeY() * FormatTools.getBytesPerPixel(getPixelType()));
// look for block of XML data
LOGGER.info("Looking for XML metadata");
in.findString(false, "<?xml");
if (in.getFilePointer() < in.length()) {
in.seek(in.getFilePointer() - 5);
String xml = in.readString((int) (in.length() - in.getFilePointer()));
xml = xml.substring(xml.indexOf("<"), xml.lastIndexOf("plist>") + 6);
IvisionHandler handler = new IvisionHandler();
try {
XMLTools.parseXML(xml, handler);
}
catch (IOException e) {
LOGGER.debug("", e);
}
}
else LOGGER.debug("XML metadata not found");
}
LOGGER.info("Populating core metadata");
core[0].rgb = getSizeC() > 1;
core[0].dimensionOrder = "XYCZT";
core[0].littleEndian = false;
core[0].interleaved = true;
core[0].indexed = false;
core[0].imageCount = getSizeZ() * getSizeT();
LOGGER.info("Populating MetadataStore");
MetadataStore store = makeFilterMetadata();
MetadataTools.populatePixels(store, this, true);
if (creationDate != null) {
String date = DateTools.formatDate(creationDate, DATE_FORMAT);
store.setImageAcquiredDate(date, 0);
}
else MetadataTools.setDefaultCreationDate(store, currentId, 0);
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
String instrumentID = MetadataTools.createLSID("Instrument", 0);
store.setInstrumentID(instrumentID, 0);
store.setImageInstrumentRef(instrumentID, 0);
if (deltaT != null) {
store.setPixelsTimeIncrement(new Double(deltaT), 0);
}
String objectiveID = MetadataTools.createLSID("Objective", 0, 0);
store.setObjectiveID(objectiveID, 0, 0);
store.setImageObjectiveSettingsID(objectiveID, 0);
store.setObjectiveCorrection(getCorrection("Other"), 0, 0);
store.setObjectiveImmersion(getImmersion("Other"), 0, 0);
if (lensNA != null) store.setObjectiveLensNA(lensNA, 0, 0);
if (magnification != null) {
store.setObjectiveNominalMagnification(
new PositiveInteger(magnification), 0, 0);
}
if (refractiveIndex != null) {
store.setImageObjectiveSettingsRefractiveIndex(refractiveIndex, 0);
}
String detectorID = MetadataTools.createLSID("Detector", 0, 0);
store.setDetectorID(detectorID, 0, 0);
store.setDetectorSettingsID(detectorID, 0, 0);
store.setDetectorType(getDetectorType("Other"), 0, 0);
store.setDetectorSettingsBinning(getBinning(binX + "x" + binY), 0, 0);
if (gain != null) {
store.setDetectorSettingsGain(new Double(gain), 0, 0);
}
}
}
|
diff --git a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/launcher/AddVMDialog.java b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/launcher/AddVMDialog.java
index d3008acb3..4e1de7ae0 100644
--- a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/launcher/AddVMDialog.java
+++ b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/launcher/AddVMDialog.java
@@ -1,475 +1,477 @@
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.debug.ui.launcher;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.MessageFormat;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jdt.debug.ui.IJavaDebugUIConstants;
import org.eclipse.jdt.internal.debug.ui.IJavaDebugHelpContextIds;
import org.eclipse.jdt.internal.debug.ui.JDIDebugUIPlugin;
import org.eclipse.jdt.internal.ui.dialogs.StatusDialog;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.ComboDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IStringButtonAdapter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringDialogField;
import org.eclipse.jdt.launching.AbstractVMInstallType;
import org.eclipse.jdt.launching.IVMInstall;
import org.eclipse.jdt.launching.IVMInstallType;
import org.eclipse.jdt.launching.VMStandin;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.help.WorkbenchHelp;
public class AddVMDialog extends StatusDialog {
private IAddVMDialogRequestor fRequestor;
private IVMInstall fEditedVM;
private IVMInstallType[] fVMTypes;
private IVMInstallType fSelectedVMType;
private ComboDialogField fVMTypeCombo;
private VMLibraryBlock fLibraryBlock;
private StringButtonDialogField fJRERoot;
private StringDialogField fVMName;
private StringButtonDialogField fJavadocURL;
private boolean fAutoDetectJavadocLocation = false;
private IDialogSettings fDialogSettings;
private IStatus[] fStati;
public AddVMDialog(IAddVMDialogRequestor requestor, Shell shell, IVMInstallType[] vmInstallTypes, IVMInstall editedVM) {
super(shell);
fRequestor= requestor;
fStati= new IStatus[5];
for (int i= 0; i < fStati.length; i++) {
fStati[i]= new StatusInfo();
}
fVMTypes= vmInstallTypes;
fSelectedVMType= editedVM != null ? editedVM.getVMInstallType() : vmInstallTypes[0];
fEditedVM= editedVM;
fDialogSettings= JDIDebugUIPlugin.getDefault().getDialogSettings();
//only detect the javadoc location if not already set
fAutoDetectJavadocLocation = fEditedVM == null || fEditedVM.getJavadocLocation() == null;
}
/**
* @see Windows#configureShell
*/
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
WorkbenchHelp.setHelp(newShell, IJavaDebugHelpContextIds.EDIT_JRE_DIALOG);
}
protected void createDialogFields() {
fVMTypeCombo= new ComboDialogField(SWT.READ_ONLY);
fVMTypeCombo.setLabelText(LauncherMessages.getString("addVMDialog.jreType")); //$NON-NLS-1$
- fVMTypeCombo.setDialogFieldListener(new IDialogFieldListener() {
- public void dialogFieldChanged(DialogField field) {
- updateVMType();
- }
- });
+ if (fEditedVM == null) {
+ fVMTypeCombo.setDialogFieldListener(new IDialogFieldListener() {
+ public void dialogFieldChanged(DialogField field) {
+ updateVMType();
+ }
+ });
+ }
fVMName= new StringDialogField();
fVMName.setLabelText(LauncherMessages.getString("addVMDialog.jreName")); //$NON-NLS-1$
fVMName.setDialogFieldListener(new IDialogFieldListener() {
public void dialogFieldChanged(DialogField field) {
setVMNameStatus(validateVMName());
updateStatusLine();
}
});
fJRERoot= new StringButtonDialogField(new IStringButtonAdapter() {
public void changeControlPressed(DialogField field) {
browseForInstallDir();
}
});
fJRERoot.setLabelText(LauncherMessages.getString("addVMDialog.jreHome")); //$NON-NLS-1$
fJRERoot.setButtonLabel(LauncherMessages.getString("addVMDialog.browse1")); //$NON-NLS-1$
fJRERoot.setDialogFieldListener(new IDialogFieldListener() {
public void dialogFieldChanged(DialogField field) {
setJRELocationStatus(validateJRELocation());
updateStatusLine();
}
});
fJavadocURL = new StringButtonDialogField(new IStringButtonAdapter() {
public void changeControlPressed(DialogField field) {
browseForJavadocURL();
}
});
fJavadocURL.setLabelText(LauncherMessages.getString("AddVMDialog.Java&doc_URL__1")); //$NON-NLS-1$
fJavadocURL.setButtonLabel(LauncherMessages.getString("AddVMDialog.Bro&wse..._2")); //$NON-NLS-1$
fJavadocURL.setDialogFieldListener(new IDialogFieldListener() {
public void dialogFieldChanged(DialogField field) {
setJavadocURLStatus(validateJavadocURL());
updateStatusLine();
}
});
}
protected String getVMName() {
return fVMName.getText();
}
protected File getInstallLocation() {
return new File(fJRERoot.getText());
}
protected Control createDialogArea(Composite ancestor) {
Font font = ancestor.getFont();
initializeDialogUnits(ancestor);
createDialogFields();
Composite parent= new Composite(ancestor, SWT.NULL);
GridLayout layout= new GridLayout();
layout.numColumns= 3;
parent.setLayout(layout);
parent.setFont(font);
fVMTypeCombo.doFillIntoGrid(parent, 3);
((GridData)fVMTypeCombo.getComboControl(null).getLayoutData()).widthHint= convertWidthInCharsToPixels(50);
fVMName.doFillIntoGrid(parent, 3);
fJRERoot.doFillIntoGrid(parent, 3);
fJavadocURL.doFillIntoGrid(parent, 3);
Label l = new Label(parent, SWT.NONE);
l.setText(LauncherMessages.getString("AddVMDialog.JRE_system_libraries__1")); //$NON-NLS-1$
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan = 3;
l.setLayoutData(gd);
l.setFont(font);
fLibraryBlock = new VMLibraryBlock(this);
Control block = fLibraryBlock.createControl(parent);
gd = new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan = 3;
block.setLayoutData(gd);
Text t= fJRERoot.getTextControl(parent);
gd= (GridData)t.getLayoutData();
gd.grabExcessHorizontalSpace=true;
gd.widthHint= convertWidthInCharsToPixels(50);
t= fJavadocURL.getTextControl(parent);
gd= (GridData)t.getLayoutData();
gd.grabExcessHorizontalSpace=true;
gd.widthHint= convertWidthInCharsToPixels(50);
initializeFields();
return parent;
}
private void updateVMType() {
int selIndex= fVMTypeCombo.getSelectionIndex();
if (selIndex >= 0 && selIndex < fVMTypes.length) {
fSelectedVMType= fVMTypes[selIndex];
}
setJRELocationStatus(validateJRELocation());
fLibraryBlock.initializeFrom(fEditedVM, fSelectedVMType);
updateStatusLine();
}
public void create() {
super.create();
fVMName.setFocus();
selectVMType();
}
private String[] getVMTypeNames() {
String[] names= new String[fVMTypes.length];
for (int i= 0; i < fVMTypes.length; i++) {
names[i]= fVMTypes[i].getName();
}
return names;
}
private void selectVMType() {
for (int i= 0; i < fVMTypes.length; i++) {
if (fSelectedVMType == fVMTypes[i]) {
fVMTypeCombo.selectItem(i);
return;
}
}
}
private void initializeFields() {
fVMTypeCombo.setItems(getVMTypeNames());
if (fEditedVM == null) {
fVMName.setText(""); //$NON-NLS-1$
fJRERoot.setText(""); //$NON-NLS-1$
fJavadocURL.setText(""); //$NON-NLS-1$
fLibraryBlock.initializeFrom(null, fSelectedVMType);
} else {
fVMTypeCombo.setEnabled(false);
fVMName.setText(fEditedVM.getName());
fJRERoot.setText(fEditedVM.getInstallLocation().getAbsolutePath());
URL url = fEditedVM.getJavadocLocation();
if (url == null) {
fJavadocURL.setText(""); //$NON-NLS-1$
} else {
fJavadocURL.setText(url.toExternalForm());
}
fLibraryBlock.initializeFrom(fEditedVM, fSelectedVMType);
}
}
private IVMInstallType getVMType() {
return fSelectedVMType;
}
private IStatus validateJRELocation() {
String locationName= fJRERoot.getText();
IStatus s = null;
File file = null;
if (locationName.length() == 0) {//$NON-NLS-1$
s = new StatusInfo(IStatus.INFO, LauncherMessages.getString("addVMDialog.enterLocation")); //$NON-NLS-1$
} else {
file= new File(locationName);
if (!file.exists()) {
s = new StatusInfo(IStatus.ERROR, LauncherMessages.getString("addVMDialog.locationNotExists")); //$NON-NLS-1$
} else {
final IStatus[] temp = new IStatus[1];
final File tempFile = file;
Runnable r = new Runnable() {
/**
* @see java.lang.Runnable#run()
*/
public void run() {
temp[0] = getVMType().validateInstallLocation(tempFile);
}
};
BusyIndicator.showWhile(getShell().getDisplay(), r);
s = temp[0];
}
}
if (s.isOK()) {
fLibraryBlock.setHomeDirectory(file);
} else {
fLibraryBlock.setHomeDirectory(null);
}
fLibraryBlock.update();
detectJavadocLocation();
return s;
}
private IStatus validateJavadocURL() {
String text = fJavadocURL.getText();
if (text != null && text.length() > 0) {
try {
new URL(text);
} catch (MalformedURLException e) {
return new Status(IStatus.ERROR, JDIDebugUIPlugin.getUniqueIdentifier(), IJavaDebugUIConstants.INTERNAL_ERROR, LauncherMessages.getString("AddVMDialog.Invalid_URL_syntax_specified_for_Javadoc_location._1"), e); //$NON-NLS-1$
}
}
return new StatusInfo();
}
/**
* Auto-detects the default javadoc location
*/
private void detectJavadocLocation() {
if (fAutoDetectJavadocLocation) {
if (getVMType() instanceof AbstractVMInstallType) {
AbstractVMInstallType type = (AbstractVMInstallType)getVMType();
URL url = type.getDefaultJavadocLocation(getInstallLocation());
if (url == null) {
fJavadocURL.setText(""); //$NON-NLS-1$
} else {
fJavadocURL.setText(url.toExternalForm());
}
}
}
}
private IStatus validateVMName() {
StatusInfo status= new StatusInfo();
String name= fVMName.getText();
if (name == null || name.trim().length() == 0) {
status.setInfo(LauncherMessages.getString("addVMDialog.enterName")); //$NON-NLS-1$
} else {
if (fRequestor.isDuplicateName(name) && (fEditedVM == null || !name.equals(fEditedVM.getName()))) {
status.setError(LauncherMessages.getString("addVMDialog.duplicateName")); //$NON-NLS-1$
} else {
IStatus s = ResourcesPlugin.getWorkspace().validateName(name, IResource.FILE);
if (!s.isOK()) {
status.setError(MessageFormat.format(LauncherMessages.getString("AddVMDialog.JRE_name_must_be_a_valid_file_name__{0}_1"), new String[]{s.getMessage()})); //$NON-NLS-1$
}
}
}
return status;
}
protected void updateStatusLine() {
IStatus max= null;
for (int i= 0; i < fStati.length; i++) {
IStatus curr= fStati[i];
if (curr.matches(IStatus.ERROR)) {
updateStatus(curr);
return;
}
if (max == null || curr.getSeverity() > max.getSeverity()) {
max= curr;
}
}
updateStatus(max);
}
private void browseForInstallDir() {
DirectoryDialog dialog= new DirectoryDialog(getShell());
dialog.setFilterPath(fJRERoot.getText());
dialog.setMessage(LauncherMessages.getString("addVMDialog.pickJRERootDialog.message")); //$NON-NLS-1$
String newPath= dialog.open();
if (newPath != null) {
fJRERoot.setText(newPath);
}
}
private void browseForJavadocURL() {
DirectoryDialog dialog= new DirectoryDialog(getShell());
String initPath= ""; //$NON-NLS-1$
URL url = getURL();
if (url != null && "file".equals(url.getProtocol())) { //$NON-NLS-1$
initPath= (new File(url.getFile())).getPath();
}
dialog.setFilterPath(initPath);
dialog.setMessage(LauncherMessages.getString("AddVMDialog.Select_Javadoc_location__3")); //$NON-NLS-1$
String res = dialog.open();
if (res != null) {
try {
url = (new File(res)).toURL();
fJavadocURL.setText(url.toExternalForm());
} catch (MalformedURLException e) {
// should not happen
JDIDebugUIPlugin.log(e);
}
}
}
protected URL getURL() {
try {
return new URL(fJavadocURL.getText());
} catch (MalformedURLException e) {
return null;
}
}
protected void okPressed() {
doOkPressed();
super.okPressed();
}
private void doOkPressed() {
if (fEditedVM == null) {
IVMInstall vm= new VMStandin(fSelectedVMType, createUniqueId(fSelectedVMType));
setFieldValuesToVM(vm);
fRequestor.vmAdded(vm);
} else {
setFieldValuesToVM(fEditedVM);
}
}
private String createUniqueId(IVMInstallType vmType) {
String id= null;
do {
id= String.valueOf(System.currentTimeMillis());
} while (vmType.findVMInstall(id) != null);
return id;
}
protected void setFieldValuesToVM(IVMInstall vm) {
vm.setInstallLocation(new File(fJRERoot.getText()).getAbsoluteFile());
vm.setName(fVMName.getText());
vm.setJavadocLocation(getURL());
fLibraryBlock.performApply(vm);
}
protected File getAbsoluteFileOrEmpty(String path) {
if (path == null || path.length() == 0) {
return new File(""); //$NON-NLS-1$
}
return new File(path).getAbsoluteFile();
}
private void setVMNameStatus(IStatus status) {
fStati[0]= status;
}
private void setJRELocationStatus(IStatus status) {
fStati[1]= status;
}
private void setJavadocURLStatus(IStatus status) {
fStati[2] = status;
}
protected IStatus getSystemLibraryStatus() {
return fStati[3];
}
protected void setSystemLibraryStatus(IStatus status) {
fStati[3]= status;
}
/**
* Updates the status of the ok button to reflect the given status.
* Subclasses may override this method to update additional buttons.
* @param status the status.
*/
protected void updateButtonsEnableState(IStatus status) {
Button ok = getButton(IDialogConstants.OK_ID);
if (ok != null && !ok.isDisposed())
ok.setEnabled(status.getSeverity() == IStatus.OK);
}
/**
* @see org.eclipse.jface.dialogs.Dialog#setButtonLayoutData(org.eclipse.swt.widgets.Button)
*/
protected void setButtonLayoutData(Button button) {
super.setButtonLayoutData(button);
}
}
| true | true | protected void createDialogFields() {
fVMTypeCombo= new ComboDialogField(SWT.READ_ONLY);
fVMTypeCombo.setLabelText(LauncherMessages.getString("addVMDialog.jreType")); //$NON-NLS-1$
fVMTypeCombo.setDialogFieldListener(new IDialogFieldListener() {
public void dialogFieldChanged(DialogField field) {
updateVMType();
}
});
fVMName= new StringDialogField();
fVMName.setLabelText(LauncherMessages.getString("addVMDialog.jreName")); //$NON-NLS-1$
fVMName.setDialogFieldListener(new IDialogFieldListener() {
public void dialogFieldChanged(DialogField field) {
setVMNameStatus(validateVMName());
updateStatusLine();
}
});
fJRERoot= new StringButtonDialogField(new IStringButtonAdapter() {
public void changeControlPressed(DialogField field) {
browseForInstallDir();
}
});
fJRERoot.setLabelText(LauncherMessages.getString("addVMDialog.jreHome")); //$NON-NLS-1$
fJRERoot.setButtonLabel(LauncherMessages.getString("addVMDialog.browse1")); //$NON-NLS-1$
fJRERoot.setDialogFieldListener(new IDialogFieldListener() {
public void dialogFieldChanged(DialogField field) {
setJRELocationStatus(validateJRELocation());
updateStatusLine();
}
});
fJavadocURL = new StringButtonDialogField(new IStringButtonAdapter() {
public void changeControlPressed(DialogField field) {
browseForJavadocURL();
}
});
fJavadocURL.setLabelText(LauncherMessages.getString("AddVMDialog.Java&doc_URL__1")); //$NON-NLS-1$
fJavadocURL.setButtonLabel(LauncherMessages.getString("AddVMDialog.Bro&wse..._2")); //$NON-NLS-1$
fJavadocURL.setDialogFieldListener(new IDialogFieldListener() {
public void dialogFieldChanged(DialogField field) {
setJavadocURLStatus(validateJavadocURL());
updateStatusLine();
}
});
}
| protected void createDialogFields() {
fVMTypeCombo= new ComboDialogField(SWT.READ_ONLY);
fVMTypeCombo.setLabelText(LauncherMessages.getString("addVMDialog.jreType")); //$NON-NLS-1$
if (fEditedVM == null) {
fVMTypeCombo.setDialogFieldListener(new IDialogFieldListener() {
public void dialogFieldChanged(DialogField field) {
updateVMType();
}
});
}
fVMName= new StringDialogField();
fVMName.setLabelText(LauncherMessages.getString("addVMDialog.jreName")); //$NON-NLS-1$
fVMName.setDialogFieldListener(new IDialogFieldListener() {
public void dialogFieldChanged(DialogField field) {
setVMNameStatus(validateVMName());
updateStatusLine();
}
});
fJRERoot= new StringButtonDialogField(new IStringButtonAdapter() {
public void changeControlPressed(DialogField field) {
browseForInstallDir();
}
});
fJRERoot.setLabelText(LauncherMessages.getString("addVMDialog.jreHome")); //$NON-NLS-1$
fJRERoot.setButtonLabel(LauncherMessages.getString("addVMDialog.browse1")); //$NON-NLS-1$
fJRERoot.setDialogFieldListener(new IDialogFieldListener() {
public void dialogFieldChanged(DialogField field) {
setJRELocationStatus(validateJRELocation());
updateStatusLine();
}
});
fJavadocURL = new StringButtonDialogField(new IStringButtonAdapter() {
public void changeControlPressed(DialogField field) {
browseForJavadocURL();
}
});
fJavadocURL.setLabelText(LauncherMessages.getString("AddVMDialog.Java&doc_URL__1")); //$NON-NLS-1$
fJavadocURL.setButtonLabel(LauncherMessages.getString("AddVMDialog.Bro&wse..._2")); //$NON-NLS-1$
fJavadocURL.setDialogFieldListener(new IDialogFieldListener() {
public void dialogFieldChanged(DialogField field) {
setJavadocURLStatus(validateJavadocURL());
updateStatusLine();
}
});
}
|
diff --git a/src/jogl/classes/jogamp/opengl/awt/AWTTilePainter.java b/src/jogl/classes/jogamp/opengl/awt/AWTTilePainter.java
index 7850762ef..a06dbcb3d 100644
--- a/src/jogl/classes/jogamp/opengl/awt/AWTTilePainter.java
+++ b/src/jogl/classes/jogamp/opengl/awt/AWTTilePainter.java
@@ -1,378 +1,378 @@
/**
* Copyright 2013 JogAmp Community. 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.
*
* THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of JogAmp Community.
*/
package jogamp.opengl.awt;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Set;
import java.util.Map.Entry;
import javax.imageio.ImageIO;
import javax.media.nativewindow.util.DimensionImmutable;
import javax.media.opengl.GL;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.GLCapabilitiesImmutable;
import javax.media.opengl.GLEventListener;
import jogamp.opengl.Debug;
import com.jogamp.opengl.util.TileRenderer;
import com.jogamp.opengl.util.TileRendererBase;
import com.jogamp.opengl.util.GLPixelBuffer.GLPixelAttributes;
import com.jogamp.opengl.util.awt.AWTGLPixelBuffer;
import com.jogamp.opengl.util.awt.AWTGLPixelBuffer.AWTGLPixelBufferProvider;
/**
* Implementing AWT {@link Graphics2D} based {@link TileRenderer} <i>painter</i>.
* <p>
* Maybe utilized for AWT printing.
* </p>
*/
public class AWTTilePainter {
private static final boolean DEBUG_TILES = Debug.debug("TileRenderer.PNG");
public final TileRenderer renderer;
public final int componentCount;
public final double scaleMatX, scaleMatY;
public final boolean verbose;
public boolean flipVertical;
private AWTGLPixelBuffer tBuffer = null;
private BufferedImage vFlipImage = null;
private Graphics2D g2d = null;
private AffineTransform saveAT = null;
public static void dumpHintsAndScale(Graphics2D g2d) {
final RenderingHints rHints = g2d.getRenderingHints();
final Set<Entry<Object, Object>> rEntries = rHints.entrySet();
int count = 0;
for(Iterator<Entry<Object, Object>> rEntryIter = rEntries.iterator(); rEntryIter.hasNext(); count++) {
final Entry<Object, Object> rEntry = rEntryIter.next();
System.err.println("Hint["+count+"]: "+rEntry.getKey()+" -> "+rEntry.getValue());
}
final AffineTransform aTrans = g2d.getTransform();
System.err.println(" type "+aTrans.getType());
System.err.println(" scale "+aTrans.getScaleX()+" x "+aTrans.getScaleY());
System.err.println(" move "+aTrans.getTranslateX()+" x "+aTrans.getTranslateY());
System.err.println(" mat "+aTrans);
}
/**
* @param numSamples multisampling value: < 0 turns off, == 0 leaves as-is, > 0 enables using given num samples
* @param caps used capabilties
* @return resulting number of samples, 0 if disabled
*/
public static int getNumSamples(int numSamples, GLCapabilitiesImmutable caps) {
if( 0 > numSamples ) {
return 0;
} else if( 0 < numSamples ) {
if ( !caps.getGLProfile().isGL2ES3() ) {
return 0;
}
return Math.max(caps.getNumSamples(), numSamples);
} else {
return caps.getNumSamples();
}
}
/**
* Assumes a configured {@link TileRenderer}, i.e.
* an {@link TileRenderer#attachToAutoDrawable(GLAutoDrawable) attached}
* {@link GLAutoDrawable} with {@link TileRenderer#setTileSize(int, int, int) set tile size}.
* <p>
* Sets the renderer to {@link TileRenderer#TR_TOP_TO_BOTTOM} row order.
* </p>
* <p>
* <code>componentCount</code> reflects opaque, i.e. 4 if non opaque.
* </p>
* @param renderer
* @param componentCount
* @param scaleMatX {@link Graphics2D} {@link Graphics2D#scale(double, double) scaling factor}, i.e. rendering 1/scaleMatX * width pixels
* @param scaleMatY {@link Graphics2D} {@link Graphics2D#scale(double, double) scaling factor}, i.e. rendering 1/scaleMatY * height pixels
* @param verbose
*/
public AWTTilePainter(TileRenderer renderer, int componentCount, double scaleMatX, double scaleMatY, boolean verbose) {
this.renderer = renderer;
this.renderer.setGLEventListener(preTileGLEL, postTileGLEL);
this.componentCount = componentCount;
this.scaleMatX = scaleMatX;
this.scaleMatY = scaleMatY;
this.verbose = verbose;
this.flipVertical = true;
}
public String toString() { return renderer.toString(); }
public void setIsGLOriented(boolean v) {
flipVertical = v;
}
private static Rectangle getRoundedRect(Rectangle2D r) {
if( null == r ) { return null; }
return new Rectangle((int)Math.round(r.getX()), (int)Math.round(r.getY()),
(int)Math.round(r.getWidth()), (int)Math.round(r.getHeight()));
}
private static Rectangle clipNegative(Rectangle in) {
if( null == in ) { return null; }
final Rectangle out = new Rectangle(in);
if( 0 > out.x ) {
out.width += out.x;
out.x = 0;
}
if( 0 > out.y ) {
out.height += out.y;
out.y = 0;
}
return out;
}
/**
* Caches the {@link Graphics2D} instance for rendering.
* <p>
* Copies the current {@link Graphics2D} {@link AffineTransform}
* and scales {@link Graphics2D} w/ <code>scaleMatX</code> x <code>scaleMatY</code>.<br>
* After rendering, the {@link AffineTransform} should be reset via {@link #resetGraphics2D()}.
* </p>
* <p>
* Sets the {@link TileRenderer}'s {@link TileRenderer#setImageSize(int, int) image size}
* and {@link TileRenderer#setTileOffset(int, int) tile offset} according the
* the {@link Graphics2D#getClipBounds() graphics clip bounds}.
* </p>
* @param g2d Graphics2D instance used for transform and clipping
* @param width width of the AWT component in case clipping is null
* @param height height of the AWT component in case clipping is null
*/
public void setupGraphics2DAndClipBounds(Graphics2D g2d, int width, int height) {
this.g2d = g2d;
saveAT = g2d.getTransform();
final Rectangle gClipOrigR;
final Rectangle2D dClipOrig, dImageSizeOrig; // double precision for scaling
// setup original rectangles
{
gClipOrigR = g2d.getClipBounds();
final Rectangle gClipOrig = clipNegative(gClipOrigR);
dClipOrig = null != gClipOrig ? new Rectangle2D.Double(gClipOrig.getX(), gClipOrig.getY(), gClipOrig.getWidth(), gClipOrig.getHeight()) : null;
dImageSizeOrig = new Rectangle2D.Double(0, 0, width, height);
}
final Rectangle2D dClipScaled, dImageSizeScaled; // double precision for scaling
// retrieve scaled image-size and clip-bounds
{
g2d.setClip(dImageSizeOrig);
g2d.scale(scaleMatX, scaleMatY);
dImageSizeScaled = (Rectangle2D) g2d.getClip();
if( null == dClipOrig ) {
g2d.setClip(null);
dClipScaled = (Rectangle2D) dImageSizeScaled.clone();
} else {
g2d.setTransform(saveAT); // reset
g2d.setClip(dClipOrig);
g2d.scale(scaleMatX, scaleMatY);
dClipScaled = (Rectangle2D) g2d.getClip();
}
}
final Rectangle iClipScaled = getRoundedRect(dClipScaled);
final Rectangle iImageSizeScaled = getRoundedRect(dImageSizeScaled);
scaledYOffset = iClipScaled.y;
renderer.setImageSize(iImageSizeScaled.width, iImageSizeScaled.height);
renderer.clipImageSize(iClipScaled.width, iClipScaled.height);
final int clipH = Math.min(iImageSizeScaled.height, iClipScaled.height);
if( flipVertical ) {
renderer.setTileOffset(iClipScaled.x, iImageSizeScaled.height - ( iClipScaled.y + clipH ));
} else {
renderer.setTileOffset(iClipScaled.x, iClipScaled.y);
}
if( verbose ) {
System.err.println("AWT print.0: image "+dImageSizeOrig + " -> " + dImageSizeScaled + " -> " + iImageSizeScaled);
System.err.println("AWT print.0: clip "+gClipOrigR + " -> " + dClipOrig + " -> " + dClipScaled + " -> " + iClipScaled);
System.err.println("AWT print.0: "+renderer);
}
}
private int scaledYOffset;
/** See {@ #setupGraphics2DAndClipBounds(Graphics2D)}. */
public void resetGraphics2D() {
g2d.setTransform(saveAT);
}
/**
* Disposes resources and {@link TileRenderer#detachFromAutoDrawable() detaches}
* the {@link TileRenderer}'s {@link GLAutoDrawable}.
*/
public void dispose() {
renderer.detachFromAutoDrawable(); // tile-renderer -> printGLAD
g2d = null;
if( null != tBuffer ) {
tBuffer.dispose();
tBuffer = null;
}
if( null != vFlipImage ) {
vFlipImage.flush();
vFlipImage = null;
}
}
final GLEventListener preTileGLEL = new GLEventListener() {
@Override
public void init(GLAutoDrawable drawable) {}
@Override
public void dispose(GLAutoDrawable drawable) {}
@Override
public void display(GLAutoDrawable drawable) {
final GL gl = drawable.getGL();
if( null == tBuffer ) {
final int tWidth = renderer.getParam(TileRenderer.TR_TILE_WIDTH);
final int tHeight = renderer.getParam(TileRenderer.TR_TILE_HEIGHT);
final AWTGLPixelBufferProvider printBufferProvider = new AWTGLPixelBufferProvider( true /* allowRowStride */ );
final GLPixelAttributes pixelAttribs = printBufferProvider.getAttributes(gl, componentCount);
tBuffer = printBufferProvider.allocate(gl, pixelAttribs, tWidth, tHeight, 1, true, 0);
renderer.setTileBuffer(tBuffer);
if( flipVertical ) {
vFlipImage = new BufferedImage(tBuffer.width, tBuffer.height, tBuffer.image.getType());
} else {
vFlipImage = null;
}
}
if( verbose ) {
System.err.println("XXX tile-pre "+renderer);
}
}
@Override
public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) {}
};
static int _counter = 0;
final GLEventListener postTileGLEL = new GLEventListener() {
@Override
public void init(GLAutoDrawable drawable) {
}
@Override
public void dispose(GLAutoDrawable drawable) {}
@Override
public void display(GLAutoDrawable drawable) {
final DimensionImmutable cis = renderer.getClippedImageSize();
final int tWidth = renderer.getParam(TileRendererBase.TR_CURRENT_TILE_WIDTH);
final int tHeight = renderer.getParam(TileRendererBase.TR_CURRENT_TILE_HEIGHT);
final int pX = renderer.getParam(TileRendererBase.TR_CURRENT_TILE_X_POS);
final int pY = renderer.getParam(TileRendererBase.TR_CURRENT_TILE_Y_POS);
final int pYOff = renderer.getParam(TileRenderer.TR_TILE_Y_OFFSET);
final int pYf;
if( flipVertical ) {
pYf = cis.getHeight() - ( pY - pYOff + tHeight ) + scaledYOffset;
} else {
pYf = pY;
}
// Copy temporary data into raster of BufferedImage for faster
// blitting Note that we could avoid this copy in the cases
// where !offscreenDrawable.isGLOriented(),
// but that's the software rendering path which is very slow anyway.
final BufferedImage dstImage;
if( DEBUG_TILES ) {
final String fname = String.format("file_%03d_0_tile_[%02d][%02d]_sz_%03dx%03d_pos0_%03d_%03d_yOff_%03d_pos1_%03d_%03d.png",
_counter,
renderer.getParam(TileRenderer.TR_CURRENT_COLUMN), renderer.getParam(TileRenderer.TR_CURRENT_ROW),
tWidth, tHeight,
pX, pY, pYOff, pX, pYf).replace(' ', '_');
System.err.println("XXX file "+fname);
final File fout = new File(fname);
try {
ImageIO.write(tBuffer.image, "png", fout);
} catch (IOException e) {
e.printStackTrace();
}
}
if( flipVertical ) {
final BufferedImage srcImage = tBuffer.image;
dstImage = vFlipImage;
final int[] src = ((DataBufferInt) srcImage.getRaster().getDataBuffer()).getData();
final int[] dst = ((DataBufferInt) dstImage.getRaster().getDataBuffer()).getData();
if( DEBUG_TILES ) {
Arrays.fill(dst, 0x55);
}
final int incr = tBuffer.width;
int srcPos = 0;
int destPos = (tHeight - 1) * tBuffer.width;
for (; destPos >= 0; srcPos += incr, destPos -= incr) {
System.arraycopy(src, srcPos, dst, destPos, incr);
}
} else {
dstImage = tBuffer.image;
}
if( DEBUG_TILES ) {
final String fname = String.format("file_%03d_1_tile_[%02d][%02d]_sz_%03dx%03d_pos0_%03d_%03d_yOff_%03d_pos1_%03d_%03d.png",
_counter,
renderer.getParam(TileRenderer.TR_CURRENT_COLUMN), renderer.getParam(TileRenderer.TR_CURRENT_ROW),
tWidth, tHeight,
pX, pY, pYOff, pX, pYf).replace(' ', '_');
System.err.println("XXX file "+fname);
final File fout = new File(fname);
try {
ImageIO.write(dstImage, "png", fout);
} catch (IOException e) {
e.printStackTrace();
}
_counter++;
}
// Draw resulting image in one shot
final Shape oClip = g2d.getClip();
// g2d.clipRect(pX, pYf, tWidth, tHeight);
final BufferedImage outImage = dstImage.getSubimage(0, 0, tWidth, tHeight); // instead of clipping
final boolean drawDone = g2d.drawImage(outImage, pX, pYf, null); // Null ImageObserver since image data is ready.
// final boolean drawDone = g2d.drawImage(dstImage, pX, pYf, dstImage.getWidth(), dstImage.getHeight(), null); // Null ImageObserver since image data is ready.
if( verbose ) {
System.err.println("XXX tile-post.X clippedImageSize "+cis);
System.err.println("XXX tile-post.X pYf "+cis.getHeight()+" - ( "+pY+" - "+pYOff+" + "+tHeight+" ) "+scaledYOffset+" = "+ pYf);
System.err.println("XXX tile-post.X clip "+oClip+" + "+pX+" / [pY "+pY+", pYOff "+pYOff+", pYf "+pYf+"] "+tWidth+"x"+tHeight+" -> "+g2d.getClip());
g2d.setColor(Color.BLACK);
g2d.drawRect(pX, pYf, tWidth, tHeight);
if( null != oClip ) {
final Rectangle r = oClip.getBounds();
g2d.setColor(Color.YELLOW);
g2d.drawRect(r.x, r.y, r.width, r.height);
}
System.err.println("XXX tile-post.X "+renderer);
System.err.println("XXX tile-post.X dst-img "+dstImage.getWidth()+"x"+dstImage.getHeight());
- System.err.println("XXX tile-post.X out-img "+outImage.getWidth()+"x"+dstImage.getHeight());
+ System.err.println("XXX tile-post.X out-img "+outImage.getWidth()+"x"+outImage.getHeight());
System.err.println("XXX tile-post.X y-flip "+flipVertical+" -> "+pX+"/"+pYf+", drawDone "+drawDone);
}
// g2d.setClip(oClip);
}
@Override
public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) {}
};
}
| true | true | public void display(GLAutoDrawable drawable) {
final DimensionImmutable cis = renderer.getClippedImageSize();
final int tWidth = renderer.getParam(TileRendererBase.TR_CURRENT_TILE_WIDTH);
final int tHeight = renderer.getParam(TileRendererBase.TR_CURRENT_TILE_HEIGHT);
final int pX = renderer.getParam(TileRendererBase.TR_CURRENT_TILE_X_POS);
final int pY = renderer.getParam(TileRendererBase.TR_CURRENT_TILE_Y_POS);
final int pYOff = renderer.getParam(TileRenderer.TR_TILE_Y_OFFSET);
final int pYf;
if( flipVertical ) {
pYf = cis.getHeight() - ( pY - pYOff + tHeight ) + scaledYOffset;
} else {
pYf = pY;
}
// Copy temporary data into raster of BufferedImage for faster
// blitting Note that we could avoid this copy in the cases
// where !offscreenDrawable.isGLOriented(),
// but that's the software rendering path which is very slow anyway.
final BufferedImage dstImage;
if( DEBUG_TILES ) {
final String fname = String.format("file_%03d_0_tile_[%02d][%02d]_sz_%03dx%03d_pos0_%03d_%03d_yOff_%03d_pos1_%03d_%03d.png",
_counter,
renderer.getParam(TileRenderer.TR_CURRENT_COLUMN), renderer.getParam(TileRenderer.TR_CURRENT_ROW),
tWidth, tHeight,
pX, pY, pYOff, pX, pYf).replace(' ', '_');
System.err.println("XXX file "+fname);
final File fout = new File(fname);
try {
ImageIO.write(tBuffer.image, "png", fout);
} catch (IOException e) {
e.printStackTrace();
}
}
if( flipVertical ) {
final BufferedImage srcImage = tBuffer.image;
dstImage = vFlipImage;
final int[] src = ((DataBufferInt) srcImage.getRaster().getDataBuffer()).getData();
final int[] dst = ((DataBufferInt) dstImage.getRaster().getDataBuffer()).getData();
if( DEBUG_TILES ) {
Arrays.fill(dst, 0x55);
}
final int incr = tBuffer.width;
int srcPos = 0;
int destPos = (tHeight - 1) * tBuffer.width;
for (; destPos >= 0; srcPos += incr, destPos -= incr) {
System.arraycopy(src, srcPos, dst, destPos, incr);
}
} else {
dstImage = tBuffer.image;
}
if( DEBUG_TILES ) {
final String fname = String.format("file_%03d_1_tile_[%02d][%02d]_sz_%03dx%03d_pos0_%03d_%03d_yOff_%03d_pos1_%03d_%03d.png",
_counter,
renderer.getParam(TileRenderer.TR_CURRENT_COLUMN), renderer.getParam(TileRenderer.TR_CURRENT_ROW),
tWidth, tHeight,
pX, pY, pYOff, pX, pYf).replace(' ', '_');
System.err.println("XXX file "+fname);
final File fout = new File(fname);
try {
ImageIO.write(dstImage, "png", fout);
} catch (IOException e) {
e.printStackTrace();
}
_counter++;
}
// Draw resulting image in one shot
final Shape oClip = g2d.getClip();
// g2d.clipRect(pX, pYf, tWidth, tHeight);
final BufferedImage outImage = dstImage.getSubimage(0, 0, tWidth, tHeight); // instead of clipping
final boolean drawDone = g2d.drawImage(outImage, pX, pYf, null); // Null ImageObserver since image data is ready.
// final boolean drawDone = g2d.drawImage(dstImage, pX, pYf, dstImage.getWidth(), dstImage.getHeight(), null); // Null ImageObserver since image data is ready.
if( verbose ) {
System.err.println("XXX tile-post.X clippedImageSize "+cis);
System.err.println("XXX tile-post.X pYf "+cis.getHeight()+" - ( "+pY+" - "+pYOff+" + "+tHeight+" ) "+scaledYOffset+" = "+ pYf);
System.err.println("XXX tile-post.X clip "+oClip+" + "+pX+" / [pY "+pY+", pYOff "+pYOff+", pYf "+pYf+"] "+tWidth+"x"+tHeight+" -> "+g2d.getClip());
g2d.setColor(Color.BLACK);
g2d.drawRect(pX, pYf, tWidth, tHeight);
if( null != oClip ) {
final Rectangle r = oClip.getBounds();
g2d.setColor(Color.YELLOW);
g2d.drawRect(r.x, r.y, r.width, r.height);
}
System.err.println("XXX tile-post.X "+renderer);
System.err.println("XXX tile-post.X dst-img "+dstImage.getWidth()+"x"+dstImage.getHeight());
System.err.println("XXX tile-post.X out-img "+outImage.getWidth()+"x"+dstImage.getHeight());
System.err.println("XXX tile-post.X y-flip "+flipVertical+" -> "+pX+"/"+pYf+", drawDone "+drawDone);
}
// g2d.setClip(oClip);
}
| public void display(GLAutoDrawable drawable) {
final DimensionImmutable cis = renderer.getClippedImageSize();
final int tWidth = renderer.getParam(TileRendererBase.TR_CURRENT_TILE_WIDTH);
final int tHeight = renderer.getParam(TileRendererBase.TR_CURRENT_TILE_HEIGHT);
final int pX = renderer.getParam(TileRendererBase.TR_CURRENT_TILE_X_POS);
final int pY = renderer.getParam(TileRendererBase.TR_CURRENT_TILE_Y_POS);
final int pYOff = renderer.getParam(TileRenderer.TR_TILE_Y_OFFSET);
final int pYf;
if( flipVertical ) {
pYf = cis.getHeight() - ( pY - pYOff + tHeight ) + scaledYOffset;
} else {
pYf = pY;
}
// Copy temporary data into raster of BufferedImage for faster
// blitting Note that we could avoid this copy in the cases
// where !offscreenDrawable.isGLOriented(),
// but that's the software rendering path which is very slow anyway.
final BufferedImage dstImage;
if( DEBUG_TILES ) {
final String fname = String.format("file_%03d_0_tile_[%02d][%02d]_sz_%03dx%03d_pos0_%03d_%03d_yOff_%03d_pos1_%03d_%03d.png",
_counter,
renderer.getParam(TileRenderer.TR_CURRENT_COLUMN), renderer.getParam(TileRenderer.TR_CURRENT_ROW),
tWidth, tHeight,
pX, pY, pYOff, pX, pYf).replace(' ', '_');
System.err.println("XXX file "+fname);
final File fout = new File(fname);
try {
ImageIO.write(tBuffer.image, "png", fout);
} catch (IOException e) {
e.printStackTrace();
}
}
if( flipVertical ) {
final BufferedImage srcImage = tBuffer.image;
dstImage = vFlipImage;
final int[] src = ((DataBufferInt) srcImage.getRaster().getDataBuffer()).getData();
final int[] dst = ((DataBufferInt) dstImage.getRaster().getDataBuffer()).getData();
if( DEBUG_TILES ) {
Arrays.fill(dst, 0x55);
}
final int incr = tBuffer.width;
int srcPos = 0;
int destPos = (tHeight - 1) * tBuffer.width;
for (; destPos >= 0; srcPos += incr, destPos -= incr) {
System.arraycopy(src, srcPos, dst, destPos, incr);
}
} else {
dstImage = tBuffer.image;
}
if( DEBUG_TILES ) {
final String fname = String.format("file_%03d_1_tile_[%02d][%02d]_sz_%03dx%03d_pos0_%03d_%03d_yOff_%03d_pos1_%03d_%03d.png",
_counter,
renderer.getParam(TileRenderer.TR_CURRENT_COLUMN), renderer.getParam(TileRenderer.TR_CURRENT_ROW),
tWidth, tHeight,
pX, pY, pYOff, pX, pYf).replace(' ', '_');
System.err.println("XXX file "+fname);
final File fout = new File(fname);
try {
ImageIO.write(dstImage, "png", fout);
} catch (IOException e) {
e.printStackTrace();
}
_counter++;
}
// Draw resulting image in one shot
final Shape oClip = g2d.getClip();
// g2d.clipRect(pX, pYf, tWidth, tHeight);
final BufferedImage outImage = dstImage.getSubimage(0, 0, tWidth, tHeight); // instead of clipping
final boolean drawDone = g2d.drawImage(outImage, pX, pYf, null); // Null ImageObserver since image data is ready.
// final boolean drawDone = g2d.drawImage(dstImage, pX, pYf, dstImage.getWidth(), dstImage.getHeight(), null); // Null ImageObserver since image data is ready.
if( verbose ) {
System.err.println("XXX tile-post.X clippedImageSize "+cis);
System.err.println("XXX tile-post.X pYf "+cis.getHeight()+" - ( "+pY+" - "+pYOff+" + "+tHeight+" ) "+scaledYOffset+" = "+ pYf);
System.err.println("XXX tile-post.X clip "+oClip+" + "+pX+" / [pY "+pY+", pYOff "+pYOff+", pYf "+pYf+"] "+tWidth+"x"+tHeight+" -> "+g2d.getClip());
g2d.setColor(Color.BLACK);
g2d.drawRect(pX, pYf, tWidth, tHeight);
if( null != oClip ) {
final Rectangle r = oClip.getBounds();
g2d.setColor(Color.YELLOW);
g2d.drawRect(r.x, r.y, r.width, r.height);
}
System.err.println("XXX tile-post.X "+renderer);
System.err.println("XXX tile-post.X dst-img "+dstImage.getWidth()+"x"+dstImage.getHeight());
System.err.println("XXX tile-post.X out-img "+outImage.getWidth()+"x"+outImage.getHeight());
System.err.println("XXX tile-post.X y-flip "+flipVertical+" -> "+pX+"/"+pYf+", drawDone "+drawDone);
}
// g2d.setClip(oClip);
}
|
diff --git a/MyParser.java b/MyParser.java
index 9b57649..cb62ff8 100755
--- a/MyParser.java
+++ b/MyParser.java
@@ -1,794 +1,794 @@
//---------------------------------------------------------------------
//
//---------------------------------------------------------------------
import java_cup.runtime.*;
import java.util.Vector;
class MyParser extends parser
{
//----------------------------------------------------------------
// Instance variables
//----------------------------------------------------------------
private Lexer m_lexer;
private ErrorPrinter m_errors;
private int m_nNumErrors;
private String m_strLastLexeme;
private boolean m_bSyntaxError = true;
private int m_nSavedLineNum;
private SymbolTable m_symtab;
//----------------------------------------------------------------
//
//----------------------------------------------------------------
public
MyParser(Lexer lexer, ErrorPrinter errors)
{
m_lexer = lexer;
m_symtab = new SymbolTable();
m_errors = errors;
m_nNumErrors = 0;
}
//----------------------------------------------------------------
//
//----------------------------------------------------------------
public boolean
Ok()
{
return (m_nNumErrors == 0);
}
//----------------------------------------------------------------
//
//----------------------------------------------------------------
public Symbol
scan()
{
Token t = m_lexer.GetToken();
// We'll save the last token read for error messages.
// Sometimes, the token is lost reading for the next
// token which can be null.
m_strLastLexeme = t.GetLexeme();
switch(t.GetCode())
{
case sym.T_ID:
case sym.T_ID_U:
case sym.T_STR_LITERAL:
case sym.T_FLOAT_LITERAL:
case sym.T_INT_LITERAL:
case sym.T_CHAR_LITERAL:
return (new Symbol(t.GetCode(), t.GetLexeme()));
default:
return (new Symbol(t.GetCode()));
}
}
//----------------------------------------------------------------
//
//----------------------------------------------------------------
public void
syntax_error(Symbol s)
{
}
//----------------------------------------------------------------
//
//----------------------------------------------------------------
public void
report_fatal_error(Symbol s)
{
m_nNumErrors++;
if(m_bSyntaxError)
{
m_nNumErrors++;
// It is possible that the error was detected
// at the end of a line - in which case, s will
// be null. Instead, we saved the last token
// read in to give a more meaningful error
// message.
m_errors.print(Formatter.toString(ErrorMsg.syntax_error, m_strLastLexeme));
}
}
//----------------------------------------------------------------
//
//----------------------------------------------------------------
public void
unrecovered_syntax_error(Symbol s)
{
report_fatal_error(s);
}
//----------------------------------------------------------------
//
//----------------------------------------------------------------
public void
DisableSyntaxError()
{
m_bSyntaxError = false;
}
public void
EnableSyntaxError()
{
m_bSyntaxError = true;
}
//----------------------------------------------------------------
//
//----------------------------------------------------------------
public String
GetFile()
{
return (m_lexer.getEPFilename());
}
public int
GetLineNum()
{
return (m_lexer.getLineNumber());
}
public void
SaveLineNum()
{
m_nSavedLineNum = m_lexer.getLineNumber();
}
public int
GetSavedLineNum()
{
return (m_nSavedLineNum);
}
//----------------------------------------------------------------
//
//----------------------------------------------------------------
void
DoProgramStart()
{
// Opens the global scope.
m_symtab.openScope();
}
//----------------------------------------------------------------
//
//----------------------------------------------------------------
void
DoProgramEnd()
{
m_symtab.closeScope();
}
//----------------------------------------------------------------
//
//----------------------------------------------------------------
void
DoVarDecl(Type type, Vector<String> lstIDs)
{
for(int i = 0; i < lstIDs.size(); i++)
{
String id = lstIDs.elementAt(i);
if(m_symtab.accessLocal(id) != null)
{
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.redeclared_id, id));
}
VarSTO sto = new VarSTO(id, type);
m_symtab.insert(sto);
}
}
//----------------------------------------------------------------
//
//----------------------------------------------------------------
void
DoExternDecl(Vector<String> lstIDs)
{
for(int i = 0; i < lstIDs.size(); i++)
{
String id = lstIDs.elementAt(i);
if(m_symtab.accessLocal(id) != null)
{
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.redeclared_id, id));
}
VarSTO sto = new VarSTO(id);
m_symtab.insert(sto);
}
}
//----------------------------------------------------------------
//
//----------------------------------------------------------------
void
DoConstDecl(Vector<String> lstIDs)
{
for(int i = 0; i < lstIDs.size(); i++)
{
String id = lstIDs.elementAt(i);
if(m_symtab.accessLocal(id) != null)
{
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.redeclared_id, id));
}
ConstSTO sto = new ConstSTO(id);
m_symtab.insert(sto);
}
}
//----------------------------------------------------------------
//
//----------------------------------------------------------------
void
DoTypedefDecl(Vector<String> lstIDs)
{
for(int i = 0; i < lstIDs.size(); i++)
{
String id = lstIDs.elementAt(i);
if(m_symtab.accessLocal(id) != null)
{
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.redeclared_id, id));
}
TypedefSTO sto = new TypedefSTO(id);
m_symtab.insert(sto);
}
}
//----------------------------------------------------------------
//
//----------------------------------------------------------------
void
DoStructdefDecl(String id)
{
if(m_symtab.accessLocal(id) != null)
{
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.redeclared_id, id));
}
TypedefSTO sto = new TypedefSTO(id);
m_symtab.insert(sto);
}
//----------------------------------------------------------------
//
//----------------------------------------------------------------
void
DoFuncDecl_1(Type returnType, String id)
{
if(m_symtab.accessLocal(id) != null)
{
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.redeclared_id, id));
}
FuncSTO sto = new FuncSTO(id);
// Set return type
sto.setReturnType(returnType);
m_symtab.insert(sto);
m_symtab.openScope();
m_symtab.setFunc(sto);
// Set the function's level
sto.setLevel(m_symtab.getLevel());
}
//----------------------------------------------------------------
//
//----------------------------------------------------------------
void
DoFuncDecl_2()
{
// Check #6c - no return statement for non-void type function
FuncSTO stoFunc;
if((stoFunc = m_symtab.getFunc()) == null)
{
m_nNumErrors++;
m_errors.print("internal: DoFuncDecl_2 says no proc!");
return;
}
if(!stoFunc.getReturnType().isVoid())
{
if(!stoFunc.getHasReturnStatement())
{
m_nNumErrors++;
m_errors.print(ErrorMsg.error6c_Return_missing);
}
}
m_symtab.closeScope();
m_symtab.setFunc(null);
}
//----------------------------------------------------------------
//
//----------------------------------------------------------------
void
DoFormalParams(Vector<ParamSTO> params)
{
FuncSTO stoFunc;
if((stoFunc = m_symtab.getFunc()) == null)
{
m_nNumErrors++;
m_errors.print("internal: DoFormalParams says no proc!");
return;
}
// Insert parameters
stoFunc.setParameters(params);
}
//----------------------------------------------------------------
//
//----------------------------------------------------------------
void
DoBlockOpen()
{
// Open a scope.
m_symtab.openScope();
}
//----------------------------------------------------------------
//
//----------------------------------------------------------------
void
DoBlockClose()
{
m_symtab.closeScope();
}
//----------------------------------------------------------------
//
//----------------------------------------------------------------
STO
DoAssignExpr(STO stoDes, STO stoValue)
{
// Check for previous errors in line and short circuit
if(stoDes.isError())
{
return stoDes;
}
if(stoValue.isError())
{
return stoValue;
}
// Check #3a - illegal assignment - not modifiable L-value
if(!stoDes.isModLValue())
{
m_nNumErrors++;
m_errors.print(ErrorMsg.error3a_Assign);
return (new ErrorSTO("DoAssignExpr Error - not mod-L-Value"));
}
if(!stoValue.getType().isAssignable(stoDes.getType()))
{
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.error3b_Assign, stoValue.getType().getName(), stoDes.getType().getName()));
return (new ErrorSTO("DoAssignExpr Error - bad types"));
}
return stoDes;
}
//----------------------------------------------------------------
//
//----------------------------------------------------------------
STO
DoFuncCall(STO sto, Vector<ExprSTO> args)
{
if(!sto.isFunc())
{
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.not_function, sto.getName()));
return (new ErrorSTO(sto.getName()));
}
// We know it's a function, do function call checks
FuncSTO stoFunc =(FuncSTO)sto;
// Check #5
// Check #5a - # args = # params
- if(!(stoFunc.getNumOfParams() != args.size()))
+ if((stoFunc.getNumOfParams() != args.size()))
{
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.error5n_Call, args.size(), stoFunc.getNumOfParams()));
return (new ErrorSTO("DoFuncCall - # args"));
}
// Now we check each arg individually, accepting one error per arg
boolean error_flag = false;
for(int i = 0; i < args.size(); i++)
{
// For readability and shorter lines
ParamSTO thisParam = stoFunc.getParameters().elementAt(i);
ExprSTO thisArg = args.elementAt(i);
// Check #5b - non-assignable arg for pass-by-value param
if(!thisParam.isPassByReference())
{
if(!thisArg.getType().isAssignable(thisParam.getType()))
{
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.error5a_Call, thisArg.getType().getName(), thisParam.getName(), thisParam.getType().getName()));
error_flag = true;
}
}
// Check #5c - arg type not equivalent to pass-by-ref param type
else if(thisParam.isPassByReference())
{
if(!thisArg.getType().isEquivalent(thisParam.getType()))
{
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.error5r_Call, thisArg.getType().getName(), thisParam.getName(), thisParam.getType().getName()));
error_flag = true;
}
}
// Check #5d - arg not modifiable l-value for pass by ref param
else if(thisParam.isPassByReference())
{
if(!thisArg.isModLValue())
{
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.error5c_Call, thisArg.getName(), thisArg.getType().getName()));
error_flag = true;
}
}
}
if(error_flag)
{
// Error occured in at least one arg, return error
return (new ErrorSTO("DoFuncCall - Check 5"));
}
else
// Func call legal, return function return type
return (new ExprSTO(stoFunc.getName() + " return type", stoFunc.getReturnType()));
}
//----------------------------------------------------------------
//
//----------------------------------------------------------------
STO
DoDesignator2_Dot(STO sto, String strID)
{
// Good place to do the struct checks
return sto;
}
//----------------------------------------------------------------
//
//----------------------------------------------------------------
STO
DoDesignator2_Array(STO sto)
{
// Good place to do the array checks
return sto;
}
//----------------------------------------------------------------
//
//----------------------------------------------------------------
STO
DoDesignator3_GlobalID(String strID)
{
STO sto;
if((sto = m_symtab.accessGlobal(strID)) == null)
{
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.error0g_Scope, strID));
sto = new ErrorSTO(strID);
}
return (sto);
}
//----------------------------------------------------------------
//
//----------------------------------------------------------------
STO
DoDesignator3_ID(String strID)
{
STO sto;
if((sto = m_symtab.access(strID)) == null)
{
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.undeclared_id, strID));
sto = new ErrorSTO(strID);
}
return (sto);
}
//----------------------------------------------------------------
//
//----------------------------------------------------------------
STO
DoQualIdent(String strID)
{
STO sto;
if((sto = m_symtab.access(strID)) == null)
{
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.undeclared_id, strID));
return (new ErrorSTO(strID));
}
if(!sto.isTypedef())
{
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.not_type, sto.getName()));
return (new ErrorSTO(sto.getName()));
}
return (sto);
}
//----------------------------------------------------------------
// DoBinaryOp
//----------------------------------------------------------------
STO
DoBinaryOp(BinaryOp op, STO operand1, STO operand2)
{
// Check for previous errors in line and short circuit
if(operand1.isError())
{
return operand1;
}
if(operand2.isError())
{
return operand2;
}
// Use BinaryOp.checkOperands() to perform error checks
STO resultSTO = op.checkOperands(operand1, operand2);
// Process/Print errors
if(resultSTO.isError())
{
m_nNumErrors++;
m_errors.print(resultSTO.getName());
}
return resultSTO;
}
//----------------------------------------------------------------
// DoUnaryOp
//----------------------------------------------------------------
STO
DoUnaryOp(UnaryOp op, STO operand)
{
// Check for previous errors in line and short circuit
if(operand.isError())
{
return operand;
}
// Use UnaryOp.checkOperand() to perform error checks
STO resultSTO = op.checkOperand(operand);
// Process/Print errors
if(resultSTO.isError())
{
m_nNumErrors++;
m_errors.print(resultSTO.getName());
}
return resultSTO;
}
//----------------------------------------------------------------
// DoWhileExpr
//----------------------------------------------------------------
STO
DoWhileExpr(STO stoExpr)
{
// Check for previous errors in line and short circuit
if(stoExpr.isError())
{
return stoExpr;
}
// Check #4 - while expr - int or bool
if((!stoExpr.getType().isInt()) &&(!stoExpr.getType().isBool()))
{
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.error4_Test, stoExpr.getType().getName()));
return (new ErrorSTO("DoWhile error"));
}
return stoExpr;
}
//----------------------------------------------------------------
// DoIfExpr
//----------------------------------------------------------------
STO
DoIfExpr(STO stoExpr)
{
// Check for previous errors in line and short circuit
if(stoExpr.isError())
{
return stoExpr;
}
// Check #4 - if expr - int or bool
if((!stoExpr.getType().isInt()) &&(!stoExpr.getType().isBool()))
{
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.error4_Test, stoExpr.getType().getName()));
return (new ErrorSTO("DoIf error"));
}
return stoExpr;
}
//----------------------------------------------------------------
// DoReturnStmt_1
//----------------------------------------------------------------
STO
DoReturnStmt_1()
{
FuncSTO stoFunc;
if((stoFunc = m_symtab.getFunc()) == null)
{
m_nNumErrors++;
m_errors.print("internal: DoReturnStmt_1 says no proc!");
return (new ErrorSTO("DoReturnStmt_1 Error"));
}
// Check #6a - no expr on non-void rtn
if(!stoFunc.getReturnType().isVoid())
{
m_nNumErrors++;
m_errors.print(ErrorMsg.error6a_Return_expr);
return (new ErrorSTO("DoReturnStmt_1 Error"));
}
// valid return statement, set func.hasReturnStatement
stoFunc.setHasReturnStatement(true);
return (new ExprSTO(stoFunc.getName() + " Return", new VoidType()));
}
//----------------------------------------------------------------
// DoReturnStmt_2
//----------------------------------------------------------------
STO
DoReturnStmt_2(STO stoExpr)
{
FuncSTO stoFunc;
// Check for previous errors in line and short circuit
if(stoExpr.isError())
{
return stoExpr;
}
if((stoFunc = m_symtab.getFunc()) == null)
{
m_nNumErrors++;
m_errors.print("internal: DoReturnStmt_2 says no proc!");
return (new ErrorSTO("DoReturnStmt_2 Error"));
}
// Check #6b - 1st bullet - rtn by val - rtn expr type not assignable to return
if(!stoFunc.getReturnByRef())
{
if(!stoExpr.getType().isAssignable(stoFunc.getReturnType()))
{
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg. error6a_Return_type, stoExpr.getType().getName(), stoFunc.getReturnType().getName()));
return (new ErrorSTO("DoReturnStmt_2 Error"));
}
}
else
{
// Check #6b - 2nd bullet - rtn by ref - rtn expr type not equivalent to return type
if(!stoExpr.getType().isEquivalent(stoFunc.getReturnType()))
{
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.error6b_Return_equiv, stoExpr.getType().getName(), stoFunc.getReturnType().getName()));
return (new ErrorSTO("DoReturnStmt_2 Error"));
}
// Check #6b - 3rd bullet - rtn by ref - rtn expr not modLValue
if(!stoExpr.isModLValue())
{
m_nNumErrors++;
m_errors.print(ErrorMsg.error6b_Return_modlval);
return (new ErrorSTO("DoReturnStmt_2 Error"));
}
}
// valid return statement, set func.hasReturnStatement
stoFunc.setHasReturnStatement(true);
return stoExpr;
}
//----------------------------------------------------------------
// DoExitStmt
//----------------------------------------------------------------
STO
DoExitStmt(STO stoExpr)
{
// Check for previous errors in line and short circuit
if(stoExpr.isError())
{
return stoExpr;
}
// Check #7 - exit value assignable to int
if(!stoExpr.getType().isAssignable(new IntType()))
{
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.error7_Exit, stoExpr.getType().getName()));
}
return stoExpr;
}
}
| true | true | STO
DoFuncCall(STO sto, Vector<ExprSTO> args)
{
if(!sto.isFunc())
{
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.not_function, sto.getName()));
return (new ErrorSTO(sto.getName()));
}
// We know it's a function, do function call checks
FuncSTO stoFunc =(FuncSTO)sto;
// Check #5
// Check #5a - # args = # params
if(!(stoFunc.getNumOfParams() != args.size()))
{
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.error5n_Call, args.size(), stoFunc.getNumOfParams()));
return (new ErrorSTO("DoFuncCall - # args"));
}
// Now we check each arg individually, accepting one error per arg
boolean error_flag = false;
for(int i = 0; i < args.size(); i++)
{
// For readability and shorter lines
ParamSTO thisParam = stoFunc.getParameters().elementAt(i);
ExprSTO thisArg = args.elementAt(i);
// Check #5b - non-assignable arg for pass-by-value param
if(!thisParam.isPassByReference())
{
if(!thisArg.getType().isAssignable(thisParam.getType()))
{
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.error5a_Call, thisArg.getType().getName(), thisParam.getName(), thisParam.getType().getName()));
error_flag = true;
}
}
// Check #5c - arg type not equivalent to pass-by-ref param type
else if(thisParam.isPassByReference())
{
if(!thisArg.getType().isEquivalent(thisParam.getType()))
{
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.error5r_Call, thisArg.getType().getName(), thisParam.getName(), thisParam.getType().getName()));
error_flag = true;
}
}
// Check #5d - arg not modifiable l-value for pass by ref param
else if(thisParam.isPassByReference())
{
if(!thisArg.isModLValue())
{
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.error5c_Call, thisArg.getName(), thisArg.getType().getName()));
error_flag = true;
}
}
}
if(error_flag)
{
// Error occured in at least one arg, return error
return (new ErrorSTO("DoFuncCall - Check 5"));
}
else
// Func call legal, return function return type
return (new ExprSTO(stoFunc.getName() + " return type", stoFunc.getReturnType()));
}
| STO
DoFuncCall(STO sto, Vector<ExprSTO> args)
{
if(!sto.isFunc())
{
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.not_function, sto.getName()));
return (new ErrorSTO(sto.getName()));
}
// We know it's a function, do function call checks
FuncSTO stoFunc =(FuncSTO)sto;
// Check #5
// Check #5a - # args = # params
if((stoFunc.getNumOfParams() != args.size()))
{
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.error5n_Call, args.size(), stoFunc.getNumOfParams()));
return (new ErrorSTO("DoFuncCall - # args"));
}
// Now we check each arg individually, accepting one error per arg
boolean error_flag = false;
for(int i = 0; i < args.size(); i++)
{
// For readability and shorter lines
ParamSTO thisParam = stoFunc.getParameters().elementAt(i);
ExprSTO thisArg = args.elementAt(i);
// Check #5b - non-assignable arg for pass-by-value param
if(!thisParam.isPassByReference())
{
if(!thisArg.getType().isAssignable(thisParam.getType()))
{
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.error5a_Call, thisArg.getType().getName(), thisParam.getName(), thisParam.getType().getName()));
error_flag = true;
}
}
// Check #5c - arg type not equivalent to pass-by-ref param type
else if(thisParam.isPassByReference())
{
if(!thisArg.getType().isEquivalent(thisParam.getType()))
{
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.error5r_Call, thisArg.getType().getName(), thisParam.getName(), thisParam.getType().getName()));
error_flag = true;
}
}
// Check #5d - arg not modifiable l-value for pass by ref param
else if(thisParam.isPassByReference())
{
if(!thisArg.isModLValue())
{
m_nNumErrors++;
m_errors.print(Formatter.toString(ErrorMsg.error5c_Call, thisArg.getName(), thisArg.getType().getName()));
error_flag = true;
}
}
}
if(error_flag)
{
// Error occured in at least one arg, return error
return (new ErrorSTO("DoFuncCall - Check 5"));
}
else
// Func call legal, return function return type
return (new ExprSTO(stoFunc.getName() + " return type", stoFunc.getReturnType()));
}
|
diff --git a/web/src/main/java/org/mule/galaxy/web/server/RegistryServiceImpl.java b/web/src/main/java/org/mule/galaxy/web/server/RegistryServiceImpl.java
index e0e8f228..eb5d43a9 100755
--- a/web/src/main/java/org/mule/galaxy/web/server/RegistryServiceImpl.java
+++ b/web/src/main/java/org/mule/galaxy/web/server/RegistryServiceImpl.java
@@ -1,1835 +1,1835 @@
/*
* $Id: ContextPathResolver.java 794 2008-04-23 22:23:10Z andrew $
* --------------------------------------------------------------------------------------
* 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 org.mule.galaxy.web.server;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.xml.namespace.QName;
import org.acegisecurity.context.SecurityContextHolder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.mule.galaxy.Artifact;
import org.mule.galaxy.ArtifactType;
import org.mule.galaxy.ArtifactTypeDao;
import org.mule.galaxy.ArtifactVersion;
import org.mule.galaxy.DuplicateItemException;
import org.mule.galaxy.Entry;
import org.mule.galaxy.EntryResult;
import org.mule.galaxy.EntryVersion;
import org.mule.galaxy.Item;
import org.mule.galaxy.Link;
import org.mule.galaxy.Links;
import org.mule.galaxy.NotFoundException;
import org.mule.galaxy.PropertyException;
import org.mule.galaxy.PropertyInfo;
import org.mule.galaxy.Registry;
import org.mule.galaxy.RegistryException;
import org.mule.galaxy.Workspace;
import org.mule.galaxy.activity.Activity;
import org.mule.galaxy.activity.ActivityManager;
import org.mule.galaxy.activity.ActivityManager.EventType;
import org.mule.galaxy.collab.Comment;
import org.mule.galaxy.collab.CommentManager;
import org.mule.galaxy.event.EventManager;
import org.mule.galaxy.extension.Extension;
import org.mule.galaxy.impl.jcr.UserDetailsWrapper;
import org.mule.galaxy.index.Index;
import org.mule.galaxy.index.IndexManager;
import org.mule.galaxy.lifecycle.Lifecycle;
import org.mule.galaxy.lifecycle.LifecycleManager;
import org.mule.galaxy.lifecycle.Phase;
import org.mule.galaxy.policy.ApprovalMessage;
import org.mule.galaxy.policy.Policy;
import org.mule.galaxy.policy.PolicyException;
import org.mule.galaxy.policy.PolicyManager;
import org.mule.galaxy.query.OpRestriction;
import org.mule.galaxy.query.Query;
import org.mule.galaxy.query.QueryException;
import org.mule.galaxy.query.Restriction;
import org.mule.galaxy.query.SearchResults;
import org.mule.galaxy.query.OpRestriction.Operator;
import org.mule.galaxy.render.ItemRenderer;
import org.mule.galaxy.render.RendererManager;
import org.mule.galaxy.security.AccessControlManager;
import org.mule.galaxy.security.AccessException;
import org.mule.galaxy.security.Permission;
import org.mule.galaxy.security.User;
import org.mule.galaxy.security.UserManager;
import org.mule.galaxy.type.PropertyDescriptor;
import org.mule.galaxy.type.TypeManager;
import org.mule.galaxy.view.View;
import org.mule.galaxy.view.ArtifactViewManager;
import org.mule.galaxy.web.client.RPCException;
import org.mule.galaxy.web.rpc.EntryGroup;
import org.mule.galaxy.web.rpc.EntryVersionInfo;
import org.mule.galaxy.web.rpc.EntryInfo;
import org.mule.galaxy.web.rpc.ExtendedEntryInfo;
import org.mule.galaxy.web.rpc.ItemExistsException;
import org.mule.galaxy.web.rpc.ItemNotFoundException;
import org.mule.galaxy.web.rpc.LinkInfo;
import org.mule.galaxy.web.rpc.RegistryService;
import org.mule.galaxy.web.rpc.SearchPredicate;
import org.mule.galaxy.web.rpc.WActivity;
import org.mule.galaxy.web.rpc.WApprovalMessage;
import org.mule.galaxy.web.rpc.WPolicy;
import org.mule.galaxy.web.rpc.WArtifactType;
import org.mule.galaxy.web.rpc.WArtifactView;
import org.mule.galaxy.web.rpc.WComment;
import org.mule.galaxy.web.rpc.WExtensionInfo;
import org.mule.galaxy.web.rpc.WGovernanceInfo;
import org.mule.galaxy.web.rpc.WIndex;
import org.mule.galaxy.web.rpc.WLifecycle;
import org.mule.galaxy.web.rpc.WPhase;
import org.mule.galaxy.web.rpc.WPolicyException;
import org.mule.galaxy.web.rpc.WProperty;
import org.mule.galaxy.web.rpc.WPropertyDescriptor;
import org.mule.galaxy.web.rpc.WSearchResults;
import org.mule.galaxy.web.rpc.WUser;
import org.mule.galaxy.web.rpc.WWorkspace;
public class RegistryServiceImpl implements RegistryService {
protected static final String DEFAULT_DATETIME_FORMAT = "h:mm a, MMMM d, yyyy";
private static final String RECENT_VIEWS = "recent.artifactViews";
private final Log log = LogFactory.getLog(getClass());
private Registry registry;
private ArtifactTypeDao artifactTypeDao;
private RendererManager rendererManager;
private PolicyManager policyManager;
private IndexManager indexManager;
private ActivityManager activityManager;
private AccessControlManager accessControlManager;
private ArtifactViewManager artifactViewManager;
private TypeManager typeManager;
private UserManager userManager;
private ContextPathResolver contextPathResolver;
private LifecycleManager localLifecycleManager;
private EventManager eventManager;
public List<WExtensionInfo> getExtensions() throws RPCException {
ArrayList<WExtensionInfo> exts = new ArrayList<WExtensionInfo>();
for (Extension e : registry.getExtensions()) {
exts.add(new WExtensionInfo(e.getId(), e.getName(), e.getPropertyDescriptorConfigurationKeys(), e.isMultivalueSupported()));
}
return exts;
}
public Collection<WWorkspace> getWorkspaces() throws RPCException {
try {
Collection<Workspace> workspaces = registry.getWorkspaces();
List<WWorkspace> wis = new ArrayList<WWorkspace>();
for (Workspace w : workspaces) {
WWorkspace ww = toWeb(w);
wis.add(ww);
}
return wis;
} catch (RegistryException e) {
log.error(e.getMessage(), e);
throw new RPCException(e.getMessage());
} catch (AccessException e) {
throw new RPCException(e.getMessage());
}
}
private WWorkspace toWeb(Workspace w) {
WWorkspace ww = new WWorkspace(w.getId(), w.getName(), w.getPath());
ww.setDefaultLifecycleId(w.getDefaultLifecycle().getId());
Collection<Workspace> children = w.getWorkspaces();
if (children != null && children.size() > 0) {
ww.setWorkspaces(new ArrayList<WWorkspace>());
addWorkspaces(ww, children);
}
return ww;
}
private void addWorkspaces(WWorkspace parent, Collection<Workspace> workspaces) {
for (Workspace w : workspaces) {
WWorkspace ww = new WWorkspace(w.getId(), w.getName(), w.getPath());
parent.getWorkspaces().add(ww);
Collection<Workspace> children = w.getWorkspaces();
if (children != null && children.size() > 0) {
ww.setWorkspaces(new ArrayList<WWorkspace>());
addWorkspaces(ww, children);
}
}
}
public void addWorkspace(String parentWorkspaceId, String workspaceName, String lifecycleId) throws RPCException, ItemNotFoundException, ItemExistsException {
try {
Workspace w;
if (parentWorkspaceId == null || "[No parent]".equals(parentWorkspaceId)) {
w = registry.createWorkspace(workspaceName);
} else {
Workspace parent = (Workspace) registry.getItemById(parentWorkspaceId);
w = registry.createWorkspace(parent, workspaceName);
}
if (lifecycleId != null) {
w.setDefaultLifecycle(w.getLifecycleManager().getLifecycleById(lifecycleId));
registry.save(w);
}
} catch (DuplicateItemException e) {
throw new ItemExistsException();
} catch (RegistryException e) {
log.error(e.getMessage(), e);
throw new RPCException(e.getMessage());
} catch (NotFoundException e) {
log.error(e.getMessage(), e);
throw new ItemNotFoundException();
} catch (AccessException e) {
throw new RPCException(e.getMessage());
}
}
public void updateWorkspace(String workspaceId, String parentWorkspaceId, String workspaceName, String lifecycleId)
throws RPCException, ItemNotFoundException {
try {
if (parentWorkspaceId == null || "[No parent]".equals(parentWorkspaceId)) {
parentWorkspaceId = null;
}
Workspace w = (Workspace) registry.getItemById(workspaceId);
if (lifecycleId != null) {
w.setDefaultLifecycle(w.getLifecycleManager().getLifecycleById(lifecycleId));
}
w.setName(workspaceName);
registry.save(w, parentWorkspaceId);
} catch (RegistryException e) {
log.error(e.getMessage(), e);
throw new RPCException(e.getMessage());
} catch (NotFoundException e) {
throw new ItemNotFoundException();
} catch (AccessException e) {
throw new RPCException(e.getMessage());
}
}
public void deleteWorkspace(String workspaceId) throws RPCException, ItemNotFoundException {
try {
registry.getItemById(workspaceId).delete();
} catch (RegistryException e) {
log.error(e.getMessage(), e);
throw new RPCException(e.getMessage());
} catch (NotFoundException e) {
throw new ItemNotFoundException();
} catch (AccessException e) {
throw new RPCException(e.getMessage());
}
}
public String newEntry(String workspaceId, String name, String version)
throws RPCException, ItemExistsException, WPolicyException, ItemNotFoundException {
try {
Workspace w = (Workspace) registry.getItemById(workspaceId);
EntryResult result = w.newEntry(name, version);
return result.getEntry().getId();
} catch (RegistryException e) {
log.error(e.getMessage(), e);
throw new RPCException(e.getMessage());
} catch (AccessException e) {
throw new RPCException(e.getMessage());
} catch (DuplicateItemException e) {
throw new ItemExistsException();
} catch (PolicyException e) {
throw toWeb(e);
} catch (NotFoundException e) {
throw new ItemNotFoundException();
}
}
public String newEntryVersion(String entryId, String version)
throws RPCException, ItemExistsException, WPolicyException, ItemNotFoundException {
try {
Entry e = (Entry) registry.getItemById(entryId);
EntryResult result = e.newVersion(version);
return result.getEntryVersion().getId();
} catch (RegistryException e) {
log.error(e.getMessage(), e);
throw new RPCException(e.getMessage());
} catch (AccessException e) {
throw new RPCException(e.getMessage());
} catch (DuplicateItemException e) {
throw new ItemExistsException();
} catch (PolicyException e) {
throw toWeb(e);
} catch (NotFoundException e) {
throw new ItemNotFoundException();
}
}
public Collection<WArtifactType> getArtifactTypes() {
Collection<ArtifactType> artifactTypes = artifactTypeDao.listAll();
List<WArtifactType> atis = new ArrayList<WArtifactType>();
for (ArtifactType a : artifactTypes) {
WArtifactType at = toWeb(a);
atis.add(at);
}
return atis;
}
public WArtifactType getArtifactType(String id) throws RPCException {
try {
return toWeb(artifactTypeDao.get(id));
} catch (Exception e) {
throw new RPCException(e.getMessage());
}
}
private WArtifactType toWeb(ArtifactType a) {
Set<QName> docTypes = a.getDocumentTypes();
List<String> docTypesAsStr = new ArrayList<String>();
if (docTypes != null) {
for (QName q : docTypes) {
docTypesAsStr.add(q.toString());
}
}
return new WArtifactType(a.getId(), a.getContentType(),
a.getDescription(), docTypesAsStr,
a.getFileExtensions());
}
public void deleteArtifactType(String id) throws RPCException {
try {
artifactTypeDao.delete(id);
} catch (RuntimeException e) {
log.error(e.getMessage(), e);
throw new RPCException(e.getMessage());
}
}
public void saveArtifactType(WArtifactType artifactType) throws RPCException, ItemExistsException {
try {
ArtifactType at = fromWeb(artifactType);
artifactTypeDao.save(at);
} catch (RuntimeException e) {
log.error(e.getMessage(), e);
throw new RPCException(e.getMessage());
} catch (DuplicateItemException e) {
throw new ItemExistsException();
} catch (NotFoundException e) {
throw new RPCException(e.getMessage());
}
}
private ArtifactType fromWeb(WArtifactType wat) {
ArtifactType at = new ArtifactType();
at.setId(wat.getId());
at.setDescription(wat.getDescription());
at.setContentType(wat.getMediaType());
at.setDocumentTypes(fromWeb(wat.getDocumentTypes()));
HashSet<String> exts = new HashSet<String>();
exts.addAll((Collection<String>) wat.getFileExtensions());
at.setFileExtensions(exts);
return at;
}
private Set<QName> fromWeb(Collection<String> documentTypes) {
if (documentTypes == null) return null;
Set<QName> s = new HashSet<QName>();
for (Object o : documentTypes) {
String qn = o.toString();
if (qn.startsWith("{}")) {
qn = qn.substring(2);
}
s.add(QName.valueOf(qn));
}
return s;
}
private OpRestriction getRestrictionForPredicate(SearchPredicate pred) {
String property = pred.getProperty();
String value = pred.getValue();
switch (pred.getMatchType()) {
case SearchPredicate.HAS_VALUE:
return OpRestriction.eq(property, value);
case SearchPredicate.LIKE:
return OpRestriction.like(property, value);
case SearchPredicate.DOES_NOT_HAVE_VALUE:
return OpRestriction.not(OpRestriction.eq(property, value));
default:
return null;
}
}
public WSearchResults getArtifacts(String workspaceId, String workspacePath, boolean includeChildWkspcs,
Set<String> artifactTypes, Set<SearchPredicate> searchPredicates, String freeformQuery,
int start, int maxResults) throws RPCException {
Query q = getQuery(searchPredicates, start, maxResults);
if (workspaceId != null) {
q.workspaceId(workspaceId, includeChildWkspcs);
} else if (workspacePath != null && !"".equals(workspacePath) && !"/".equals(workspacePath)) {
q.workspacePath(workspacePath, includeChildWkspcs);
}
try {
SearchResults results;
if (freeformQuery != null && !freeformQuery.equals(""))
results = registry.search(freeformQuery, start, maxResults);
else
results = registry.search(q);
return getSearchResults(artifactTypes, results);
} catch (QueryException e) {
throw new RPCException(e.getMessage());
} catch (RegistryException e) {
log.error("Could not query the registry.", e);
throw new RPCException(e.getMessage());
}
}
private Query getQuery(Set<SearchPredicate> searchPredicates, int start, int maxResults) {
Query q = new Query().orderBy("artifactType");
q.setMaxResults(maxResults);
q.setStart(start);
// Filter based on our search terms
if (searchPredicates != null) {
for (Object predObj : searchPredicates) {
SearchPredicate pred = (SearchPredicate) predObj;
q.add(getRestrictionForPredicate(pred));
}
}
return q;
}
private WSearchResults getSearchResults(Set<String> artifactTypes, SearchResults results) {
Map<String, EntryGroup> name2group = new HashMap<String, EntryGroup>();
Map<String, ItemRenderer> name2view = new HashMap<String, ItemRenderer>();
int total = 0;
for (Object obj : results.getResults()) {
Entry e = (Entry) obj;
String groupName;
ArtifactType type = null;
if (e instanceof Artifact) {
type = artifactTypeDao.getArtifactType(
((Artifact) e).getContentType().toString(),
((Artifact) e).getDocumentType());
groupName = type.getDescription();
} else {
groupName = "Entries";
}
// If we want to filter based on the artifact type, filter!
if (artifactTypes != null && artifactTypes.size() != 0
- && type != null
- && !artifactTypes.contains(type.getId())) {
+ && (type == null
+ || !artifactTypes.contains(type.getId()))) {
continue;
}
total++;
EntryGroup g = name2group.get(groupName);
ItemRenderer view = name2view.get(groupName);
if (g == null) {
g = new EntryGroup();
g.setName(groupName);
name2group.put(groupName, g);
if (e instanceof Artifact) {
Artifact a = (Artifact) e;
view = rendererManager.getArtifactRenderer(a.getDocumentType());
if (view == null) {
view = rendererManager.getArtifactRenderer(a.getContentType().toString());
}
} else {
// Hack
view = rendererManager.getArtifactRenderer("application/octet-stream");
}
name2view.put(groupName, view);
int i = 0;
for (String col : view.getColumnNames()) {
if (view.isSummary(i)) {
g.getColumns().add(col);
}
i++;
}
}
EntryInfo info = createBasicEntryInfo(e, view);
g.getRows().add(info);
}
List<EntryGroup> values = new ArrayList<EntryGroup>();
List<String> keys = new ArrayList<String>();
keys.addAll(name2group.keySet());
Collections.sort(keys);
for (String key : keys) {
values.add(name2group.get(key));
}
WSearchResults wsr = new WSearchResults();
wsr.setResults(values);
wsr.setTotal(total);
return wsr;
}
private EntryInfo createBasicEntryInfo(Entry a, ItemRenderer view) {
EntryInfo info = new EntryInfo();
return createBasicEntryInfo(a, view, info, false);
}
private EntryInfo createBasicEntryInfo(Entry a,
ItemRenderer view,
EntryInfo info,
boolean extended) {
info.setId(a.getId());
info.setWorkspaceId(a.getParent().getId());
info.setName(a.getName());
info.setPath(a.getParent().getPath());
int column = 0;
for (int i = 0; i < view.getColumnNames().length; i++) {
if (!extended && view.isSummary(i)) {
info.setColumn(column, view.getColumnValue(a, i));
column++;
} else if (extended && view.isDetail(i)) {
info.setColumn(column, view.getColumnValue(a, i));
column++;
}
}
return info;
}
public WSearchResults getArtifactsForView(String viewId,
int resultStart,
int maxResults)
throws RPCException {
View view = artifactViewManager.getArtifactView(viewId);
try {
return getSearchResults(null, registry.search(view.getQuery(), resultStart, maxResults));
} catch (QueryException e) {
throw new RPCException(e.getMessage());
} catch (RegistryException e) {
log.error("Could not query the registry.", e);
throw new RPCException(e.getMessage());
}
}
@SuppressWarnings("unchecked")
public void deleteArtifactView(String id) throws RPCException {
artifactViewManager.delete(id);
// clean up recent views too
User user = getCurrentUser();
List<String> views = (List<String>) user.getProperties().get(RECENT_VIEWS);
boolean wasFound = views.remove(id);
assert wasFound : "View deleted, but no corresponding Recent Views entry found for " + id;
}
public WArtifactView getArtifactView(String id) throws RPCException, ItemExistsException, ItemNotFoundException {
User user = getCurrentUser();
WArtifactView view = toWeb(artifactViewManager.getArtifactView(id));
try {
updateRecentArtifactViews(user, id);
} catch (DuplicateItemException e) {
throw new ItemExistsException();
} catch (NotFoundException e) {
log.error(e.getMessage(), e);
throw new ItemNotFoundException();
}
return view;
}
private void updateRecentArtifactViews(User user, String id) throws DuplicateItemException, NotFoundException {
List<String> recent = getRecentArtifactViewIds(user);
// remove this id if it alread exists
recent.remove(id);
// add the view to the top of the list
recent.add(0, id);
while (recent.size() > 5) {
recent.remove(recent.size() - 1);
}
userManager.save(user);
}
@SuppressWarnings("unchecked")
private List<String> getRecentArtifactViewIds(User user) {
if (user.getProperties() == null) {
user.setProperties(new HashMap<String, Object>());
}
List<String> recent = (List<String>) user.getProperties().get(RECENT_VIEWS);
if (recent == null) {
recent = new ArrayList<String>();
user.getProperties().put(RECENT_VIEWS, recent);
}
return recent;
}
public Collection<WArtifactView> getArtifactViews() throws RPCException {
List<WArtifactView> views = new ArrayList<WArtifactView>();
User currentUser = getCurrentUser();
for (View v : artifactViewManager.getArtifactViews(currentUser)) {
views.add(toWeb(v));
}
Collections.sort(views, new Comparator<WArtifactView>() {
public int compare(WArtifactView v1, WArtifactView v2) {
return v1.getName().compareTo(v2.getName());
}
});
return views;
}
public Collection<WArtifactView> getRecentArtifactViews() throws RPCException {
List<WArtifactView> views = new ArrayList<WArtifactView>();
User currentUser = getCurrentUser();
List<String> ids = getRecentArtifactViewIds(currentUser);
if (ids != null) {
for (String id : ids) {
views.add(toWeb(artifactViewManager.getArtifactView(id)));
}
}
return views;
}
private WArtifactView toWeb(View v) throws RPCException {
WArtifactView wv = new WArtifactView();
if (v == null) {
return wv;
}
wv.setName(v.getName());
wv.setId(v.getId());
try {
Query q = Query.fromString(v.getQuery());
wv.setPredicates(getPredicates(q));
wv.setShared(v.getUser() == null);
wv.setWorkspace(q.getWorkspacePath());
wv.setWorkspaceSearchRecursive(q.isWorkspaceSearchRecursive());
} catch (QueryException e) {
log.error("Could not parse query. " + e.getMessage(), e);
throw new RPCException(e.getMessage());
}
return wv;
}
/**
* Convert a string query to a set of search predicates for the SearchForm.
* You'll see that we do not have full fidelity yet between text queries and
* the actual form. However, that is not a problem as we'll only ever encounter
* queries which were created with the form. So there are some cases here
* that we don't have to worry about.
*
* @param q
* @return
* @throws RPCException
*/
public Set<SearchPredicate> getPredicates(Query q) throws RPCException {
Set<SearchPredicate> predicates = new HashSet<SearchPredicate>();
for (Restriction r : q.getRestrictions()) {
if (r instanceof OpRestriction) {
OpRestriction op = (OpRestriction) r;
Object left = op.getLeft();
Object right = op.getRight();
Operator operator = op.getOperator();
if (operator.equals(Operator.NOT)) {
if (right instanceof OpRestriction) {
OpRestriction op2 = (OpRestriction) right;
predicates.add(new SearchPredicate(op2.getLeft().toString(),
SearchPredicate.DOES_NOT_HAVE_VALUE,
op2.getRight().toString()));
} else {
throw new RPCException("Query could not be converted.");
}
} else if (operator.equals(Operator.EQUALS)) {
predicates.add(new SearchPredicate(left.toString(), SearchPredicate.HAS_VALUE, right.toString()));
} else if (operator.equals(Operator.LIKE)) {
predicates.add(new SearchPredicate(left.toString(), SearchPredicate.LIKE, right.toString()));
}
}
}
return predicates;
}
public String saveArtifactView(WArtifactView wv) throws RPCException {
View v = fromWeb(wv);
try {
artifactViewManager.save(v);
return v.getId();
} catch (DuplicateItemException e) {
log.error(e.getMessage(), e);
throw new RPCException("Couldn't save view.");
} catch (NotFoundException e) {
log.error(e.getMessage(), e);
throw new RPCException("The view being saved has been deleted.");
}
}
private View fromWeb(WArtifactView wv) throws RPCException {
View v = new View();
v.setId(wv.getId());
v.setName(wv.getName());
if (!wv.isShared()) {
v.setUser(getCurrentUser());
}
Query query = getQuery(wv.getPredicates(), 0, 0);
query.workspacePath(wv.getWorkspace(), wv.isWorkspaceSearchRecursive());
v.setQuery(query.toString());
return v;
}
public Collection<WIndex> getIndexes() {
ArrayList<WIndex> windexes = new ArrayList<WIndex>();
Collection<Index> indices = indexManager.getIndexes();
for (Index idx : indices) {
windexes.add(toWeb(idx));
}
return windexes;
}
private WIndex toWeb(Index idx) {
ArrayList<String> docTypes = new ArrayList<String>();
if (idx.getDocumentTypes() != null) {
for (QName q : idx.getDocumentTypes()) {
docTypes.add(q.toString());
}
}
String qt;
if (String.class.equals(idx.getQueryType())) {
qt = "String";
} else {
qt = "QName";
}
return new WIndex(idx.getId(),
idx.getDescription(),
idx.getMediaType(),
idx.getConfiguration().get("property"),
idx.getConfiguration().get("expression"),
idx.getIndexer(),
qt,
docTypes);
}
public WIndex getIndex(String id) throws RPCException {
try {
Index idx = indexManager.getIndex(id);
if (idx == null) {
return null;
}
return toWeb(idx);
} catch (Exception e) {
throw new RPCException("Could not find index " + id);
}
}
public void saveIndex(WIndex wi) throws RPCException {
try {
Index idx = fromWeb(wi);
indexManager.save(idx);
} catch (Exception e) {
log.error(e.getMessage(), e);
throw new RPCException("Couldn't save index.");
}
}
public void deleteIndex(String id, boolean removeArtifactMetadata) throws RPCException {
try {
indexManager.delete(id, removeArtifactMetadata);
} catch (Exception e) {
log.error(e.getMessage(), e);
throw new RPCException("Couldn't save index.");
}
}
private Index fromWeb(WIndex wi) throws RPCException {
Index idx = new Index();
idx.setId(wi.getId());
idx.setConfiguration(new HashMap<String, String>());
idx.setIndexer(wi.getIndexer());
if (idx.getIndexer().contains("Groovy")) {
idx.getConfiguration().put("script", wi.getExpression());
} else {
idx.getConfiguration().put("property", wi.getProperty());
idx.getConfiguration().put("expression", wi.getExpression());
}
idx.setIndexer(wi.getIndexer());
idx.setDescription(wi.getDescription());
idx.setMediaType(wi.getMediaType());
if (wi.getResultType().equals("String")) {
idx.setQueryType(String.class);
} else {
idx.setQueryType(QName.class);
}
Set<QName> docTypes = new HashSet<QName>();
for (Object o : wi.getDocumentTypes()) {
try {
docTypes.add(QName.valueOf(o.toString()));
} catch (IllegalArgumentException e) {
throw new RPCException("QName was formatted incorrectly: " + o.toString());
}
}
idx.setDocumentTypes(docTypes);
return idx;
}
public Collection<LinkInfo> getLinks(String itemId, String property) throws RPCException {
try {
Item item = registry.getItemById(itemId);
Links links = (Links) item.getProperty(property);
List<LinkInfo> deps = new ArrayList<LinkInfo>();
for (Link l : links.getLinks()) {
deps.add(toWeb(l, false));
}
for (Link l : links.getReciprocalLinks()) {
deps.add(toWeb(l, true));
}
return deps;
} catch (Exception e) {
log.error(e.getMessage(), e);
throw new RPCException("Could not find artifact " + itemId);
}
}
private LinkInfo toWeb(Link l, boolean recip) {
Item i = recip ? l.getItem() : l.getLinkedTo();
String name;
int itemType;
String id = null;
if (i instanceof Entry) {
itemType = LinkInfo.TYPE_ENTRY;
name = ((Entry) i).getName();
id = i.getId();
} else if (i instanceof EntryVersion) {
itemType = LinkInfo.TYPE_ENTRY_VERSION;
EntryVersion av = ((EntryVersion) i);
name = av.getParent().getName() + " (" + av.getVersionLabel() + ")";
id = i.getId();
} else if (i == null) {
itemType = LinkInfo.TYPE_NOT_FOUND;
name = l.getLinkedToPath();
} else {
throw new UnsupportedOperationException();
}
return new LinkInfo(l.getId(),
l.isAutoDetected(),
id,
name,
itemType,
recip);
}
public ExtendedEntryInfo getEntry(String entryId) throws RPCException, ItemNotFoundException {
try {
Entry a = (Entry) registry.getItemById(entryId);
return getEntryGroup(a);
} catch (RegistryException e) {
log.error(e.getMessage(), e);
throw new RPCException(e.getMessage());
} catch (NotFoundException e) {
throw new ItemNotFoundException();
} catch (AccessException e) {
throw new RPCException(e.getMessage());
}
}
public ExtendedEntryInfo getArtifactByVersionId(String artifactVersionId) throws RPCException, ItemNotFoundException {
try {
ArtifactVersion av = registry.getArtifactVersion(artifactVersionId);
return getEntryGroup(av.getParent());
} catch (RegistryException e) {
log.error(e.getMessage(), e);
throw new RPCException(e.getMessage());
} catch (NotFoundException e) {
throw new ItemNotFoundException();
} catch (AccessException e) {
throw new RPCException(e.getMessage());
}
}
private ExtendedEntryInfo getEntryGroup(Entry e) {
ExtendedEntryInfo info = new ExtendedEntryInfo();
ItemRenderer view;
if (e instanceof Artifact) {
Artifact a = (Artifact) e;
ArtifactType type = artifactTypeDao.getArtifactType(a.getContentType().toString(),
a.getDocumentType());
info.setType(type.getDescription());
info.setMediaType(type.getContentType().toString());
view = rendererManager.getArtifactRenderer(a.getDocumentType());
if (view == null) {
view = rendererManager.getArtifactRenderer(a.getContentType().toString());
}
final String context = contextPathResolver.getContextPath();
info.setArtifactLink(getLink(context + "/api/registry", a));
info.setArtifactFeedLink(getLink(context + "/api/registry", a) + ";history");
info.setCommentsFeedLink(context + "/api/comments");
} else {
view = rendererManager.getArtifactRenderer("application/octet-stream");
info.setType("Entry");
}
createBasicEntryInfo(e, view, info, true);
info.setDescription(e.getDescription());
List<WComment> wcs = info.getComments();
Workspace workspace = (Workspace) e.getParent();
List<Comment> comments = workspace.getCommentManager().getComments(e.getId());
for (Comment c : comments) {
final SimpleDateFormat dateFormat = new SimpleDateFormat(DEFAULT_DATETIME_FORMAT);
WComment wc = new WComment(c.getId(), c.getUser().getUsername(), dateFormat.format(c
.getDate().getTime()), c.getText());
wcs.add(wc);
Set<Comment> children = c.getComments();
if (children != null && children.size() > 0) {
addComments(wc, children);
}
}
List<EntryVersionInfo> versions = new ArrayList<EntryVersionInfo>();
for (EntryVersion av : e.getVersions()) {
versions.add(toWeb((EntryVersion)av, false));
}
info.setVersions(versions);
return info;
}
public EntryVersionInfo getEntryVersionInfo(String entryVersionId, boolean showHidden) throws RPCException,
ItemNotFoundException {
try {
EntryVersion ev = (EntryVersion) registry.getItemById(entryVersionId);
return toWeb(ev, showHidden);
} catch (RegistryException e) {
log.error(e.getMessage(), e);
throw new RPCException(e.getMessage());
} catch (NotFoundException e) {
throw new ItemNotFoundException();
} catch (AccessException e) {
throw new RPCException(e.getMessage());
}
}
@SuppressWarnings("unchecked")
private EntryVersionInfo toWeb(EntryVersion av, boolean showHidden) {
EntryVersionInfo vi = new EntryVersionInfo(av.getId(),
av.getVersionLabel(),
av.getCreated().getTime(),
av.isDefault(),
av.isEnabled(),
av.getAuthor().getName(),
av.getAuthor().getUsername(),
av.isIndexedPropertiesStale());
if (av instanceof ArtifactVersion) {
vi.setLink(getVersionLink((ArtifactVersion)av));
}
for (Iterator<PropertyInfo> props = av.getProperties(); props.hasNext();) {
PropertyInfo p = props.next();
if (!showHidden && !p.isVisible()) {
continue;
}
Object val = p.getInternalValue();
val = convertQNames(val);
String desc = p.getDescription();
if (desc == null) {
desc = p.getName();
}
PropertyDescriptor pd = p.getPropertyDescriptor();
String ext = pd != null && pd.getExtension() != null ? pd.getExtension().getId() : null;
vi.getProperties().add(new WProperty(p.getName(), desc, val, ext, p.isLocked()));
}
Collections.sort(vi.getProperties(), new Comparator() {
public int compare(Object o1, Object o2) {
return ((WProperty) o1).getDescription().compareTo(((WProperty) o2).getDescription());
}
});
return vi;
}
/**
* This method is here temporarily until we can serialize qnames remotely
* @param val
*/
private Object convertQNames(Object val) {
if (val instanceof Collection) {
List<String> objs = new ArrayList<String>();
for (Object o : (Collection) val) {
objs.add(o.toString());
}
return objs;
}
return val;
}
private String getLink(String base, Artifact a) {
StringBuilder sb = new StringBuilder();
Workspace w = (Workspace) a.getParent();
sb.append(base).append(w.getPath()).append(a.getName());
return sb.toString();
}
public WComment addComment(String entryId, String parentComment, String text) throws RPCException, ItemNotFoundException {
try {
Artifact artifact = registry.getArtifact(entryId);
Comment comment = new Comment();
comment.setText(text);
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
comment.setDate(cal);
comment.setUser(getCurrentUser());
Workspace w = (Workspace)artifact.getParent();
CommentManager commentManager = w.getCommentManager();
if (parentComment != null) {
Comment c = commentManager.getComment(parentComment);
if (c == null) {
throw new RPCException("Invalid parent comment");
}
comment.setParent(c);
} else {
comment.setItem(artifact);
}
commentManager.addComment(comment);
SimpleDateFormat dateFormat = new SimpleDateFormat(DEFAULT_DATETIME_FORMAT);
return new WComment(comment.getId(), comment.getUser().getUsername(), dateFormat.format(comment
.getDate().getTime()), comment.getText());
} catch (RegistryException e) {
log.error(e.getMessage(), e);
throw new RPCException(e.getMessage());
} catch (NotFoundException e) {
throw new ItemNotFoundException();
} catch (AccessException e) {
throw new RPCException(e.getMessage());
}
}
private User getCurrentUser() throws RPCException {
UserDetailsWrapper wrapper = (UserDetailsWrapper) SecurityContextHolder.getContext()
.getAuthentication().getPrincipal();
if (wrapper == null) {
throw new RPCException("No user is logged in!");
}
return wrapper.getUser();
}
private void addComments(WComment parent, Set<Comment> comments) {
for (Comment c : comments) {
SimpleDateFormat dateFormat = new SimpleDateFormat(DEFAULT_DATETIME_FORMAT);
WComment child = new WComment(c.getId(), c.getUser().getUsername(), dateFormat.format(c.getDate()
.getTime()), c.getText());
parent.getComments().add(child);
Set<Comment> children = c.getComments();
if (children != null && children.size() > 0) {
addComments(child, children);
}
}
}
public void setProperty(String entryId, String propertyName, Collection<String> propertyValue)
throws RPCException, ItemNotFoundException, WPolicyException {
setProperty(entryId, propertyName, (Object)propertyValue);
}
public void setProperty(String entryId, String propertyName, String propertyValue)
throws RPCException, ItemNotFoundException, WPolicyException {
setProperty(entryId, propertyName, (Object)propertyValue);
}
protected void setProperty(String itemId, String propertyName, Object propertyValue) throws RPCException, ItemNotFoundException, WPolicyException {
try {
Item item = registry.getItemById(itemId);
item.setInternalProperty(propertyName, propertyValue);
registry.save(item);
} catch (RegistryException e) {
log.error(e.getMessage(), e);
throw new RPCException(e.getMessage());
} catch (PropertyException e) {
// occurs if property name is formatted wrong
log.error(e.getMessage(), e);
throw new RPCException(e.getMessage());
} catch (NotFoundException e) {
throw new ItemNotFoundException();
} catch (AccessException e) {
throw new RPCException(e.getMessage());
} catch (PolicyException e) {
throw toWeb(e);
}
}
public void setProperty(Collection<String> entryIds, String propertyName, Collection<String> propertyValue)
throws RPCException, ItemNotFoundException {
}
public void setProperty(Collection<String> entryIds, String propertyName, String propertyValue)
throws RPCException, ItemNotFoundException {
}
public void setProperty(Collection<String> entryIds, String propertyName, Object propertyValue) throws RPCException, ItemNotFoundException {
}
public void deleteProperty(String itemId, String propertyName) throws RPCException, ItemNotFoundException {
try {
Item item = registry.getItemById(itemId);
item.setProperty(propertyName, null);
registry.save(item);
} catch (RegistryException e) {
log.error(e.getMessage(), e);
throw new RPCException(e.getMessage());
} catch (PropertyException e) {
// occurs if property name is formatted wrong
log.error(e.getMessage(), e);
throw new RPCException(e.getMessage());
} catch (NotFoundException e) {
throw new ItemNotFoundException();
} catch (AccessException e) {
throw new RPCException(e.getMessage());
} catch (PolicyException e) {
throw new RPCException(e.getMessage());
}
}
public void deleteProperty(Collection<String> entryIds, String propertyName) throws RPCException, ItemNotFoundException {
}
public void deletePropertyDescriptor(String id) throws RPCException {
typeManager.deletePropertyDescriptor(id);
}
public WPropertyDescriptor getPropertyDescriptor(String id) throws RPCException, ItemNotFoundException {
try {
return toWeb(typeManager.getPropertyDescriptor(id));
} catch (NotFoundException e) {
throw new ItemNotFoundException();
}
}
public List<WPropertyDescriptor> getPropertyDescriptors(boolean includeIndex) throws RPCException {
List<WPropertyDescriptor> pds = new ArrayList<WPropertyDescriptor>();
for (PropertyDescriptor pd : typeManager.getPropertyDescriptors(includeIndex)) {
pds.add(toWeb(pd));
}
return pds;
}
private WPropertyDescriptor toWeb(PropertyDescriptor pd) {
String ext = pd.getExtension() != null ? pd.getExtension().getId() : null;
return new WPropertyDescriptor(pd.getId(), pd.getProperty(), pd.getDescription(), ext, pd.isMultivalued(), pd.getConfiguration());
}
public void savePropertyDescriptor(WPropertyDescriptor wpd) throws RPCException, ItemNotFoundException, ItemExistsException {
try {
PropertyDescriptor pd;
if (wpd.getId() == null) {
pd = new PropertyDescriptor();
} else {
pd = typeManager.getPropertyDescriptor(wpd.getId());
}
pd.setProperty(wpd.getName());
pd.setDescription(wpd.getDescription());
pd.setMultivalued(wpd.isMultiValued());
pd.setConfiguration(wpd.getConfiguration());
pd.setExtension(registry.getExtension(wpd.getExtension()));
typeManager.savePropertyDescriptor(pd);
wpd.setId(pd.getId());
} catch (DuplicateItemException e) {
throw new ItemExistsException();
} catch (NotFoundException e) {
throw new RPCException(e.getMessage());
} catch (AccessException e) {
throw new RPCException(e.getMessage());
}
}
public void setDescription(String entryId, String description) throws RPCException, ItemNotFoundException {
try {
Artifact artifact = registry.getArtifact(entryId);
artifact.setDescription(description);
registry.save(artifact);
} catch (RegistryException e) {
log.error(e.getMessage(), e);
throw new RPCException(e.getMessage());
} catch (NotFoundException e) {
throw new ItemNotFoundException();
} catch (AccessException e) {
throw new RPCException(e.getMessage());
}
}
public void move(String entryId, String workspaceId, String name) throws RPCException, ItemNotFoundException {
try {
Artifact artifact = registry.getArtifact(entryId);
registry.move(artifact, workspaceId, name);
} catch (RegistryException e) {
log.error(e.getMessage(), e);
throw new RPCException(e.getMessage());
} catch (NotFoundException e) {
throw new ItemNotFoundException();
} catch (AccessException e) {
throw new RPCException(e.getMessage());
}
}
public void delete(String entryId) throws RPCException, ItemNotFoundException {
try {
Artifact artifact = registry.getArtifact(entryId);
artifact.delete();
} catch (RegistryException e) {
log.error(e.getMessage(), e);
throw new RPCException(e.getMessage());
} catch (NotFoundException e) {
throw new ItemNotFoundException();
} catch (AccessException e) {
throw new RPCException(e.getMessage());
}
}
public boolean deleteArtifactVersion(String artifactVersionId) throws RPCException, ItemNotFoundException {
try {
ArtifactVersion av = registry.getArtifactVersion(artifactVersionId);
Artifact a = (Artifact) av.getParent();
boolean last = a.getVersions().size() == 1;
av.delete();
return last;
} catch (RegistryException e) {
log.error(e.getMessage(), e);
throw new RPCException(e.getMessage());
} catch (NotFoundException e) {
throw new ItemNotFoundException();
} catch (AccessException e) {
throw new RPCException(e.getMessage());
}
}
public WGovernanceInfo getGovernanceInfo(String artifactVersionId) throws RPCException, ItemNotFoundException {
try {
ArtifactVersion artifact = registry.getArtifactVersion(artifactVersionId);
WGovernanceInfo gov = new WGovernanceInfo();
Phase phase = (Phase) artifact.getProperty(Registry.PRIMARY_LIFECYCLE);
gov.setCurrentPhase(phase.getName());
gov.setLifecycle(phase.getLifecycle().getName());
gov.setNextPhases(toWeb(phase.getNextPhases()));
gov.setPreviousPhases(toWeb(phase.getPreviousPhases()));
// Collection<PolicyInfo> policies =
// policyManager.getActivePolicies(artifact, false);
return gov;
} catch (RegistryException e) {
log.error(e.getMessage(), e);
throw new RPCException(e.getMessage());
} catch (NotFoundException e) {
throw new ItemNotFoundException();
} catch (AccessException e) {
throw new RPCException(e.getMessage());
}
}
private List<WPhase> toWeb(Set<Phase> nextPhases) {
List<WPhase> wNextPhases = new ArrayList<WPhase>();
for (Phase p : nextPhases) {
wNextPhases.add(toWeb(p));
}
return wNextPhases;
}
// TODO:
public void transition(Collection<String> entryIds, String lifecycle, String phase) throws RPCException, ItemNotFoundException {
}
public Collection<WLifecycle> getLifecycles() throws RPCException {
Collection<Lifecycle> lifecycles = localLifecycleManager.getLifecycles();
Lifecycle defaultLifecycle = localLifecycleManager.getDefaultLifecycle();
ArrayList<WLifecycle> wls = new ArrayList<WLifecycle>();
for (Lifecycle l : lifecycles) {
WLifecycle lifecycle = toWeb(l, defaultLifecycle.equals(l));
wls.add(lifecycle);
}
return wls;
}
public WLifecycle getLifecycle(String id) throws RPCException {
try {
Lifecycle defaultLifecycle = localLifecycleManager.getDefaultLifecycle();
Lifecycle l = localLifecycleManager.getLifecycleById(id);
return toWeb(l, defaultLifecycle.equals(l));
} catch (Exception e) {
throw new RPCException(e.getMessage());
}
}
private WLifecycle toWeb(Lifecycle l, boolean defaultLifecycle) {
WLifecycle lifecycle = new WLifecycle(l.getId(), l.getName(), defaultLifecycle);
List<WPhase> wphases = new ArrayList<WPhase>();
lifecycle.setPhases(wphases);
for (Phase p : l.getPhases().values()) {
WPhase wp = toWeb(p);
wphases.add(wp);
if (p.equals(l.getInitialPhase())) {
lifecycle.setInitialPhase(wp);
}
}
for (Phase p : l.getPhases().values()) {
WPhase wp = lifecycle.getPhase(p.getName());
List<WPhase> nextPhases = new ArrayList<WPhase>();
for (Phase next : p.getNextPhases()) {
WPhase wnext = lifecycle.getPhase(next.getName());
nextPhases.add(wnext);
}
wp.setNextPhases(nextPhases);
}
Collections.sort(wphases, new Comparator<WPhase>() {
public int compare(WPhase o1, WPhase o2) {
return o1.getName().compareTo(o2.getName());
}
});
return lifecycle;
}
private WPhase toWeb(Phase p) {
WPhase wp = new WPhase(p.getId(), p.getName());
return wp;
}
public Collection<String> getActivePoliciesForLifecycle(String lifecycleName, String workspaceId)
throws RPCException {
Collection<Policy> pols = null;
Lifecycle lifecycle = localLifecycleManager.getLifecycle(lifecycleName);
try {
if (workspaceId != null) {
Workspace w = (Workspace) registry.getItemById(workspaceId);
pols = policyManager.getActivePolicies(w, lifecycle);
} else {
pols = policyManager.getActivePolicies(lifecycle);
}
} catch (NotFoundException e) {
throw new RPCException(e.getMessage());
} catch (RegistryException e) {
log.error(e.getMessage(), e);
throw new RPCException(e.getMessage());
} catch (AccessException e) {
throw new RPCException(e.getMessage());
}
return getArtifactPolicyIds(pols);
}
public Collection<String> getActivePoliciesForPhase(String lifecycle, String phaseName, String workspaceId)
throws RPCException {
Collection<Policy> pols = null;
Phase phase = localLifecycleManager.getLifecycle(lifecycle).getPhase(phaseName);
try {
if (workspaceId != null) {
Workspace w = (Workspace) registry.getItemById(workspaceId);
pols = policyManager.getActivePolicies(w, phase);
} else {
pols = policyManager.getActivePolicies(phase);
}
} catch (NotFoundException e) {
throw new RPCException(e.getMessage());
} catch (RegistryException e) {
log.error(e.getMessage(), e);
throw new RPCException(e.getMessage());
} catch (AccessException e) {
throw new RPCException(e.getMessage());
}
return getArtifactPolicyIds(pols);
}
public void setActivePolicies(String workspace, String lifecycle, String phase, Collection<String> ids)
throws RPCException, WPolicyException, ItemNotFoundException {
Lifecycle l = localLifecycleManager.getLifecycle(lifecycle);
List<Policy> policies = getArtifactPolicies(ids);
try {
if (phase != null) {
Phase p = l.getPhase(phase);
if (p == null) {
throw new RPCException("Invalid phase: " + phase);
}
List<Phase> phases = Arrays.asList(p);
if (workspace == null || "".equals(workspace)) {
policyManager.setActivePolicies(phases, policies.toArray(new Policy[policies
.size()]));
} else {
Workspace w = (Workspace) registry.getItemById(workspace);
policyManager.setActivePolicies(w, phases, policies.toArray(new Policy[policies
.size()]));
}
} else {
if (workspace == null || "".equals(workspace)) {
policyManager.setActivePolicies(l, policies.toArray(new Policy[policies.size()]));
} else {
Workspace w = (Workspace) registry.getItemById(workspace);
policyManager.setActivePolicies(w, l, policies
.toArray(new Policy[policies.size()]));
}
}
} catch (RegistryException e) {
log.error(e.getMessage(), e);
throw new RPCException(e.getMessage());
} catch (PolicyException e) {
throw toWeb(e);
} catch (NotFoundException e) {
throw new ItemNotFoundException();
} catch (AccessException e) {
throw new RPCException(e.getMessage());
}
}
private WPolicyException toWeb(PolicyException e) {
Map<EntryInfo, Collection<WApprovalMessage>> failures = new HashMap<EntryInfo, Collection<WApprovalMessage>>();
for (Map.Entry<Item, List<ApprovalMessage>> entry : e.getPolicyFailures().entrySet()) {
Item i = entry.getKey();
List<ApprovalMessage> approvals = entry.getValue();
Artifact a = (Artifact) i.getParent();
ItemRenderer view = rendererManager.getArtifactRenderer(a.getDocumentType());
if (view == null) {
view = rendererManager.getArtifactRenderer(a.getContentType().toString());
}
EntryInfo info = createBasicEntryInfo(a, view);
ArrayList<WApprovalMessage> wapprovals = new ArrayList<WApprovalMessage>();
for (ApprovalMessage app : approvals) {
wapprovals.add(new WApprovalMessage(app.getMessage(), app.isWarning()));
}
failures.put(info, wapprovals);
}
WPolicyException e2 = new WPolicyException(failures);
return e2;
}
private List<Policy> getArtifactPolicies(Collection ids) {
List<Policy> policies = new ArrayList<Policy>();
for (Iterator itr = ids.iterator(); itr.hasNext();) {
String id = (String) itr.next();
Policy policy = policyManager.getPolicy(id);
policies.add(policy);
}
return policies;
}
private Collection<String> getArtifactPolicyIds(Collection<Policy> pols) {
ArrayList<String> polNames = new ArrayList<String>();
for (Policy ap : pols) {
polNames.add(ap.getId());
}
return polNames;
}
public void setDefault(String artifactVersionId) throws RPCException, ItemNotFoundException, WPolicyException {
try {
ArtifactVersion artifact = registry.getArtifactVersion(artifactVersionId);
artifact.setAsDefaultVersion();
} catch (RegistryException e) {
log.error(e.getMessage(), e);
throw new RPCException(e.getMessage());
} catch (NotFoundException e) {
throw new ItemNotFoundException();
} catch (AccessException e) {
throw new RPCException(e.getMessage());
} catch (PolicyException e) {
throw toWeb(e);
}
}
public void setEnabled(String artifactVersionId, boolean enabled) throws RPCException, ItemNotFoundException, WPolicyException {
try {
ArtifactVersion artifact = registry.getArtifactVersion(artifactVersionId);
artifact.setEnabled(enabled);
} catch (RegistryException e) {
log.error(e.getMessage(), e);
throw new RPCException(e.getMessage());
} catch (NotFoundException e) {
throw new ItemNotFoundException();
} catch (AccessException e) {
throw new RPCException(e.getMessage());
} catch (PolicyException e) {
throw toWeb(e);
}
}
public Collection<WPolicy> getPolicies() throws RPCException {
Collection<Policy> policies = policyManager.getPolicies();
List<WPolicy> gwtPolicies = new ArrayList<WPolicy>();
for (Policy p : policies) {
gwtPolicies.add(toWeb(p));
}
Collections.sort(gwtPolicies, new Comparator<WPolicy>() {
public int compare(WPolicy o1, WPolicy o2) {
return o1.getName().compareTo(o2.getName());
}
});
return gwtPolicies;
}
public void saveLifecycle(WLifecycle wl) throws RPCException, ItemExistsException {
Lifecycle l = fromWeb(wl);
try {
localLifecycleManager.save(l);
if (wl.isDefaultLifecycle()) {
Lifecycle defaultLifecycle = localLifecycleManager.getDefaultLifecycle();
if (!defaultLifecycle.equals(l)) {
localLifecycleManager.setDefaultLifecycle(l);
}
}
} catch (DuplicateItemException e) {
throw new ItemExistsException();
} catch (NotFoundException e) {
throw new RPCException(e.getMessage());
}
}
public void deleteLifecycle(String id) throws RPCException {
try {
String fallback = localLifecycleManager.getDefaultLifecycle().getId();
if (id.equals(fallback)) {
throw new RPCException("The default lifecycle cannot be deleted. Please assign " +
"another lifecycle to be the default before deleting this one.");
}
localLifecycleManager.delete(id, fallback);
} catch (NotFoundException e) {
throw new RPCException(e.getMessage());
}
}
private Lifecycle fromWeb(WLifecycle wl) throws RPCException {
Lifecycle l = new Lifecycle();
l.setPhases(new HashMap<String, Phase>());
l.setName(wl.getName());
l.setId(wl.getId());
for (Object o : wl.getPhases()) {
WPhase wp = (WPhase) o;
Phase p = new Phase(l);
p.setId(wp.getId());
p.setName(wp.getName());
l.getPhases().put(p.getName(), p);
}
for (Object o : wl.getPhases()) {
WPhase wp = (WPhase) o;
Phase p = l.getPhase(wp.getName());
p.setNextPhases(new HashSet<Phase>());
if (wp.getNextPhases() != null) {
for (Object oNext : wp.getNextPhases()) {
WPhase wNext = (WPhase) oNext;
Phase next = l.getPhase(wNext.getName());
p.getNextPhases().add(next);
}
}
}
if (wl.getInitialPhase() == null) {
throw new RPCException("You must set a phase as the initial phase.");
}
l.setInitialPhase(l.getPhase(wl.getInitialPhase().getName()));
return l;
}
private WPolicy toWeb(Policy p) {
WPolicy wap = new WPolicy();
wap.setId(p.getId());
wap.setDescription(p.getDescription());
wap.setName(p.getName());
return wap;
}
private String getVersionLink(ArtifactVersion av) {
Artifact a = (Artifact) av.getParent();
StringBuilder sb = new StringBuilder();
Workspace w = (Workspace) a.getParent();
final String context = contextPathResolver.getContextPath();
sb.append(context).append("/api/registry").append(w.getPath()).append(a.getName()).append("?version=")
.append(av.getVersionLabel());
return sb.toString();
}
public Collection<WActivity> getActivities(Date from, Date to, String user, String eventTypeStr, int start,
int results, boolean ascending) throws RPCException {
if ("All".equals(user)) {
user = null;
}
if (from != null) {
Calendar c = Calendar.getInstance();
c.setTime(from);
c.set(Calendar.HOUR, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
from = c.getTime();
}
if (to != null) {
Calendar c = Calendar.getInstance();
c.setTime(to);
c.set(Calendar.HOUR, 23);
c.set(Calendar.MINUTE, 59);
c.set(Calendar.SECOND, 59);
to = c.getTime();
}
EventType eventType = null;
if ("Info".equals(eventTypeStr)) {
eventType = EventType.INFO;
} else if ("Warning".equals(eventTypeStr)) {
eventType = EventType.WARNING;
} else if ("Error".equals(eventTypeStr)) {
eventType = EventType.ERROR;
}
try {
Collection<Activity> activities = activityManager.getActivities(from, to, user, eventType, start,
results, ascending);
ArrayList<WActivity> wactivities = new ArrayList<WActivity>();
for (Activity a : activities) {
wactivities.add(createWActivity(a));
}
return wactivities;
} catch (AccessException e) {
throw new RPCException(e.getMessage());
}
}
protected WActivity createWActivity(Activity a) {
WActivity wa = new WActivity();
wa.setId(a.getId());
wa.setEventType(a.getEventType().getText());
if (a.getUser() != null) {
wa.setUsername(a.getUser().getUsername());
wa.setName(a.getUser().getName());
}
wa.setMessage(a.getMessage());
SimpleDateFormat dateFormat = new SimpleDateFormat(DEFAULT_DATETIME_FORMAT);
wa.setDate(dateFormat.format(a.getDate().getTime()));
return wa;
}
public WUser getUserInfo() throws RPCException {
User user = getCurrentUser();
WUser w = SecurityServiceImpl.createWUser(user);
List<String> perms = new ArrayList<String>();
for (Permission p : accessControlManager.getGrantedPermissions(user)) {
perms.add(p.toString());
}
w.setPermissions(perms);
return w;
}
public void setAccessControlManager(AccessControlManager accessControlManager) {
this.accessControlManager = accessControlManager;
}
public void setRegistry(Registry registry) {
this.registry = registry;
}
public void setTypeManager(TypeManager typeManager) {
this.typeManager = typeManager;
}
public void setLifecycleManager(LifecycleManager lifecycleManager) {
this.localLifecycleManager = lifecycleManager;
}
public void setArtifactTypeDao(ArtifactTypeDao artifactTypeDao) {
this.artifactTypeDao = artifactTypeDao;
}
public void setPolicyManager(PolicyManager policyManager) {
this.policyManager = policyManager;
}
public void setRendererManager(RendererManager viewManager) {
this.rendererManager = viewManager;
}
public void setActivityManager(ActivityManager activityManager) {
this.activityManager = activityManager;
}
public void setIndexManager(IndexManager indexManager) {
this.indexManager = indexManager;
}
public void setArtifactViewManager(ArtifactViewManager artifactViewManager) {
this.artifactViewManager = artifactViewManager;
}
public void setUserManager(UserManager userManager) {
this.userManager = userManager;
}
public ContextPathResolver getContextPathResolver() {
return contextPathResolver;
}
public void setContextPathResolver(final ContextPathResolver contextPathResolver) {
this.contextPathResolver = contextPathResolver;
}
public EventManager getEventManager() {
return eventManager;
}
public void setEventManager(final EventManager eventManager) {
this.eventManager = eventManager;
}
}
| true | true | private WSearchResults getSearchResults(Set<String> artifactTypes, SearchResults results) {
Map<String, EntryGroup> name2group = new HashMap<String, EntryGroup>();
Map<String, ItemRenderer> name2view = new HashMap<String, ItemRenderer>();
int total = 0;
for (Object obj : results.getResults()) {
Entry e = (Entry) obj;
String groupName;
ArtifactType type = null;
if (e instanceof Artifact) {
type = artifactTypeDao.getArtifactType(
((Artifact) e).getContentType().toString(),
((Artifact) e).getDocumentType());
groupName = type.getDescription();
} else {
groupName = "Entries";
}
// If we want to filter based on the artifact type, filter!
if (artifactTypes != null && artifactTypes.size() != 0
&& type != null
&& !artifactTypes.contains(type.getId())) {
continue;
}
total++;
EntryGroup g = name2group.get(groupName);
ItemRenderer view = name2view.get(groupName);
if (g == null) {
g = new EntryGroup();
g.setName(groupName);
name2group.put(groupName, g);
if (e instanceof Artifact) {
Artifact a = (Artifact) e;
view = rendererManager.getArtifactRenderer(a.getDocumentType());
if (view == null) {
view = rendererManager.getArtifactRenderer(a.getContentType().toString());
}
} else {
// Hack
view = rendererManager.getArtifactRenderer("application/octet-stream");
}
name2view.put(groupName, view);
int i = 0;
for (String col : view.getColumnNames()) {
if (view.isSummary(i)) {
g.getColumns().add(col);
}
i++;
}
}
EntryInfo info = createBasicEntryInfo(e, view);
g.getRows().add(info);
}
List<EntryGroup> values = new ArrayList<EntryGroup>();
List<String> keys = new ArrayList<String>();
keys.addAll(name2group.keySet());
Collections.sort(keys);
for (String key : keys) {
values.add(name2group.get(key));
}
WSearchResults wsr = new WSearchResults();
wsr.setResults(values);
wsr.setTotal(total);
return wsr;
}
| private WSearchResults getSearchResults(Set<String> artifactTypes, SearchResults results) {
Map<String, EntryGroup> name2group = new HashMap<String, EntryGroup>();
Map<String, ItemRenderer> name2view = new HashMap<String, ItemRenderer>();
int total = 0;
for (Object obj : results.getResults()) {
Entry e = (Entry) obj;
String groupName;
ArtifactType type = null;
if (e instanceof Artifact) {
type = artifactTypeDao.getArtifactType(
((Artifact) e).getContentType().toString(),
((Artifact) e).getDocumentType());
groupName = type.getDescription();
} else {
groupName = "Entries";
}
// If we want to filter based on the artifact type, filter!
if (artifactTypes != null && artifactTypes.size() != 0
&& (type == null
|| !artifactTypes.contains(type.getId()))) {
continue;
}
total++;
EntryGroup g = name2group.get(groupName);
ItemRenderer view = name2view.get(groupName);
if (g == null) {
g = new EntryGroup();
g.setName(groupName);
name2group.put(groupName, g);
if (e instanceof Artifact) {
Artifact a = (Artifact) e;
view = rendererManager.getArtifactRenderer(a.getDocumentType());
if (view == null) {
view = rendererManager.getArtifactRenderer(a.getContentType().toString());
}
} else {
// Hack
view = rendererManager.getArtifactRenderer("application/octet-stream");
}
name2view.put(groupName, view);
int i = 0;
for (String col : view.getColumnNames()) {
if (view.isSummary(i)) {
g.getColumns().add(col);
}
i++;
}
}
EntryInfo info = createBasicEntryInfo(e, view);
g.getRows().add(info);
}
List<EntryGroup> values = new ArrayList<EntryGroup>();
List<String> keys = new ArrayList<String>();
keys.addAll(name2group.keySet());
Collections.sort(keys);
for (String key : keys) {
values.add(name2group.get(key));
}
WSearchResults wsr = new WSearchResults();
wsr.setResults(values);
wsr.setTotal(total);
return wsr;
}
|
diff --git a/src/main/java/org/geppetto/frontend/SimulationListener.java b/src/main/java/org/geppetto/frontend/SimulationListener.java
index e5aeb4699..fc2cc298d 100644
--- a/src/main/java/org/geppetto/frontend/SimulationListener.java
+++ b/src/main/java/org/geppetto/frontend/SimulationListener.java
@@ -1,427 +1,429 @@
/*******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2011, 2013 OpenWorm.
* http://openworm.org
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the MIT License
* which accompanies this distribution, and is available at
* http://opensource.org/licenses/MIT
*
* Contributors:
* OpenWorm - http://openworm.org/people.html
*
* 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.geppetto.frontend;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.CharBuffer;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.geppetto.core.common.GeppettoExecutionException;
import org.geppetto.core.common.GeppettoInitializationException;
import org.geppetto.core.simulation.ISimulation;
import org.geppetto.core.simulation.ISimulationCallbackListener;
import org.geppetto.frontend.GeppettoVisitorWebSocket.VisitorRunMode;
import org.geppetto.frontend.JSONUtility.MESSAGES_TYPES;
import org.geppetto.frontend.SimulationServerConfig.ServerBehaviorModes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;
import com.google.gson.JsonObject;
/**
* Class that handles the Web Socket connections the servlet is receiving.
*
*
* @author Jesus R. Martinez ([email protected])
*
*/
public class SimulationListener implements ISimulationCallbackListener {
private static Log logger = LogFactory.getLog(SimulationListener.class);
@Autowired
private ISimulation simulationService;
@Autowired
private SimulationServerConfig simulationServerConfig;
private final ConcurrentHashMap<Integer, GeppettoVisitorWebSocket> _connections =
new ConcurrentHashMap<Integer, GeppettoVisitorWebSocket>();
private List<GeppettoVisitorWebSocket> observers = new ArrayList<GeppettoVisitorWebSocket>();
private static SimulationListener instance = null;
protected SimulationListener(){
//Access SimulationService via spring injection of autowired dependencies
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
}
public static SimulationListener getInstance() {
if(instance == null) {
instance = new SimulationListener();
}
return instance;
}
/**
* Add new connection to list of current ones
*
* @param newVisitor - New connection to be added to current ones
*/
public void addConnection(GeppettoVisitorWebSocket newVisitor){
_connections.put(Integer.valueOf(newVisitor.getConnectionID()), newVisitor);
//Simulation is being used, notify new user controls are unavailable
if(isSimulationInUse()){
simulationControlsUnavailable(newVisitor);
}
//Simulation not in use, notify client is safe to read and load
//any simulation file embedded in url
else{
messageClient(newVisitor, MESSAGES_TYPES.READ_URL_PARAMETERS);
}
}
/**
* Remove connection from list of current ones.
*
* @param exitingVisitor - Connection to be removed
*/
public void removeConnection(GeppettoVisitorWebSocket exitingVisitor){
_connections.remove(Integer.valueOf(exitingVisitor.getConnectionID()));
//Handle operations after user closes connection
postClosingConnectionCheck(exitingVisitor);
}
/**
* Return all the current web socket connections
*
* @return
*/
public Collection<GeppettoVisitorWebSocket> getConnections()
{
return Collections.unmodifiableCollection(_connections.values());
}
/**
* Initialize simulation with URL of model to load and listener
*
* @param url - model to simulate
*/
public void initializeSimulation(String url, GeppettoVisitorWebSocket visitor){
try
{
switch(visitor.getCurrentRunMode()){
//User in control attempting to load another simulation
case CONTROLLING:
//Clear canvas of users connected for new model to be loaded
for(GeppettoVisitorWebSocket observer : getConnections()){
messageClient(observer, MESSAGES_TYPES.CLEAR_CANVAS);
}
simulationServerConfig.setIsSimulationLoaded(false);
//load another simulation
simulationService.init(new URL(url), this);
messageClient(visitor,MESSAGES_TYPES.SIMULATION_LOADED);
break;
default:
/*
* Default user can only initialize it if it's not already in use.
*
*/
if(!isSimulationInUse()){
simulationServerConfig.setServerBehaviorMode(ServerBehaviorModes.CONTROLLED);
simulationServerConfig.setIsSimulationLoaded(false);
simulationService.init(new URL(url), this);
visitor.setVisitorRunMode(VisitorRunMode.CONTROLLING);
//Simulation just got someone to control it, notify everyone else
//connected that simulation controls are unavailable.
for(GeppettoVisitorWebSocket connection : getConnections()){
if(connection != visitor){
simulationControlsUnavailable(connection);
}
}
messageClient(visitor, MESSAGES_TYPES.SIMULATION_LOADED);
}
else{
simulationControlsUnavailable(visitor);
}
break;
}
}
//Catch any Malformed URL file entered by the user.
//Send back to client a message to display to user.
catch(MalformedURLException e)
{
+ simulationServerConfig.setServerBehaviorMode(ServerBehaviorModes.OBSERVE);
messageClient(visitor,MESSAGES_TYPES.ERROR_LOADING_SIMULATION);
}
//Catch any errors happening while attempting to read simulation
catch (GeppettoInitializationException e) {
+ simulationServerConfig.setServerBehaviorMode(ServerBehaviorModes.OBSERVE);
messageClient(visitor,MESSAGES_TYPES.ERROR_LOADING_SIMULATION);
}
}
/**
* Start the simulation
*/
public void startSimulation(GeppettoVisitorWebSocket controllingUser){
try
{
simulationService.start();
//notify user simulation has started
messageClient(controllingUser,MESSAGES_TYPES.SIMULATION_STARTED);
}
catch(GeppettoExecutionException e)
{
throw new RuntimeException(e);
}
}
/**
* Pause the simulation
*/
public void pauseSimulation(){
try
{
simulationService.pause();
}
catch(GeppettoExecutionException e)
{
throw new RuntimeException(e);
}
}
/**
* Stop the running simulation
*/
public void stopSimulation(){
try
{
simulationService.stop();
}
catch(GeppettoExecutionException e)
{
throw new RuntimeException(e);
}
}
/**
* Add visitor to list users Observing simulation
*
* @param observingVisitor - Geppetto visitor joining list of simulation observers
*/
public void observeSimulation(GeppettoVisitorWebSocket observingVisitor){
observers.add(observingVisitor);
observingVisitor.setVisitorRunMode(VisitorRunMode.OBSERVING);
if(!simulationService.isRunning()){
updateScene(observingVisitor,MESSAGES_TYPES.LOAD_MODEL, getSimulationServerConfig().getLoadedScene());
}
//Notify visitor they are now in Observe Mode
messageClient(observingVisitor, MESSAGES_TYPES.OBSERVER_MODE);
}
/**
* Simulation is being controlled by another user, new visitor that just loaded Geppetto Simulation in browser
* is notified with an alert message of status of simulation.
*
* @param id - ID of new Websocket connection.
*/
public void simulationControlsUnavailable(GeppettoVisitorWebSocket visitor)
{
messageClient(visitor,MESSAGES_TYPES.SERVER_UNAVAILABLE);
}
/**
* On closing a client connection (WebSocket Connection),
* perform check to see if user leaving was the one in control
* of simulation if it was running.
*
* @param id - WebSocket ID of user closing connection
*/
public void postClosingConnectionCheck(GeppettoVisitorWebSocket exitingVisitor){
/*
* If the exiting visitor was running the simulation, notify all the observing
* visitors that the controls for the simulation became available
*/
if(exitingVisitor.getCurrentRunMode() == GeppettoVisitorWebSocket.VisitorRunMode.CONTROLLING){
//Simulation no longer in use since controlling user is leaving
simulationServerConfig.setServerBehaviorMode(ServerBehaviorModes.OBSERVE);
//Controlling user is leaving, but simulation might still be running.
try{
if(simulationService.isRunning()){
//Pause running simulation upon controlling user's exit
simulationService.stop();
}
}
catch (GeppettoExecutionException e) {
e.printStackTrace();
}
//Notify all observers
for(GeppettoVisitorWebSocket visitor : observers){
//visitor.setVisitorRunMode(VisitorRunMode.DEFAULT);
//send message to alert client of server availability
messageClient(visitor,MESSAGES_TYPES.SERVER_AVAILABLE);
}
}
/*
* Closing connection is that of a visitor in OBSERVE mode, remove the
* visitor from the list of observers.
*/
else if (exitingVisitor.getCurrentRunMode() == GeppettoVisitorWebSocket.VisitorRunMode.OBSERVING){
//User observing simulation is closing the connection
if(observers.contains(exitingVisitor)){
//Remove user from observers list
observers.remove(exitingVisitor);
}
}
}
/**
* Requests JSONUtility class for a json object with a message to send to the client
*
* @param visitor - client to receive the message
* @param type - type of message to be send
*/
public void messageClient(GeppettoVisitorWebSocket visitor, MESSAGES_TYPES type){
//Create a JSON object to be send to the client
JsonObject jsonUpdate = JSONUtility.getInstance().getJSONObject(type);
String msg = jsonUpdate.toString();
//Send the message to the client
sendMessage(visitor, msg);
}
/**
* Requests JSONUtility class for a json object with simulation update to
* be send to the client
*
* @param visitor - Client to receive the simulation update
* @param type - Type of udpate to be send
* @param update - update to be send
*/
private void updateScene(GeppettoVisitorWebSocket visitor, MESSAGES_TYPES type, String update){
JsonObject jsonUpdate = JSONUtility.getInstance().getJSONObject(type, update);
String msg = jsonUpdate.toString();
sendMessage(visitor, msg);
}
/**
* Sends a message to a specific user. The id of the
* WebSocket connection is used to contact the desired user.
*
* @param id - ID of WebSocket connection that will be sent a message
* @param msg - The message the user will be receiving
*/
public void sendMessage(GeppettoVisitorWebSocket visitor, String msg){
try
{
CharBuffer buffer = CharBuffer.wrap(msg);
visitor.getWsOutbound().writeTextMessage(buffer);
}
catch (IOException ignore)
{
logger.error("Unable to communicate with client " + ignore.getMessage());
}
}
/**
* Returns status of server simulation used
*
* @return
*/
public boolean isSimulationInUse(){
if(simulationServerConfig.getServerBehaviorMode() == ServerBehaviorModes.CONTROLLED){
return true;
}
return false;
}
public SimulationServerConfig getSimulationServerConfig() {
return simulationServerConfig;
}
/**
* Receives update from simulation when there are new ones.
* From here the updates are send to the connected clients
*
*/
@Override
public void updateReady(String update) {
long start=System.currentTimeMillis();
Date date = new Date(start);
DateFormat formatter = new SimpleDateFormat("HH:mm:ss:SSS");
String dateFormatted = formatter.format(date);
logger.info("Simulation Frontend Update Starting: "+dateFormatted);
MESSAGES_TYPES action = MESSAGES_TYPES.SCENE_UPDATE;
/*
* Simulation is running but model has not yet been loaded.
*/
if(!getSimulationServerConfig().isSimulationLoaded()){
action = MESSAGES_TYPES.LOAD_MODEL;
getSimulationServerConfig().setIsSimulationLoaded(true);
}
for (GeppettoVisitorWebSocket connection : getConnections())
{
//Notify all connected clients about update either to load model or update current one.
updateScene(connection, action , update);
}
getSimulationServerConfig().setLoadedScene(update);
logger.info("Simulation Frontend Update Finished: Took:"+(System.currentTimeMillis()-start));
}
}
| false | true | public void initializeSimulation(String url, GeppettoVisitorWebSocket visitor){
try
{
switch(visitor.getCurrentRunMode()){
//User in control attempting to load another simulation
case CONTROLLING:
//Clear canvas of users connected for new model to be loaded
for(GeppettoVisitorWebSocket observer : getConnections()){
messageClient(observer, MESSAGES_TYPES.CLEAR_CANVAS);
}
simulationServerConfig.setIsSimulationLoaded(false);
//load another simulation
simulationService.init(new URL(url), this);
messageClient(visitor,MESSAGES_TYPES.SIMULATION_LOADED);
break;
default:
/*
* Default user can only initialize it if it's not already in use.
*
*/
if(!isSimulationInUse()){
simulationServerConfig.setServerBehaviorMode(ServerBehaviorModes.CONTROLLED);
simulationServerConfig.setIsSimulationLoaded(false);
simulationService.init(new URL(url), this);
visitor.setVisitorRunMode(VisitorRunMode.CONTROLLING);
//Simulation just got someone to control it, notify everyone else
//connected that simulation controls are unavailable.
for(GeppettoVisitorWebSocket connection : getConnections()){
if(connection != visitor){
simulationControlsUnavailable(connection);
}
}
messageClient(visitor, MESSAGES_TYPES.SIMULATION_LOADED);
}
else{
simulationControlsUnavailable(visitor);
}
break;
}
}
//Catch any Malformed URL file entered by the user.
//Send back to client a message to display to user.
catch(MalformedURLException e)
{
messageClient(visitor,MESSAGES_TYPES.ERROR_LOADING_SIMULATION);
}
//Catch any errors happening while attempting to read simulation
catch (GeppettoInitializationException e) {
messageClient(visitor,MESSAGES_TYPES.ERROR_LOADING_SIMULATION);
}
}
| public void initializeSimulation(String url, GeppettoVisitorWebSocket visitor){
try
{
switch(visitor.getCurrentRunMode()){
//User in control attempting to load another simulation
case CONTROLLING:
//Clear canvas of users connected for new model to be loaded
for(GeppettoVisitorWebSocket observer : getConnections()){
messageClient(observer, MESSAGES_TYPES.CLEAR_CANVAS);
}
simulationServerConfig.setIsSimulationLoaded(false);
//load another simulation
simulationService.init(new URL(url), this);
messageClient(visitor,MESSAGES_TYPES.SIMULATION_LOADED);
break;
default:
/*
* Default user can only initialize it if it's not already in use.
*
*/
if(!isSimulationInUse()){
simulationServerConfig.setServerBehaviorMode(ServerBehaviorModes.CONTROLLED);
simulationServerConfig.setIsSimulationLoaded(false);
simulationService.init(new URL(url), this);
visitor.setVisitorRunMode(VisitorRunMode.CONTROLLING);
//Simulation just got someone to control it, notify everyone else
//connected that simulation controls are unavailable.
for(GeppettoVisitorWebSocket connection : getConnections()){
if(connection != visitor){
simulationControlsUnavailable(connection);
}
}
messageClient(visitor, MESSAGES_TYPES.SIMULATION_LOADED);
}
else{
simulationControlsUnavailable(visitor);
}
break;
}
}
//Catch any Malformed URL file entered by the user.
//Send back to client a message to display to user.
catch(MalformedURLException e)
{
simulationServerConfig.setServerBehaviorMode(ServerBehaviorModes.OBSERVE);
messageClient(visitor,MESSAGES_TYPES.ERROR_LOADING_SIMULATION);
}
//Catch any errors happening while attempting to read simulation
catch (GeppettoInitializationException e) {
simulationServerConfig.setServerBehaviorMode(ServerBehaviorModes.OBSERVE);
messageClient(visitor,MESSAGES_TYPES.ERROR_LOADING_SIMULATION);
}
}
|
diff --git a/src/com/android/contacts/model/RawContact.java b/src/com/android/contacts/model/RawContact.java
index 3a193b4db..d8841983d 100644
--- a/src/com/android/contacts/model/RawContact.java
+++ b/src/com/android/contacts/model/RawContact.java
@@ -1,261 +1,262 @@
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.contacts.model;
import android.content.ContentValues;
import android.content.Context;
import android.content.Entity;
import android.net.Uri;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.RawContacts;
import com.android.contacts.model.account.AccountType;
import com.android.contacts.model.account.AccountWithDataSet;
import com.android.contacts.model.dataitem.DataItem;
import java.util.ArrayList;
import java.util.List;
/**
* RawContact represents a single raw contact in the raw contacts database.
* It has specialized getters/setters for raw contact
* items, and also contains a collection of DataItem objects. A RawContact contains the information
* from a single account.
*
* This allows RawContact objects to be thought of as a class with raw contact
* fields (like account type, name, data set, sync state, etc.) and a list of
* DataItem objects that represent contact information elements (like phone
* numbers, email, address, etc.).
*/
public class RawContact {
private final Context mContext;
private AccountTypeManager mAccountTypeManager;
private final ContentValues mValues;
private final ArrayList<NamedDataItem> mDataItems;
public static class NamedDataItem {
public final Uri uri;
public final DataItem dataItem;
public NamedDataItem(Uri uri, DataItem dataItem) {
this.uri = uri;
this.dataItem = dataItem;
}
}
public static RawContact createFrom(Entity entity) {
final ContentValues values = entity.getEntityValues();
final ArrayList<Entity.NamedContentValues> subValues = entity.getSubValues();
RawContact rawContact = new RawContact(null, values);
for (Entity.NamedContentValues subValue : subValues) {
rawContact.addNamedDataItemValues(subValue.uri, subValue.values);
}
return rawContact;
}
/**
* A RawContact object can be created with or without a context.
*
* The context is used for the buildString() member function in DataItem objects,
* specifically for retrieving an instance of AccountTypeManager. It is okay to
* pass in null for the context in which case, you will not be able to call buildString(),
* getDataKind(), or getAccountType() from a DataItem object.
*/
public RawContact(Context context) {
this(context, new ContentValues());
}
public RawContact(Context context, ContentValues values) {
mContext = context;
mValues = values;
mDataItems = new ArrayList<NamedDataItem>();
}
public AccountTypeManager getAccountTypeManager() {
if (mAccountTypeManager == null) {
mAccountTypeManager = AccountTypeManager.getInstance(mContext);
}
return mAccountTypeManager;
}
public Context getContext() {
return mContext;
}
public ContentValues getValues() {
return mValues;
}
/**
* Returns the id of the raw contact.
*/
public Long getId() {
return getValues().getAsLong(RawContacts._ID);
}
/**
* Returns the account name of the raw contact.
*/
public String getAccountName() {
return getValues().getAsString(RawContacts.ACCOUNT_NAME);
}
/**
* Returns the account type of the raw contact.
*/
public String getAccountTypeString() {
return getValues().getAsString(RawContacts.ACCOUNT_TYPE);
}
/**
* Returns the data set of the raw contact.
*/
public String getDataSet() {
return getValues().getAsString(RawContacts.DATA_SET);
}
/**
* Returns the account type and data set of the raw contact.
*/
public String getAccountTypeAndDataSetString() {
return getValues().getAsString(RawContacts.ACCOUNT_TYPE_AND_DATA_SET);
}
public boolean isDirty() {
return getValues().getAsBoolean(RawContacts.DIRTY);
}
public long getVersion() {
return getValues().getAsLong(RawContacts.DIRTY);
}
public String getSourceId() {
return getValues().getAsString(RawContacts.SOURCE_ID);
}
public String getSync1() {
return getValues().getAsString(RawContacts.SYNC1);
}
public String getSync2() {
return getValues().getAsString(RawContacts.SYNC2);
}
public String getSync3() {
return getValues().getAsString(RawContacts.SYNC3);
}
public String getSync4() {
return getValues().getAsString(RawContacts.SYNC4);
}
public boolean isDeleted() {
return getValues().getAsBoolean(RawContacts.DELETED);
}
public boolean isNameVerified() {
return getValues().getAsBoolean(RawContacts.NAME_VERIFIED);
}
public long getContactId() {
return getValues().getAsLong(Contacts.Entity.CONTACT_ID);
}
public boolean isStarred() {
return getValues().getAsBoolean(Contacts.STARRED);
}
public AccountType getAccountType() {
return getAccountTypeManager().getAccountType(getAccountTypeString(), getDataSet());
}
/**
* Sets the account name, account type, and data set strings.
* Valid combinations for account-name, account-type, data-set
* 1) null, null, null (local account)
* 2) non-null, non-null, null (valid account without data-set)
* 3) non-null, non-null, non-null (valid account with data-set)
*/
private void setAccount(String accountName, String accountType, String dataSet) {
final ContentValues values = getValues();
if (accountName == null) {
if (accountType == null && dataSet == null) {
// This is a local account
values.putNull(RawContacts.ACCOUNT_NAME);
values.putNull(RawContacts.ACCOUNT_TYPE);
values.putNull(RawContacts.DATA_SET);
return;
}
} else {
if (accountType != null) {
// This is a valid account, either with or without a dataSet.
values.put(RawContacts.ACCOUNT_NAME, accountName);
values.put(RawContacts.ACCOUNT_TYPE, accountType);
if (dataSet == null) {
values.putNull(RawContacts.DATA_SET);
} else {
values.put(RawContacts.DATA_SET, dataSet);
}
+ return;
}
}
throw new IllegalArgumentException(
"Not a valid combination of account name, type, and data set.");
}
public void setAccount(AccountWithDataSet accountWithDataSet) {
setAccount(accountWithDataSet.name, accountWithDataSet.type, accountWithDataSet.dataSet);
}
public void setAccountToLocal() {
setAccount(null, null, null);
}
public void addDataItemValues(ContentValues values) {
addNamedDataItemValues(Data.CONTENT_URI, values);
}
public void addNamedDataItemValues(Uri uri, ContentValues values) {
mDataItems.add(new NamedDataItem(uri, DataItem.createFrom(this, values)));
}
public List<DataItem> getDataItems() {
final ArrayList<DataItem> list = new ArrayList<DataItem>();
for (NamedDataItem dataItem : mDataItems) {
if (Data.CONTENT_URI.equals(dataItem.uri)) {
list.add(dataItem.dataItem);
}
}
return list;
}
public List<NamedDataItem> getNamedDataItems() {
return mDataItems;
}
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("RawContact: ").append(mValues);
for (RawContact.NamedDataItem namedDataItem : mDataItems) {
sb.append("\n ").append(namedDataItem.uri);
sb.append("\n -> ").append(namedDataItem.dataItem.getContentValues());
}
return sb.toString();
}
}
| true | true | private void setAccount(String accountName, String accountType, String dataSet) {
final ContentValues values = getValues();
if (accountName == null) {
if (accountType == null && dataSet == null) {
// This is a local account
values.putNull(RawContacts.ACCOUNT_NAME);
values.putNull(RawContacts.ACCOUNT_TYPE);
values.putNull(RawContacts.DATA_SET);
return;
}
} else {
if (accountType != null) {
// This is a valid account, either with or without a dataSet.
values.put(RawContacts.ACCOUNT_NAME, accountName);
values.put(RawContacts.ACCOUNT_TYPE, accountType);
if (dataSet == null) {
values.putNull(RawContacts.DATA_SET);
} else {
values.put(RawContacts.DATA_SET, dataSet);
}
}
}
throw new IllegalArgumentException(
"Not a valid combination of account name, type, and data set.");
}
| private void setAccount(String accountName, String accountType, String dataSet) {
final ContentValues values = getValues();
if (accountName == null) {
if (accountType == null && dataSet == null) {
// This is a local account
values.putNull(RawContacts.ACCOUNT_NAME);
values.putNull(RawContacts.ACCOUNT_TYPE);
values.putNull(RawContacts.DATA_SET);
return;
}
} else {
if (accountType != null) {
// This is a valid account, either with or without a dataSet.
values.put(RawContacts.ACCOUNT_NAME, accountName);
values.put(RawContacts.ACCOUNT_TYPE, accountType);
if (dataSet == null) {
values.putNull(RawContacts.DATA_SET);
} else {
values.put(RawContacts.DATA_SET, dataSet);
}
return;
}
}
throw new IllegalArgumentException(
"Not a valid combination of account name, type, and data set.");
}
|
diff --git a/lucene/core/src/test/org/apache/lucene/util/TestPagedBytes.java b/lucene/core/src/test/org/apache/lucene/util/TestPagedBytes.java
index 4becc30d1..f858c5142 100644
--- a/lucene/core/src/test/org/apache/lucene/util/TestPagedBytes.java
+++ b/lucene/core/src/test/org/apache/lucene/util/TestPagedBytes.java
@@ -1,134 +1,134 @@
/*
* 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.lucene.util;
import java.util.*;
import org.apache.lucene.store.DataInput;
import org.apache.lucene.store.DataOutput;
public class TestPagedBytes extends LuceneTestCase {
public void testDataInputOutput() throws Exception {
Random random = random();
for(int iter=0;iter<5*RANDOM_MULTIPLIER;iter++) {
final int blockBits = _TestUtil.nextInt(random, 1, 20);
final int blockSize = 1 << blockBits;
final PagedBytes p = new PagedBytes(blockBits);
final DataOutput out = p.getDataOutput();
- final int numBytes = random().nextInt(10000000);
+ final int numBytes = _TestUtil.nextInt(random(), 2, 10000000);
final byte[] answer = new byte[numBytes];
random().nextBytes(answer);
int written = 0;
while(written < numBytes) {
if (random().nextInt(10) == 7) {
out.writeByte(answer[written++]);
} else {
int chunk = Math.min(random().nextInt(1000), numBytes - written);
out.writeBytes(answer, written, chunk);
written += chunk;
}
}
final PagedBytes.Reader reader = p.freeze(random.nextBoolean());
final DataInput in = p.getDataInput();
final byte[] verify = new byte[numBytes];
int read = 0;
while(read < numBytes) {
if (random().nextInt(10) == 7) {
verify[read++] = in.readByte();
} else {
int chunk = Math.min(random().nextInt(1000), numBytes - read);
in.readBytes(verify, read, chunk);
read += chunk;
}
}
assertTrue(Arrays.equals(answer, verify));
final BytesRef slice = new BytesRef();
for(int iter2=0;iter2<100;iter2++) {
final int pos = random.nextInt(numBytes-1);
final int len = random.nextInt(Math.min(blockSize+1, numBytes - pos));
reader.fillSlice(slice, pos, len);
for(int byteUpto=0;byteUpto<len;byteUpto++) {
assertEquals(answer[pos + byteUpto], slice.bytes[slice.offset + byteUpto]);
}
}
}
}
public void testLengthPrefix() throws Exception {
Random random = random();
for(int iter=0;iter<5*RANDOM_MULTIPLIER;iter++) {
final int blockBits = _TestUtil.nextInt(random, 2, 20);
final int blockSize = 1 << blockBits;
final PagedBytes p = new PagedBytes(blockBits);
final List<Integer> addresses = new ArrayList<Integer>();
final List<BytesRef> answers = new ArrayList<BytesRef>();
int totBytes = 0;
while(totBytes < 10000000 && answers.size() < 100000) {
final int len = random.nextInt(Math.min(blockSize-2, 32768));
final BytesRef b = new BytesRef();
b.bytes = new byte[len];
b.length = len;
b.offset = 0;
random.nextBytes(b.bytes);
answers.add(b);
addresses.add((int) p.copyUsingLengthPrefix(b));
totBytes += len;
}
final PagedBytes.Reader reader = p.freeze(random.nextBoolean());
final BytesRef slice = new BytesRef();
for(int idx=0;idx<answers.size();idx++) {
reader.fillSliceWithPrefix(slice, addresses.get(idx));
assertEquals(answers.get(idx), slice);
}
}
}
// LUCENE-3841: even though
// copyUsingLengthPrefix will never span two blocks, make
// sure if caller writes their own prefix followed by the
// bytes, it still works:
public void testLengthPrefixAcrossTwoBlocks() throws Exception {
Random random = random();
final PagedBytes p = new PagedBytes(10);
final DataOutput out = p.getDataOutput();
final byte[] bytes1 = new byte[1000];
random.nextBytes(bytes1);
out.writeBytes(bytes1, 0, bytes1.length);
out.writeByte((byte) 40);
final byte[] bytes2 = new byte[40];
random.nextBytes(bytes2);
out.writeBytes(bytes2, 0, bytes2.length);
final PagedBytes.Reader reader = p.freeze(random.nextBoolean());
BytesRef answer = reader.fillSliceWithPrefix(new BytesRef(), 1000);
assertEquals(40, answer.length);
for(int i=0;i<40;i++) {
assertEquals(bytes2[i], answer.bytes[answer.offset + i]);
}
}
}
| true | true | public void testDataInputOutput() throws Exception {
Random random = random();
for(int iter=0;iter<5*RANDOM_MULTIPLIER;iter++) {
final int blockBits = _TestUtil.nextInt(random, 1, 20);
final int blockSize = 1 << blockBits;
final PagedBytes p = new PagedBytes(blockBits);
final DataOutput out = p.getDataOutput();
final int numBytes = random().nextInt(10000000);
final byte[] answer = new byte[numBytes];
random().nextBytes(answer);
int written = 0;
while(written < numBytes) {
if (random().nextInt(10) == 7) {
out.writeByte(answer[written++]);
} else {
int chunk = Math.min(random().nextInt(1000), numBytes - written);
out.writeBytes(answer, written, chunk);
written += chunk;
}
}
final PagedBytes.Reader reader = p.freeze(random.nextBoolean());
final DataInput in = p.getDataInput();
final byte[] verify = new byte[numBytes];
int read = 0;
while(read < numBytes) {
if (random().nextInt(10) == 7) {
verify[read++] = in.readByte();
} else {
int chunk = Math.min(random().nextInt(1000), numBytes - read);
in.readBytes(verify, read, chunk);
read += chunk;
}
}
assertTrue(Arrays.equals(answer, verify));
final BytesRef slice = new BytesRef();
for(int iter2=0;iter2<100;iter2++) {
final int pos = random.nextInt(numBytes-1);
final int len = random.nextInt(Math.min(blockSize+1, numBytes - pos));
reader.fillSlice(slice, pos, len);
for(int byteUpto=0;byteUpto<len;byteUpto++) {
assertEquals(answer[pos + byteUpto], slice.bytes[slice.offset + byteUpto]);
}
}
}
}
| public void testDataInputOutput() throws Exception {
Random random = random();
for(int iter=0;iter<5*RANDOM_MULTIPLIER;iter++) {
final int blockBits = _TestUtil.nextInt(random, 1, 20);
final int blockSize = 1 << blockBits;
final PagedBytes p = new PagedBytes(blockBits);
final DataOutput out = p.getDataOutput();
final int numBytes = _TestUtil.nextInt(random(), 2, 10000000);
final byte[] answer = new byte[numBytes];
random().nextBytes(answer);
int written = 0;
while(written < numBytes) {
if (random().nextInt(10) == 7) {
out.writeByte(answer[written++]);
} else {
int chunk = Math.min(random().nextInt(1000), numBytes - written);
out.writeBytes(answer, written, chunk);
written += chunk;
}
}
final PagedBytes.Reader reader = p.freeze(random.nextBoolean());
final DataInput in = p.getDataInput();
final byte[] verify = new byte[numBytes];
int read = 0;
while(read < numBytes) {
if (random().nextInt(10) == 7) {
verify[read++] = in.readByte();
} else {
int chunk = Math.min(random().nextInt(1000), numBytes - read);
in.readBytes(verify, read, chunk);
read += chunk;
}
}
assertTrue(Arrays.equals(answer, verify));
final BytesRef slice = new BytesRef();
for(int iter2=0;iter2<100;iter2++) {
final int pos = random.nextInt(numBytes-1);
final int len = random.nextInt(Math.min(blockSize+1, numBytes - pos));
reader.fillSlice(slice, pos, len);
for(int byteUpto=0;byteUpto<len;byteUpto++) {
assertEquals(answer[pos + byteUpto], slice.bytes[slice.offset + byteUpto]);
}
}
}
}
|
diff --git a/web/src/main/java/org/fao/geonet/kernel/mef/Importer.java b/web/src/main/java/org/fao/geonet/kernel/mef/Importer.java
index 11d730e437..8842443f78 100644
--- a/web/src/main/java/org/fao/geonet/kernel/mef/Importer.java
+++ b/web/src/main/java/org/fao/geonet/kernel/mef/Importer.java
@@ -1,569 +1,569 @@
//=============================================================================
//=== 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.mef;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import jeeves.exceptions.BadFormatEx;
import jeeves.resources.dbms.Dbms;
import jeeves.server.context.ServiceContext;
import jeeves.utils.BinaryFile;
import jeeves.utils.Log;
import jeeves.utils.Util;
import jeeves.utils.Xml;
import org.fao.geonet.GeonetContext;
import org.fao.geonet.constants.Geonet;
import org.fao.geonet.constants.Params;
import org.fao.geonet.kernel.DataManager;
import org.fao.geonet.lib.Lib;
import org.fao.geonet.util.ISODate;
import org.fao.oaipmh.exceptions.BadArgumentException;
import org.jdom.Element;
public class Importer {
public static List<String> doImport(final Element params,
final ServiceContext context, File mefFile, final String stylePath)
throws Exception {
return doImport(params, context, mefFile, stylePath, false);
}
public static List<String> doImport(final Element params,
final ServiceContext context, File mefFile, final String stylePath,
final boolean indexGroup) throws Exception {
final GeonetContext gc = (GeonetContext) context
.getHandlerContext(Geonet.CONTEXT_NAME);
final DataManager dm = gc.getDataManager();
// Load preferred schema and set to iso19139 by default
final String preferredSchema = (gc.getHandlerConfig()
.getMandatoryValue("preferredSchema") != null ? gc
.getHandlerConfig().getMandatoryValue("preferredSchema")
: "iso19139");
final Dbms dbms = (Dbms) context.getResourceManager().open(
Geonet.Res.MAIN_DB);
final List<String> id = new ArrayList<String>();
final List<Element> md = new ArrayList<Element>();
final List<Element> fc = new ArrayList<Element>();
// Try to define MEF version from mef file not from parameter
String fileType = Util.getParam(params, "file_type", "mef");
if (fileType.equals("mef")) {
MEFLib.Version version = MEFLib.getMEFVersion(mefFile);
if (version.equals(MEFLib.Version.V2))
fileType = "mef2";
}
IVisitor visitor = null;
if (fileType.equals("single"))
visitor = new XmlVisitor();
else if (fileType.equals("mef"))
visitor = new MEFVisitor();
else if (fileType.equals("mef2"))
visitor = new MEF2Visitor();
else
throw new BadArgumentException("Bad file type parameter.");
// --- import metadata from MEF, Xml, ZIP files
MEFLib.visit(mefFile, visitor, new IMEFVisitor() {
public void handleMetadata(Element metadata, int index)
throws Exception {
Log.debug(Geonet.MEF, "Collecting metadata:\n"
+ Xml.getString(metadata));
md.add(index, metadata);
}
public void handleMetadataFiles(File[] Files, int index)
throws Exception {
Log.debug(Geonet.MEF, "Multiple metadata files");
Element metadataValidForImport = null;
for (int i = 0; i < Files.length; i++) {
File file = Files[i];
if (file != null && !file.isDirectory()) {
Element metadata = Xml.loadFile(file);
String metadataSchema = dm.autodetectSchema(metadata);
// If local node doesn't know metadata
// schema try to load next xml file.
if (metadataSchema == null)
continue;
// If schema is preferred local node schema
// load that file.
if (metadataSchema.equals(preferredSchema)) {
Log.debug(Geonet.MEF, "Found metadata file "
+ file.getName()
+ " with preferred schema ("
+ preferredSchema + ").");
handleMetadata(metadata, index);
return;
} else {
Log.debug(Geonet.MEF, "Found metadata file "
+ file.getName() + " with known schema ("
+ metadataSchema + ").");
metadataValidForImport = metadata;
}
}
}
// Import a valid metadata if not one found
// with preferred schema.
if (metadataValidForImport != null) {
Log
.debug(Geonet.MEF,
"Importing metadata with valide schema but not preferred one.");
handleMetadata(metadataValidForImport, index);
return;
} else
throw new BadFormatEx("No valid metadata file found.");
}
// --------------------------------------------------------------------
public void handleFeatureCat(Element featureCat, int index)
throws Exception {
if (featureCat != null) {
Log.debug(Geonet.MEF, "Collecting feature catalog:\n"
+ Xml.getString(featureCat));
}
fc.add(index, featureCat);
}
// --------------------------------------------------------------------
/**
* Record is not a template by default. No category attached to
* record by default. No stylesheet used by default. If no site
* identifier provided, use current node id by default. No
* validation by default.
*
* If record is a template and not a MEF file always generate a new
* UUID.
*/
public void handleInfo(Element info, int index) throws Exception {
String FS = File.separator;
String uuid = null;
String createDate = null;
String changeDate = null;
String source = null;
String sourceName = null;
// Schema in info.xml is not used anymore.
// as we use autodetect schema to define
// metadata schema.
// String schema = null;
String isTemplate = null;
String localId = null;
String rating = null;
String popularity = null;
String groupId = null;
Element categs = null;
Element privileges = null;
boolean validate = false;
Element metadata = md.get(index);
String schema = dm.autodetectSchema(metadata);
if (schema == null)
throw new Exception("Unknown schema format : " + schema);
// Handle non MEF files insertion
if (info.getChildren().size() == 0) {
source = Util.getParam(params, Params.SITE_ID, gc
.getSiteId());
isTemplate = Util.getParam(params, Params.TEMPLATE, "n");
String category = Util
.getParam(params, Params.CATEGORY, "");
if (!category.equals("")) {
categs = new Element("categories");
categs.addContent((new Element("category"))
.setAttribute("name", category));
}
groupId = Util.getParam(params, Params.GROUP);
privileges = new Element("group");
privileges.addContent(new Element("operation")
.setAttribute("name", "view"));
privileges.addContent(new Element("operation")
.setAttribute("name", "editing"));
privileges.addContent(new Element("operation")
.setAttribute("name", "download"));
privileges.addContent(new Element("operation")
.setAttribute("name", "notify"));
privileges.addContent(new Element("operation")
.setAttribute("name", "dynamic"));
privileges.addContent(new Element("operation")
.setAttribute("name", "featured"));
String style = Util.getParam(params, Params.STYLESHEET,
"_none_");
// Apply a stylesheet transformation if requested
if (!style.equals("_none_"))
md.add(index, Xml.transform(md.get(index), stylePath
+ FS + style));
// Get the Metadata uuid if it's not a template.
if (isTemplate.equals("n"))
uuid = dm.extractUUID(schema, md.get(index));
validate = Util.getParam(params, Params.VALIDATE, "off")
.equals("on");
} else {
categs = info.getChild("categories");
privileges = info.getChild("privileges");
Element general = info.getChild("general");
uuid = general.getChildText("uuid");
createDate = general.getChildText("createDate");
changeDate = general.getChildText("changeDate");
source = general.getChildText("siteId");
sourceName = general.getChildText("siteName");
localId = general.getChildText("localId");
isTemplate = general.getChildText("isTemplate").equals(
"true") ? "y" : "n";
rating = general.getChildText("rating");
popularity = general.getChildText("popularity");
}
if (validate)
dm.validate(schema, metadata);
String uuidAction = Util.getParam(params, Params.UUID_ACTION,
Params.NOTHING);
importRecord(uuid, localId, uuidAction, md, schema, index,
source, sourceName, context, id, createDate,
changeDate, groupId, isTemplate);
if (fc.size() != 0 && fc.get(index) != null) {
// UUID is set as @uuid in root element
uuid = UUID.randomUUID().toString();
fc.add(index, dm.setUUID("iso19110", uuid, fc.get(index)));
String fcId = dm.insertMetadataExt(dbms, "iso19110", fc
.get(index), context.getSerialFactory(), source,
createDate, changeDate, uuid, context
.getUserSession().getUserIdAsInt(), null);
Log.debug(Geonet.MEF, "Adding Feature catalog with uuid: "
+ uuid);
// Create database relation between metadata and feature
// catalog
String mdId = id.get(index);
String query = "INSERT INTO Relations (id, relatedId) VALUES (?, ?)";
- dbms.execute(query, mdId, fcId);
+ dbms.execute(query, Integer.parseInt(mdId), Integer.parseInt(fcId));
id.add(fcId);
// TODO : privileges not handled for feature
// catalog ...
}
int iId = Integer.parseInt(id.get(index));
if (rating != null)
dbms.execute("UPDATE Metadata SET rating=? WHERE id=?",
new Integer(rating), iId);
if (popularity != null)
dbms.execute("UPDATE Metadata SET popularity=? WHERE id=?",
new Integer(popularity), iId);
dm.setTemplateExt(dbms, iId, isTemplate, null);
dm.setHarvestedExt(dbms, iId, null);
String pubDir = Lib.resource.getDir(context, "public", id
.get(index));
String priDir = Lib.resource.getDir(context, "private", id
.get(index));
new File(pubDir).mkdirs();
new File(priDir).mkdirs();
if (categs != null)
addCategories(dm, dbms, id.get(index), categs);
if (groupId == null)
addPrivileges(dm, dbms, id.get(index), privileges);
else
addOperations(dm, dbms, privileges, id.get(index), groupId);
if (indexGroup) {
dm.indexMetadataGroup(dbms, id.get(index));
} else {
dm.indexMetadata(dbms, id.get(index));
}
}
// --------------------------------------------------------------------
public void handlePublicFile(String file, String changeDate,
InputStream is, int index) throws IOException {
Log.debug(Geonet.MEF, "Adding public file with name=" + file);
saveFile(context, id.get(index), "public", file, changeDate, is);
}
// --------------------------------------------------------------------
public void handlePrivateFile(String file, String changeDate,
InputStream is, int index) throws IOException {
Log.debug(Geonet.MEF, "Adding private file with name=" + file);
saveFile(context, id.get(index), "private", file, changeDate,
is);
}
});
return id;
}
public static void importRecord(String uuid, String localId,
String uuidAction, List<Element> md, String schema, int index,
String source, String sourceName, ServiceContext context,
List<String> id, String createDate, String changeDate,
String groupId, String isTemplate) throws Exception {
GeonetContext gc = (GeonetContext) context
.getHandlerContext(Geonet.CONTEXT_NAME);
DataManager dm = gc.getDataManager();
Dbms dbms = (Dbms) context.getResourceManager()
.open(Geonet.Res.MAIN_DB);
if (uuid == null || uuid.equals("")
|| uuidAction.equals(Params.GENERATE_UUID)) {
String newuuid = UUID.randomUUID().toString();
source = null;
Log
.debug(Geonet.MEF, "Replacing UUID " + uuid + " with "
+ newuuid);
uuid = newuuid;
// --- set uuid inside metadata
md.add(index, dm.setUUID(schema, uuid, md.get(index)));
} else {
if (sourceName == null)
sourceName = "???";
if (source == null || source.trim().length() == 0)
throw new Exception(
"Missing siteId parameter from info.xml file");
Lib.sources.update(dbms, source, sourceName, true);
}
try {
if (dm.existsMetadataUuid(dbms, uuid)
&& !uuidAction.equals(Params.NOTHING)) {
dm.deleteMetadata(dbms, dm.getMetadataId(dbms, uuid));
Log.debug(Geonet.MEF, "Deleting existing metadata with UUID : "
+ uuid);
}
} catch (Exception e) {
throw new Exception(
" Existing metadata with same UUID could not be deleted.");
}
Log.debug(Geonet.MEF, "Adding metadata with uuid:" + uuid);
// Try to insert record with localId provided, if not use a new id.
boolean insertedWithLocalId = false;
if (localId != null && !localId.equals("")) {
try {
int iLocalId = Integer.parseInt(localId);
// Use the same id to insert the metadata record.
// This is an optional element. If present, indicates the
// id used locally by the sourceId actor to store the metadata. Its
// purpose is just to allow the reuse of the same local id when
// reimporting a metadata.
if (!dm.existsMetadata(dbms, iLocalId)) {
Log.debug(Geonet.MEF, "Using given localId: " + localId);
id.add(index, dm.insertMetadataExt(dbms, schema, md.get(index),
iLocalId, source, createDate, changeDate, uuid, context
.getUserSession().getUserIdAsInt(), groupId,
isTemplate));
insertedWithLocalId = true;
}
} catch (NumberFormatException e) {
Log.debug(Geonet.MEF, "Invalid localId provided: " + localId + ". Adding record with a new id.");
}
}
if (!insertedWithLocalId) {
id.add(index, dm.insertMetadataExt(dbms, schema, md.get(index),
context.getSerialFactory(), source, createDate, changeDate,
uuid, context.getUserSession().getUserIdAsInt(), groupId));
}
}
// --------------------------------------------------------------------------
private static void saveFile(ServiceContext context, String id,
String access, String file, String changeDate, InputStream is)
throws IOException {
String dir = Lib.resource.getDir(context, access, id);
File outFile = new File(dir, file);
FileOutputStream os = new FileOutputStream(outFile);
BinaryFile.copy(is, os, false, true);
outFile.setLastModified(new ISODate(changeDate).getSeconds() * 1000);
}
/**
* Add categories registered in information file.
*
* @param dm
* @param dbms
* @param id
* @param categ
* @throws Exception
*/
public static void addCategories(DataManager dm, Dbms dbms, String id,
Element categ) throws Exception {
List locCats = dbms.select("SELECT id,name FROM Categories")
.getChildren();
List list = categ.getChildren("category");
for (Iterator j = list.iterator(); j.hasNext();) {
String catName = ((Element) j.next()).getAttributeValue("name");
String catId = mapLocalEntity(locCats, catName);
if (catId == null) {
Log.debug(Geonet.MEF, " - Skipping inexistent category : "
+ catName);
} else {
// --- metadata category exists locally
Log.debug(Geonet.MEF, " - Setting category : " + catName);
dm.setCategory(dbms, id, catId);
}
}
}
/**
* Add privileges according to information file.
*
* @param dm
* @param dbms
* @param id
* @param privil
* @throws Exception
*/
private static void addPrivileges(DataManager dm, Dbms dbms, String id,
Element privil) throws Exception {
List locGrps = dbms.select("SELECT id,name FROM Groups").getChildren();
List list = privil.getChildren("group");
for (Object g : list) {
Element group = (Element) g;
String grpName = group.getAttributeValue("name");
boolean groupOwner = group.getAttributeValue("groupOwner") != null;
String grpId = mapLocalEntity(locGrps, grpName);
if (grpId == null)
Log.debug(Geonet.MEF, " - Skipping inesistent group : "
+ grpName);
else {
// --- metadata group exists locally
Log.debug(Geonet.MEF, " - Setting privileges for group : "
+ grpName);
addOperations(dm, dbms, group, id, grpId);
if (groupOwner) {
Log.debug(Geonet.MEF, grpName + " set as group Owner ");
dm.setGroupOwner(dbms, id, grpId);
}
}
}
}
/**
* Add operations according to information file.
*
* @param dm
* @param dbms
* @param group
* @param id
* @param grpId
* @throws Exception
*/
private static void addOperations(DataManager dm, Dbms dbms, Element group,
String id, String grpId) throws Exception {
List opers = group.getChildren("operation");
for (int j = 0; j < opers.size(); j++) {
Element oper = (Element) opers.get(j);
String opName = oper.getAttributeValue("name");
int opId = dm.getAccessManager().getPrivilegeId(opName);
if (opId == -1)
Log.debug(Geonet.MEF, " Skipping --> " + opName);
else {
// --- operation exists locally
Log.debug(Geonet.MEF, " Adding --> " + opName);
dm.setOperation(dbms, id, grpId, opId + "");
}
}
}
private static String mapLocalEntity(List entities, String name) {
for (Object e : entities) {
Element entity = (Element) e;
if (entity.getChildText("name").equals(name)
|| entity.getChildText("id").equals(name))
return entity.getChildText("id");
}
return null;
}
}
// =============================================================================
| true | true | public static List<String> doImport(final Element params,
final ServiceContext context, File mefFile, final String stylePath,
final boolean indexGroup) throws Exception {
final GeonetContext gc = (GeonetContext) context
.getHandlerContext(Geonet.CONTEXT_NAME);
final DataManager dm = gc.getDataManager();
// Load preferred schema and set to iso19139 by default
final String preferredSchema = (gc.getHandlerConfig()
.getMandatoryValue("preferredSchema") != null ? gc
.getHandlerConfig().getMandatoryValue("preferredSchema")
: "iso19139");
final Dbms dbms = (Dbms) context.getResourceManager().open(
Geonet.Res.MAIN_DB);
final List<String> id = new ArrayList<String>();
final List<Element> md = new ArrayList<Element>();
final List<Element> fc = new ArrayList<Element>();
// Try to define MEF version from mef file not from parameter
String fileType = Util.getParam(params, "file_type", "mef");
if (fileType.equals("mef")) {
MEFLib.Version version = MEFLib.getMEFVersion(mefFile);
if (version.equals(MEFLib.Version.V2))
fileType = "mef2";
}
IVisitor visitor = null;
if (fileType.equals("single"))
visitor = new XmlVisitor();
else if (fileType.equals("mef"))
visitor = new MEFVisitor();
else if (fileType.equals("mef2"))
visitor = new MEF2Visitor();
else
throw new BadArgumentException("Bad file type parameter.");
// --- import metadata from MEF, Xml, ZIP files
MEFLib.visit(mefFile, visitor, new IMEFVisitor() {
public void handleMetadata(Element metadata, int index)
throws Exception {
Log.debug(Geonet.MEF, "Collecting metadata:\n"
+ Xml.getString(metadata));
md.add(index, metadata);
}
public void handleMetadataFiles(File[] Files, int index)
throws Exception {
Log.debug(Geonet.MEF, "Multiple metadata files");
Element metadataValidForImport = null;
for (int i = 0; i < Files.length; i++) {
File file = Files[i];
if (file != null && !file.isDirectory()) {
Element metadata = Xml.loadFile(file);
String metadataSchema = dm.autodetectSchema(metadata);
// If local node doesn't know metadata
// schema try to load next xml file.
if (metadataSchema == null)
continue;
// If schema is preferred local node schema
// load that file.
if (metadataSchema.equals(preferredSchema)) {
Log.debug(Geonet.MEF, "Found metadata file "
+ file.getName()
+ " with preferred schema ("
+ preferredSchema + ").");
handleMetadata(metadata, index);
return;
} else {
Log.debug(Geonet.MEF, "Found metadata file "
+ file.getName() + " with known schema ("
+ metadataSchema + ").");
metadataValidForImport = metadata;
}
}
}
// Import a valid metadata if not one found
// with preferred schema.
if (metadataValidForImport != null) {
Log
.debug(Geonet.MEF,
"Importing metadata with valide schema but not preferred one.");
handleMetadata(metadataValidForImport, index);
return;
} else
throw new BadFormatEx("No valid metadata file found.");
}
// --------------------------------------------------------------------
public void handleFeatureCat(Element featureCat, int index)
throws Exception {
if (featureCat != null) {
Log.debug(Geonet.MEF, "Collecting feature catalog:\n"
+ Xml.getString(featureCat));
}
fc.add(index, featureCat);
}
// --------------------------------------------------------------------
/**
* Record is not a template by default. No category attached to
* record by default. No stylesheet used by default. If no site
* identifier provided, use current node id by default. No
* validation by default.
*
* If record is a template and not a MEF file always generate a new
* UUID.
*/
public void handleInfo(Element info, int index) throws Exception {
String FS = File.separator;
String uuid = null;
String createDate = null;
String changeDate = null;
String source = null;
String sourceName = null;
// Schema in info.xml is not used anymore.
// as we use autodetect schema to define
// metadata schema.
// String schema = null;
String isTemplate = null;
String localId = null;
String rating = null;
String popularity = null;
String groupId = null;
Element categs = null;
Element privileges = null;
boolean validate = false;
Element metadata = md.get(index);
String schema = dm.autodetectSchema(metadata);
if (schema == null)
throw new Exception("Unknown schema format : " + schema);
// Handle non MEF files insertion
if (info.getChildren().size() == 0) {
source = Util.getParam(params, Params.SITE_ID, gc
.getSiteId());
isTemplate = Util.getParam(params, Params.TEMPLATE, "n");
String category = Util
.getParam(params, Params.CATEGORY, "");
if (!category.equals("")) {
categs = new Element("categories");
categs.addContent((new Element("category"))
.setAttribute("name", category));
}
groupId = Util.getParam(params, Params.GROUP);
privileges = new Element("group");
privileges.addContent(new Element("operation")
.setAttribute("name", "view"));
privileges.addContent(new Element("operation")
.setAttribute("name", "editing"));
privileges.addContent(new Element("operation")
.setAttribute("name", "download"));
privileges.addContent(new Element("operation")
.setAttribute("name", "notify"));
privileges.addContent(new Element("operation")
.setAttribute("name", "dynamic"));
privileges.addContent(new Element("operation")
.setAttribute("name", "featured"));
String style = Util.getParam(params, Params.STYLESHEET,
"_none_");
// Apply a stylesheet transformation if requested
if (!style.equals("_none_"))
md.add(index, Xml.transform(md.get(index), stylePath
+ FS + style));
// Get the Metadata uuid if it's not a template.
if (isTemplate.equals("n"))
uuid = dm.extractUUID(schema, md.get(index));
validate = Util.getParam(params, Params.VALIDATE, "off")
.equals("on");
} else {
categs = info.getChild("categories");
privileges = info.getChild("privileges");
Element general = info.getChild("general");
uuid = general.getChildText("uuid");
createDate = general.getChildText("createDate");
changeDate = general.getChildText("changeDate");
source = general.getChildText("siteId");
sourceName = general.getChildText("siteName");
localId = general.getChildText("localId");
isTemplate = general.getChildText("isTemplate").equals(
"true") ? "y" : "n";
rating = general.getChildText("rating");
popularity = general.getChildText("popularity");
}
if (validate)
dm.validate(schema, metadata);
String uuidAction = Util.getParam(params, Params.UUID_ACTION,
Params.NOTHING);
importRecord(uuid, localId, uuidAction, md, schema, index,
source, sourceName, context, id, createDate,
changeDate, groupId, isTemplate);
if (fc.size() != 0 && fc.get(index) != null) {
// UUID is set as @uuid in root element
uuid = UUID.randomUUID().toString();
fc.add(index, dm.setUUID("iso19110", uuid, fc.get(index)));
String fcId = dm.insertMetadataExt(dbms, "iso19110", fc
.get(index), context.getSerialFactory(), source,
createDate, changeDate, uuid, context
.getUserSession().getUserIdAsInt(), null);
Log.debug(Geonet.MEF, "Adding Feature catalog with uuid: "
+ uuid);
// Create database relation between metadata and feature
// catalog
String mdId = id.get(index);
String query = "INSERT INTO Relations (id, relatedId) VALUES (?, ?)";
dbms.execute(query, mdId, fcId);
id.add(fcId);
// TODO : privileges not handled for feature
// catalog ...
}
int iId = Integer.parseInt(id.get(index));
if (rating != null)
dbms.execute("UPDATE Metadata SET rating=? WHERE id=?",
new Integer(rating), iId);
if (popularity != null)
dbms.execute("UPDATE Metadata SET popularity=? WHERE id=?",
new Integer(popularity), iId);
dm.setTemplateExt(dbms, iId, isTemplate, null);
dm.setHarvestedExt(dbms, iId, null);
String pubDir = Lib.resource.getDir(context, "public", id
.get(index));
String priDir = Lib.resource.getDir(context, "private", id
.get(index));
new File(pubDir).mkdirs();
new File(priDir).mkdirs();
if (categs != null)
addCategories(dm, dbms, id.get(index), categs);
if (groupId == null)
addPrivileges(dm, dbms, id.get(index), privileges);
else
addOperations(dm, dbms, privileges, id.get(index), groupId);
if (indexGroup) {
dm.indexMetadataGroup(dbms, id.get(index));
} else {
dm.indexMetadata(dbms, id.get(index));
}
}
// --------------------------------------------------------------------
public void handlePublicFile(String file, String changeDate,
InputStream is, int index) throws IOException {
Log.debug(Geonet.MEF, "Adding public file with name=" + file);
saveFile(context, id.get(index), "public", file, changeDate, is);
}
// --------------------------------------------------------------------
public void handlePrivateFile(String file, String changeDate,
InputStream is, int index) throws IOException {
Log.debug(Geonet.MEF, "Adding private file with name=" + file);
saveFile(context, id.get(index), "private", file, changeDate,
is);
}
});
return id;
}
| public static List<String> doImport(final Element params,
final ServiceContext context, File mefFile, final String stylePath,
final boolean indexGroup) throws Exception {
final GeonetContext gc = (GeonetContext) context
.getHandlerContext(Geonet.CONTEXT_NAME);
final DataManager dm = gc.getDataManager();
// Load preferred schema and set to iso19139 by default
final String preferredSchema = (gc.getHandlerConfig()
.getMandatoryValue("preferredSchema") != null ? gc
.getHandlerConfig().getMandatoryValue("preferredSchema")
: "iso19139");
final Dbms dbms = (Dbms) context.getResourceManager().open(
Geonet.Res.MAIN_DB);
final List<String> id = new ArrayList<String>();
final List<Element> md = new ArrayList<Element>();
final List<Element> fc = new ArrayList<Element>();
// Try to define MEF version from mef file not from parameter
String fileType = Util.getParam(params, "file_type", "mef");
if (fileType.equals("mef")) {
MEFLib.Version version = MEFLib.getMEFVersion(mefFile);
if (version.equals(MEFLib.Version.V2))
fileType = "mef2";
}
IVisitor visitor = null;
if (fileType.equals("single"))
visitor = new XmlVisitor();
else if (fileType.equals("mef"))
visitor = new MEFVisitor();
else if (fileType.equals("mef2"))
visitor = new MEF2Visitor();
else
throw new BadArgumentException("Bad file type parameter.");
// --- import metadata from MEF, Xml, ZIP files
MEFLib.visit(mefFile, visitor, new IMEFVisitor() {
public void handleMetadata(Element metadata, int index)
throws Exception {
Log.debug(Geonet.MEF, "Collecting metadata:\n"
+ Xml.getString(metadata));
md.add(index, metadata);
}
public void handleMetadataFiles(File[] Files, int index)
throws Exception {
Log.debug(Geonet.MEF, "Multiple metadata files");
Element metadataValidForImport = null;
for (int i = 0; i < Files.length; i++) {
File file = Files[i];
if (file != null && !file.isDirectory()) {
Element metadata = Xml.loadFile(file);
String metadataSchema = dm.autodetectSchema(metadata);
// If local node doesn't know metadata
// schema try to load next xml file.
if (metadataSchema == null)
continue;
// If schema is preferred local node schema
// load that file.
if (metadataSchema.equals(preferredSchema)) {
Log.debug(Geonet.MEF, "Found metadata file "
+ file.getName()
+ " with preferred schema ("
+ preferredSchema + ").");
handleMetadata(metadata, index);
return;
} else {
Log.debug(Geonet.MEF, "Found metadata file "
+ file.getName() + " with known schema ("
+ metadataSchema + ").");
metadataValidForImport = metadata;
}
}
}
// Import a valid metadata if not one found
// with preferred schema.
if (metadataValidForImport != null) {
Log
.debug(Geonet.MEF,
"Importing metadata with valide schema but not preferred one.");
handleMetadata(metadataValidForImport, index);
return;
} else
throw new BadFormatEx("No valid metadata file found.");
}
// --------------------------------------------------------------------
public void handleFeatureCat(Element featureCat, int index)
throws Exception {
if (featureCat != null) {
Log.debug(Geonet.MEF, "Collecting feature catalog:\n"
+ Xml.getString(featureCat));
}
fc.add(index, featureCat);
}
// --------------------------------------------------------------------
/**
* Record is not a template by default. No category attached to
* record by default. No stylesheet used by default. If no site
* identifier provided, use current node id by default. No
* validation by default.
*
* If record is a template and not a MEF file always generate a new
* UUID.
*/
public void handleInfo(Element info, int index) throws Exception {
String FS = File.separator;
String uuid = null;
String createDate = null;
String changeDate = null;
String source = null;
String sourceName = null;
// Schema in info.xml is not used anymore.
// as we use autodetect schema to define
// metadata schema.
// String schema = null;
String isTemplate = null;
String localId = null;
String rating = null;
String popularity = null;
String groupId = null;
Element categs = null;
Element privileges = null;
boolean validate = false;
Element metadata = md.get(index);
String schema = dm.autodetectSchema(metadata);
if (schema == null)
throw new Exception("Unknown schema format : " + schema);
// Handle non MEF files insertion
if (info.getChildren().size() == 0) {
source = Util.getParam(params, Params.SITE_ID, gc
.getSiteId());
isTemplate = Util.getParam(params, Params.TEMPLATE, "n");
String category = Util
.getParam(params, Params.CATEGORY, "");
if (!category.equals("")) {
categs = new Element("categories");
categs.addContent((new Element("category"))
.setAttribute("name", category));
}
groupId = Util.getParam(params, Params.GROUP);
privileges = new Element("group");
privileges.addContent(new Element("operation")
.setAttribute("name", "view"));
privileges.addContent(new Element("operation")
.setAttribute("name", "editing"));
privileges.addContent(new Element("operation")
.setAttribute("name", "download"));
privileges.addContent(new Element("operation")
.setAttribute("name", "notify"));
privileges.addContent(new Element("operation")
.setAttribute("name", "dynamic"));
privileges.addContent(new Element("operation")
.setAttribute("name", "featured"));
String style = Util.getParam(params, Params.STYLESHEET,
"_none_");
// Apply a stylesheet transformation if requested
if (!style.equals("_none_"))
md.add(index, Xml.transform(md.get(index), stylePath
+ FS + style));
// Get the Metadata uuid if it's not a template.
if (isTemplate.equals("n"))
uuid = dm.extractUUID(schema, md.get(index));
validate = Util.getParam(params, Params.VALIDATE, "off")
.equals("on");
} else {
categs = info.getChild("categories");
privileges = info.getChild("privileges");
Element general = info.getChild("general");
uuid = general.getChildText("uuid");
createDate = general.getChildText("createDate");
changeDate = general.getChildText("changeDate");
source = general.getChildText("siteId");
sourceName = general.getChildText("siteName");
localId = general.getChildText("localId");
isTemplate = general.getChildText("isTemplate").equals(
"true") ? "y" : "n";
rating = general.getChildText("rating");
popularity = general.getChildText("popularity");
}
if (validate)
dm.validate(schema, metadata);
String uuidAction = Util.getParam(params, Params.UUID_ACTION,
Params.NOTHING);
importRecord(uuid, localId, uuidAction, md, schema, index,
source, sourceName, context, id, createDate,
changeDate, groupId, isTemplate);
if (fc.size() != 0 && fc.get(index) != null) {
// UUID is set as @uuid in root element
uuid = UUID.randomUUID().toString();
fc.add(index, dm.setUUID("iso19110", uuid, fc.get(index)));
String fcId = dm.insertMetadataExt(dbms, "iso19110", fc
.get(index), context.getSerialFactory(), source,
createDate, changeDate, uuid, context
.getUserSession().getUserIdAsInt(), null);
Log.debug(Geonet.MEF, "Adding Feature catalog with uuid: "
+ uuid);
// Create database relation between metadata and feature
// catalog
String mdId = id.get(index);
String query = "INSERT INTO Relations (id, relatedId) VALUES (?, ?)";
dbms.execute(query, Integer.parseInt(mdId), Integer.parseInt(fcId));
id.add(fcId);
// TODO : privileges not handled for feature
// catalog ...
}
int iId = Integer.parseInt(id.get(index));
if (rating != null)
dbms.execute("UPDATE Metadata SET rating=? WHERE id=?",
new Integer(rating), iId);
if (popularity != null)
dbms.execute("UPDATE Metadata SET popularity=? WHERE id=?",
new Integer(popularity), iId);
dm.setTemplateExt(dbms, iId, isTemplate, null);
dm.setHarvestedExt(dbms, iId, null);
String pubDir = Lib.resource.getDir(context, "public", id
.get(index));
String priDir = Lib.resource.getDir(context, "private", id
.get(index));
new File(pubDir).mkdirs();
new File(priDir).mkdirs();
if (categs != null)
addCategories(dm, dbms, id.get(index), categs);
if (groupId == null)
addPrivileges(dm, dbms, id.get(index), privileges);
else
addOperations(dm, dbms, privileges, id.get(index), groupId);
if (indexGroup) {
dm.indexMetadataGroup(dbms, id.get(index));
} else {
dm.indexMetadata(dbms, id.get(index));
}
}
// --------------------------------------------------------------------
public void handlePublicFile(String file, String changeDate,
InputStream is, int index) throws IOException {
Log.debug(Geonet.MEF, "Adding public file with name=" + file);
saveFile(context, id.get(index), "public", file, changeDate, is);
}
// --------------------------------------------------------------------
public void handlePrivateFile(String file, String changeDate,
InputStream is, int index) throws IOException {
Log.debug(Geonet.MEF, "Adding private file with name=" + file);
saveFile(context, id.get(index), "private", file, changeDate,
is);
}
});
return id;
}
|
diff --git a/src/main/java/de/cismet/cids/custom/objecteditors/wunda_blau/VermessungRissEditor.java b/src/main/java/de/cismet/cids/custom/objecteditors/wunda_blau/VermessungRissEditor.java
index 8f11b613..c0fc08f6 100644
--- a/src/main/java/de/cismet/cids/custom/objecteditors/wunda_blau/VermessungRissEditor.java
+++ b/src/main/java/de/cismet/cids/custom/objecteditors/wunda_blau/VermessungRissEditor.java
@@ -1,2559 +1,2567 @@
/***************************************************
*
* cismet GmbH, Saarbruecken, Germany
*
* ... and it just works.
*
****************************************************/
package de.cismet.cids.custom.objecteditors.wunda_blau;
import Sirius.navigator.connection.SessionManager;
import Sirius.navigator.exception.ConnectionException;
import Sirius.navigator.ui.ComponentRegistry;
import Sirius.navigator.ui.RequestsFullSizeComponent;
import Sirius.server.middleware.types.MetaObject;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.PrecisionModel;
import org.apache.log4j.Logger;
import org.openide.util.Exceptions;
import org.openide.util.NbBundle;
import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Date;
import java.text.MessageFormat;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import javax.swing.DefaultListModel;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JToggleButton;
import javax.swing.ListCellRenderer;
import javax.swing.ListModel;
import javax.swing.SwingWorker;
import javax.swing.WindowConstants;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import de.cismet.cids.custom.objectrenderer.utils.CidsBeanSupport;
import de.cismet.cids.custom.objectrenderer.utils.ObjectRendererUtils;
import de.cismet.cids.custom.utils.alkis.AlkisConstants;
import de.cismet.cids.custom.wunda_blau.search.server.CidsVermessungRissSearchStatement;
import de.cismet.cids.dynamics.CidsBean;
import de.cismet.cids.dynamics.DisposableCidsBeanStore;
import de.cismet.cids.editors.DefaultBindableReferenceCombo;
import de.cismet.cids.editors.DefaultCustomObjectEditor;
import de.cismet.cids.editors.EditorClosedEvent;
import de.cismet.cids.editors.EditorSaveListener;
import de.cismet.cids.editors.converters.SqlDateToStringConverter;
import de.cismet.cismap.cids.geometryeditor.DefaultCismapGeometryComboBoxEditor;
import de.cismet.cismap.commons.Crs;
import de.cismet.cismap.commons.CrsTransformer;
import de.cismet.cismap.commons.XBoundingBox;
import de.cismet.cismap.commons.gui.measuring.MeasuringComponent;
import de.cismet.security.WebAccessManager;
import de.cismet.tools.gui.*;
import de.cismet.tools.gui.downloadmanager.DownloadManager;
import de.cismet.tools.gui.downloadmanager.DownloadManagerDialog;
import de.cismet.tools.gui.downloadmanager.HttpDownload;
/**
* DOCUMENT ME!
*
* @author jweintraut
* @version $Revision$, $Date$
*/
public class VermessungRissEditor extends javax.swing.JPanel implements DisposableCidsBeanStore,
TitleComponentProvider,
FooterComponentProvider,
BorderProvider,
RequestsFullSizeComponent,
EditorSaveListener {
//~ Static fields/initializers ---------------------------------------------
private static final Logger LOG = Logger.getLogger(VermessungRissEditor.class);
public static final String[] SUFFIXES = new String[] {
"tif",
"jpg",
"jpe",
"tiff",
"jpeg",
"TIF",
"JPG",
"JPE",
"TIFF",
"JPEG"
};
private static final String SUFFIX_REDUCED_SIZE = "_RS";
private static final String KEY_WARNINGREDUCEDSIZE_WIDGET = "WarningReducedSize_Widget";
protected static final int DOCUMENT_BILD = 0;
protected static final int DOCUMENT_GRENZNIEDERSCHRIFT = 1;
protected static final int NO_SELECTION = -1;
protected static final ListModel MODEL_LOAD = new DefaultListModel() {
{
add(0, "Wird geladen...");
}
};
protected static XBoundingBox INITIAL_BOUNDINGBOX = new XBoundingBox(
2583621.251964098d,
5682507.032498134d,
2584022.9413952776d,
5682742.852810634d,
AlkisConstants.COMMONS.SRS_SERVICE,
true);
protected static Crs CRS = new Crs(
AlkisConstants.COMMONS.SRS_SERVICE,
AlkisConstants.COMMONS.SRS_SERVICE,
AlkisConstants.COMMONS.SRS_SERVICE,
true,
true);
protected static final GeometryFactory GEOMETRY_FACTORY = new GeometryFactory(new PrecisionModel(
PrecisionModel.FLOATING),
CrsTransformer.extractSridFromCrs(AlkisConstants.COMMONS.SRS_SERVICE));
protected static final Map<Integer, Color> COLORS_GEOMETRIE_STATUS = new HashMap<Integer, Color>();
static {
COLORS_GEOMETRIE_STATUS.put(new Integer(1), Color.green);
COLORS_GEOMETRIE_STATUS.put(new Integer(2), Color.yellow);
COLORS_GEOMETRIE_STATUS.put(new Integer(3), Color.yellow);
COLORS_GEOMETRIE_STATUS.put(new Integer(4), Color.red);
COLORS_GEOMETRIE_STATUS.put(new Integer(5), Color.red);
}
//~ Instance fields --------------------------------------------------------
protected CidsBean cidsBean;
protected Object schluessel;
protected Object gemarkung;
protected Object flur;
protected Object blatt;
protected boolean readOnly;
protected Map.Entry<URL, URL>[] documentURLs;
protected JToggleButton[] documentButtons;
protected JToggleButton currentSelectedButton;
protected PictureSelectWorker currentPictureSelectWorker = null;
protected MultiPagePictureReader pictureReader;
protected VermessungFlurstueckSelectionDialog flurstueckDialog;
protected volatile int currentDocument = NO_SELECTION;
protected volatile int currentPage = NO_SELECTION;
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.ButtonGroup bgrControls;
private javax.swing.ButtonGroup bgrDocument;
private javax.swing.JButton btnAddLandparcel;
private javax.swing.JButton btnCombineGeometries;
private javax.swing.JButton btnHome;
private javax.swing.JButton btnOpen;
private javax.swing.JButton btnRemoveLandparcel;
private javax.swing.JComboBox cmbFormat;
private javax.swing.JComboBox cmbGemarkung;
private javax.swing.JComboBox cmbGeometrie;
private javax.swing.JComboBox cmbGeometrieStatus;
private javax.swing.JComboBox cmbSchluessel;
private javax.swing.Box.Filler gluGapControls;
private javax.swing.Box.Filler gluGeneralInformationGap;
private javax.swing.JInternalFrame ifrWarningReducedSize;
private javax.swing.JLabel lblBlatt;
private javax.swing.JLabel lblErrorWhileLoadingBild;
private javax.swing.JLabel lblErrorWhileLoadingGrenzniederschrift;
private javax.swing.JLabel lblFlur;
private javax.swing.JLabel lblFormat;
private javax.swing.JLabel lblGemarkung;
private javax.swing.JLabel lblGeneralInformation;
private javax.swing.JLabel lblGeometrie;
private javax.swing.JLabel lblGeometrieStatus;
private javax.swing.JLabel lblHeaderControls;
private javax.swing.JLabel lblHeaderDocument;
private javax.swing.JLabel lblHeaderDocuments;
private javax.swing.JLabel lblHeaderLandparcels;
private javax.swing.JLabel lblHeaderPages;
private javax.swing.JLabel lblJahr;
private javax.swing.JLabel lblLetzteAenderungDatum;
private javax.swing.JLabel lblLetzteAenderungName;
private javax.swing.JLabel lblMissingDocuments;
private javax.swing.JLabel lblSchluessel;
private javax.swing.JLabel lblTitle;
private javax.swing.JLabel lblWarningReducedSize;
private javax.swing.JList lstLandparcels;
private javax.swing.JList lstPages;
private de.cismet.cismap.commons.gui.measuring.MeasuringComponent measuringComponent;
private javax.swing.JPanel pnlContainer;
private de.cismet.tools.gui.RoundedPanel pnlControls;
private de.cismet.tools.gui.RoundedPanel pnlDocument;
private de.cismet.tools.gui.RoundedPanel pnlDocuments;
private de.cismet.tools.gui.RoundedPanel pnlGeneralInformation;
private de.cismet.tools.gui.SemiRoundedPanel pnlHeaderControls;
private de.cismet.tools.gui.SemiRoundedPanel pnlHeaderDocument;
private de.cismet.tools.gui.SemiRoundedPanel pnlHeaderDocuments;
private de.cismet.tools.gui.SemiRoundedPanel pnlHeaderGeneralInformation;
private de.cismet.tools.gui.SemiRoundedPanel pnlHeaderLandparcels;
private de.cismet.tools.gui.SemiRoundedPanel pnlHeaderPages;
private de.cismet.tools.gui.RoundedPanel pnlLandparcels;
private de.cismet.tools.gui.RoundedPanel pnlPages;
private javax.swing.JPanel pnlTitle;
private javax.swing.JScrollPane scpLandparcels;
private javax.swing.JScrollPane scpPages;
private javax.swing.Box.Filler strFooter;
private javax.swing.JToggleButton togBild;
private javax.swing.JToggleButton togGrenzniederschrift;
private javax.swing.JToggleButton togPan;
private javax.swing.JToggleButton togZoom;
private javax.swing.JTextField txtBlatt;
private javax.swing.JTextField txtFlur;
private javax.swing.JTextField txtJahr;
private javax.swing.JTextField txtLetzteaenderungDatum;
private javax.swing.JTextField txtLetzteaenderungName;
private org.jdesktop.beansbinding.BindingGroup bindingGroup;
// End of variables declaration//GEN-END:variables
//~ Constructors -----------------------------------------------------------
/**
* Creates a new VermessungRissEditor object.
*/
public VermessungRissEditor() {
this(false);
}
/**
* Creates new form VermessungRissEditor.
*
* @param readOnly DOCUMENT ME!
*/
public VermessungRissEditor(final boolean readOnly) {
this.readOnly = readOnly;
documentURLs = new Map.Entry[2];
documentButtons = new JToggleButton[documentURLs.length];
initComponents();
documentButtons[DOCUMENT_BILD] = togBild;
documentButtons[DOCUMENT_GRENZNIEDERSCHRIFT] = togGrenzniederschrift;
ifrWarningReducedSize.putClientProperty("JInternalFrame.isPalette", Boolean.TRUE);
if (readOnly) {
lblSchluessel.setVisible(false);
cmbSchluessel.setVisible(false);
lblGemarkung.setVisible(false);
cmbGemarkung.setVisible(false);
lblFlur.setVisible(false);
txtFlur.setVisible(false);
lblBlatt.setVisible(false);
txtBlatt.setVisible(false);
txtJahr.setEditable(false);
cmbFormat.setEditable(false);
cmbFormat.setEnabled(false);
cmbGeometrieStatus.setEditable(false);
cmbGeometrieStatus.setEnabled(false);
lblGeometrie.setVisible(false);
btnAddLandparcel.setVisible(false);
btnRemoveLandparcel.setVisible(false);
btnCombineGeometries.setVisible(false);
} else {
flurstueckDialog = new VermessungFlurstueckSelectionDialog();
flurstueckDialog.pack();
flurstueckDialog.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
flurstueckDialog.addWindowListener(new EnableCombineGeometriesButton());
if (txtBlatt.getDocument() instanceof AbstractDocument) {
((AbstractDocument)txtBlatt.getDocument()).setDocumentFilter(new DocumentSizeFilter());
}
if (txtFlur.getDocument() instanceof AbstractDocument) {
((AbstractDocument)txtFlur.getDocument()).setDocumentFilter(new DocumentSizeFilter());
}
}
}
//~ Methods ----------------------------------------------------------------
/**
* This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The
* content of this method is always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
bindingGroup = new org.jdesktop.beansbinding.BindingGroup();
strFooter = new javax.swing.Box.Filler(new java.awt.Dimension(0, 22),
new java.awt.Dimension(0, 22),
new java.awt.Dimension(32767, 22));
pnlTitle = new javax.swing.JPanel();
lblTitle = new javax.swing.JLabel();
bgrControls = new javax.swing.ButtonGroup();
bgrDocument = new javax.swing.ButtonGroup();
ifrWarningReducedSize = new javax.swing.JInternalFrame();
lblWarningReducedSize = new javax.swing.JLabel();
pnlContainer = new javax.swing.JPanel();
pnlGeneralInformation = new de.cismet.tools.gui.RoundedPanel();
pnlHeaderGeneralInformation = new de.cismet.tools.gui.SemiRoundedPanel();
lblGeneralInformation = new javax.swing.JLabel();
lblJahr = new javax.swing.JLabel();
txtJahr = new javax.swing.JTextField();
lblFormat = new javax.swing.JLabel();
cmbFormat = new DefaultBindableReferenceCombo();
lblLetzteAenderungName = new javax.swing.JLabel();
txtLetzteaenderungName = new javax.swing.JTextField();
lblLetzteAenderungDatum = new javax.swing.JLabel();
txtLetzteaenderungDatum = new javax.swing.JTextField();
lblGeometrie = new javax.swing.JLabel();
if (!readOnly) {
cmbGeometrie = new DefaultCismapGeometryComboBoxEditor();
}
btnCombineGeometries = new javax.swing.JButton();
gluGeneralInformationGap = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0),
new java.awt.Dimension(0, 0),
new java.awt.Dimension(0, 32767));
lblGeometrieStatus = new javax.swing.JLabel();
cmbGeometrieStatus = new DefaultBindableReferenceCombo();
lblSchluessel = new javax.swing.JLabel();
cmbSchluessel = new javax.swing.JComboBox();
lblGemarkung = new javax.swing.JLabel();
cmbGemarkung = new DefaultBindableReferenceCombo();
lblFlur = new javax.swing.JLabel();
txtFlur = new javax.swing.JTextField();
lblBlatt = new javax.swing.JLabel();
txtBlatt = new javax.swing.JTextField();
pnlLandparcels = new de.cismet.tools.gui.RoundedPanel();
pnlHeaderLandparcels = new de.cismet.tools.gui.SemiRoundedPanel();
lblHeaderLandparcels = new javax.swing.JLabel();
scpLandparcels = new javax.swing.JScrollPane();
lstLandparcels = new javax.swing.JList();
btnAddLandparcel = new javax.swing.JButton();
btnRemoveLandparcel = new javax.swing.JButton();
pnlControls = new de.cismet.tools.gui.RoundedPanel();
togPan = new javax.swing.JToggleButton();
togZoom = new javax.swing.JToggleButton();
btnHome = new javax.swing.JButton();
pnlHeaderControls = new de.cismet.tools.gui.SemiRoundedPanel();
lblHeaderControls = new javax.swing.JLabel();
btnOpen = new javax.swing.JButton();
pnlDocuments = new de.cismet.tools.gui.RoundedPanel();
pnlHeaderDocuments = new de.cismet.tools.gui.SemiRoundedPanel();
lblHeaderDocuments = new javax.swing.JLabel();
togBild = new javax.swing.JToggleButton();
togGrenzniederschrift = new javax.swing.JToggleButton();
pnlPages = new de.cismet.tools.gui.RoundedPanel();
pnlHeaderPages = new de.cismet.tools.gui.SemiRoundedPanel();
lblHeaderPages = new javax.swing.JLabel();
scpPages = new javax.swing.JScrollPane();
lstPages = new javax.swing.JList();
pnlDocument = new de.cismet.tools.gui.RoundedPanel();
pnlHeaderDocument = new de.cismet.tools.gui.SemiRoundedPanel();
lblHeaderDocument = new javax.swing.JLabel();
measuringComponent = new MeasuringComponent(INITIAL_BOUNDINGBOX, CRS);
lblErrorWhileLoadingBild = new javax.swing.JLabel();
lblErrorWhileLoadingGrenzniederschrift = new javax.swing.JLabel();
lblMissingDocuments = new javax.swing.JLabel();
gluGapControls = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0),
new java.awt.Dimension(0, 0),
new java.awt.Dimension(0, 32767));
pnlTitle.setOpaque(false);
pnlTitle.setLayout(new java.awt.GridBagLayout());
lblTitle.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
lblTitle.setForeground(java.awt.Color.white);
lblTitle.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblTitle.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.1;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlTitle.add(lblTitle, gridBagConstraints);
ifrWarningReducedSize.setResizable(true);
ifrWarningReducedSize.setVisible(true);
lblWarningReducedSize.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/warningReducedSize.png"))); // NOI18N
lblWarningReducedSize.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblWarningReducedSize.text")); // NOI18N
ifrWarningReducedSize.getContentPane().add(lblWarningReducedSize, java.awt.BorderLayout.CENTER);
setLayout(new java.awt.GridBagLayout());
pnlContainer.setOpaque(false);
pnlContainer.setLayout(new java.awt.GridBagLayout());
pnlGeneralInformation.setLayout(new java.awt.GridBagLayout());
pnlHeaderGeneralInformation.setBackground(new java.awt.Color(51, 51, 51));
pnlHeaderGeneralInformation.setLayout(new java.awt.FlowLayout());
lblGeneralInformation.setForeground(new java.awt.Color(255, 255, 255));
lblGeneralInformation.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblGeneralInformation.text")); // NOI18N
pnlHeaderGeneralInformation.add(lblGeneralInformation);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 0.1;
pnlGeneralInformation.add(pnlHeaderGeneralInformation, gridBagConstraints);
lblJahr.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblJahr.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5);
pnlGeneralInformation.add(lblJahr, gridBagConstraints);
org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.jahr}"),
txtJahr,
org.jdesktop.beansbinding.BeanProperty.create("text"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
+ gridBagConstraints.weightx = 0.5;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 7);
pnlGeneralInformation.add(txtJahr, gridBagConstraints);
lblFormat.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblFormat.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5);
pnlGeneralInformation.add(lblFormat, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.format}"),
cmbFormat,
org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
+ gridBagConstraints.weightx = 0.5;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 7);
pnlGeneralInformation.add(cmbFormat, gridBagConstraints);
lblLetzteAenderungName.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblLetzteAenderungName.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 7, 5, 5);
pnlGeneralInformation.add(lblLetzteAenderungName, gridBagConstraints);
txtLetzteaenderungName.setEditable(false);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.letzteaenderung_name}"),
txtLetzteaenderungName,
org.jdesktop.beansbinding.BeanProperty.create("text"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
+ gridBagConstraints.weightx = 0.5;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10);
pnlGeneralInformation.add(txtLetzteaenderungName, gridBagConstraints);
lblLetzteAenderungDatum.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblLetzteAenderungDatum.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 7, 5, 5);
pnlGeneralInformation.add(lblLetzteAenderungDatum, gridBagConstraints);
txtLetzteaenderungDatum.setEditable(false);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.letzteaenderung_datum}"),
txtLetzteaenderungDatum,
org.jdesktop.beansbinding.BeanProperty.create("text"));
binding.setConverter(new SqlDateToStringConverter());
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
+ gridBagConstraints.weightx = 0.5;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10);
pnlGeneralInformation.add(txtLetzteaenderungDatum, gridBagConstraints);
lblGeometrie.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblGeometrie.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 5;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlGeneralInformation.add(lblGeometrie, gridBagConstraints);
if (!readOnly) {
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.geometrie}"),
cmbGeometrie,
org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
binding.setConverter(((DefaultCismapGeometryComboBoxEditor)cmbGeometrie).getConverter());
bindingGroup.addBinding(binding);
}
if (!readOnly) {
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 5;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
+ gridBagConstraints.weightx = 0.5;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10);
pnlGeneralInformation.add(cmbGeometrie, gridBagConstraints);
}
btnCombineGeometries.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/wizard.png"))); // NOI18N
btnCombineGeometries.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnCombineGeometries.text")); // NOI18N
btnCombineGeometries.setToolTipText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnCombineGeometries.toolTipText")); // NOI18N
btnCombineGeometries.setEnabled(false);
btnCombineGeometries.setFocusPainted(false);
btnCombineGeometries.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
btnCombineGeometriesActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 6;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 10, 10);
pnlGeneralInformation.add(btnCombineGeometries, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 7;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 0.1;
pnlGeneralInformation.add(gluGeneralInformationGap, gridBagConstraints);
lblGeometrieStatus.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblGeometrieStatus.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 5;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlGeneralInformation.add(lblGeometrieStatus, gridBagConstraints);
cmbGeometrieStatus.setRenderer(new GeometrieStatusRenderer(cmbGeometrieStatus.getRenderer()));
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.geometrie_status}"),
cmbGeometrieStatus,
org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
bindingGroup.addBinding(binding);
cmbGeometrieStatus.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmbGeometrieStatusActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 5;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
+ gridBagConstraints.weightx = 0.5;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10);
pnlGeneralInformation.add(cmbGeometrieStatus, gridBagConstraints);
lblSchluessel.setLabelFor(cmbSchluessel);
lblSchluessel.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblSchluessel.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(10, 10, 5, 5);
pnlGeneralInformation.add(lblSchluessel, gridBagConstraints);
cmbSchluessel.setModel(new javax.swing.DefaultComboBoxModel(
new String[] { "501", "502", "503", "504", "505", "506", "507", "508", "600", "605" }));
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.schluessel}"),
cmbSchluessel,
org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
- gridBagConstraints.weightx = 0.25;
+ gridBagConstraints.weightx = 0.5;
gridBagConstraints.insets = new java.awt.Insets(10, 5, 5, 5);
pnlGeneralInformation.add(cmbSchluessel, gridBagConstraints);
lblGemarkung.setLabelFor(cmbGemarkung);
lblGemarkung.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblGemarkung.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(10, 5, 5, 5);
pnlGeneralInformation.add(lblGemarkung, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.gemarkung}"),
cmbGemarkung,
org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
- gridBagConstraints.weightx = 0.25;
+ gridBagConstraints.weightx = 0.5;
gridBagConstraints.insets = new java.awt.Insets(10, 5, 5, 10);
pnlGeneralInformation.add(cmbGemarkung, gridBagConstraints);
lblFlur.setLabelFor(txtFlur);
lblFlur.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblFlur.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5);
pnlGeneralInformation.add(lblFlur, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.flur}"),
txtFlur,
org.jdesktop.beansbinding.BeanProperty.create("text"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
+ gridBagConstraints.weightx = 0.5;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlGeneralInformation.add(txtFlur, gridBagConstraints);
lblBlatt.setLabelFor(txtBlatt);
lblBlatt.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblBlatt.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlGeneralInformation.add(lblBlatt, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.blatt}"),
txtBlatt,
org.jdesktop.beansbinding.BeanProperty.create("text"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
+ gridBagConstraints.weightx = 0.5;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10);
pnlGeneralInformation.add(txtBlatt, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.75;
gridBagConstraints.weighty = 0.1;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 5, 5);
pnlContainer.add(pnlGeneralInformation, gridBagConstraints);
pnlLandparcels.setLayout(new java.awt.GridBagLayout());
pnlHeaderLandparcels.setBackground(new java.awt.Color(51, 51, 51));
pnlHeaderLandparcels.setLayout(new java.awt.FlowLayout());
lblHeaderLandparcels.setForeground(new java.awt.Color(255, 255, 255));
lblHeaderLandparcels.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblHeaderLandparcels.text")); // NOI18N
pnlHeaderLandparcels.add(lblHeaderLandparcels);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.1;
pnlLandparcels.add(pnlHeaderLandparcels, gridBagConstraints);
scpLandparcels.setBorder(javax.swing.BorderFactory.createEmptyBorder(10, 10, 10, 10));
scpLandparcels.setMinimumSize(new java.awt.Dimension(266, 138));
scpLandparcels.setOpaque(false);
lstLandparcels.setCellRenderer(new HighlightReferencingFlurstueckeCellRenderer());
final org.jdesktop.beansbinding.ELProperty eLProperty = org.jdesktop.beansbinding.ELProperty.create(
"${cidsBean.flurstuecksvermessung}");
final org.jdesktop.swingbinding.JListBinding jListBinding = org.jdesktop.swingbinding.SwingBindings
.createJListBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
eLProperty,
lstLandparcels);
bindingGroup.addBinding(jListBinding);
lstLandparcels.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked(final java.awt.event.MouseEvent evt) {
lstLandparcelsMouseClicked(evt);
}
});
lstLandparcels.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
@Override
public void valueChanged(final javax.swing.event.ListSelectionEvent evt) {
lstLandparcelsValueChanged(evt);
}
});
scpLandparcels.setViewportView(lstLandparcels);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weighty = 0.1;
pnlLandparcels.add(scpLandparcels, gridBagConstraints);
btnAddLandparcel.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit_add_mini.png"))); // NOI18N
btnAddLandparcel.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnAddLandparcel.text")); // NOI18N
btnAddLandparcel.setToolTipText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnAddLandparcel.toolTipText")); // NOI18N
btnAddLandparcel.setFocusPainted(false);
btnAddLandparcel.setMaximumSize(new java.awt.Dimension(43, 25));
btnAddLandparcel.setMinimumSize(new java.awt.Dimension(43, 25));
btnAddLandparcel.setPreferredSize(new java.awt.Dimension(43, 25));
btnAddLandparcel.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
btnAddLandparcelActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LAST_LINE_END;
gridBagConstraints.weightx = 0.1;
gridBagConstraints.insets = new java.awt.Insets(5, 0, 10, 2);
pnlLandparcels.add(btnAddLandparcel, gridBagConstraints);
btnRemoveLandparcel.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit_remove_mini.png"))); // NOI18N
btnRemoveLandparcel.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnRemoveLandparcel.text")); // NOI18N
btnRemoveLandparcel.setToolTipText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnRemoveLandparcel.toolTipText")); // NOI18N
btnRemoveLandparcel.setEnabled(false);
btnRemoveLandparcel.setFocusPainted(false);
btnRemoveLandparcel.setMaximumSize(new java.awt.Dimension(43, 25));
btnRemoveLandparcel.setMinimumSize(new java.awt.Dimension(43, 25));
btnRemoveLandparcel.setPreferredSize(new java.awt.Dimension(43, 25));
btnRemoveLandparcel.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
btnRemoveLandparcelActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 2, 10, 10);
pnlLandparcels.add(btnRemoveLandparcel, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridheight = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.25;
gridBagConstraints.weighty = 0.1;
gridBagConstraints.insets = new java.awt.Insets(0, 5, 5, 0);
pnlContainer.add(pnlLandparcels, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weighty = 0.1;
add(pnlContainer, gridBagConstraints);
pnlControls.setLayout(new java.awt.GridBagLayout());
bgrControls.add(togPan);
togPan.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/pan.gif"))); // NOI18N
togPan.setSelected(true);
togPan.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.togPan.text")); // NOI18N
togPan.setToolTipText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.togPan.toolTipText")); // NOI18N
togPan.setEnabled(false);
togPan.setFocusPainted(false);
togPan.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
togPan.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
togPanActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(2, 10, 3, 10);
pnlControls.add(togPan, gridBagConstraints);
bgrControls.add(togZoom);
togZoom.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/zoom.gif"))); // NOI18N
togZoom.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.togZoom.text")); // NOI18N
togZoom.setToolTipText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.togZoom.toolTipText")); // NOI18N
togZoom.setEnabled(false);
togZoom.setFocusPainted(false);
togZoom.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
togZoom.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
togZoomActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(2, 10, 3, 10);
pnlControls.add(togZoom, gridBagConstraints);
btnHome.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/home.gif"))); // NOI18N
btnHome.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnHome.text")); // NOI18N
btnHome.setToolTipText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnHome.toolTipText")); // NOI18N
btnHome.setEnabled(false);
btnHome.setFocusPainted(false);
btnHome.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
btnHome.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
btnHomeActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(5, 10, 3, 10);
pnlControls.add(btnHome, gridBagConstraints);
pnlHeaderControls.setBackground(new java.awt.Color(51, 51, 51));
pnlHeaderControls.setLayout(new java.awt.FlowLayout());
lblHeaderControls.setForeground(new java.awt.Color(255, 255, 255));
lblHeaderControls.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblHeaderControls.text")); // NOI18N
pnlHeaderControls.add(lblHeaderControls);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
pnlControls.add(pnlHeaderControls, gridBagConstraints);
btnOpen.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/folder-image.png"))); // NOI18N
btnOpen.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnOpen.text")); // NOI18N
btnOpen.setToolTipText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnOpen.toolTipText")); // NOI18N
btnOpen.setEnabled(false);
btnOpen.setFocusPainted(false);
btnOpen.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
btnOpen.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
btnOpenActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(2, 10, 8, 10);
pnlControls.add(btnOpen, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 0, 0, 5);
add(pnlControls, gridBagConstraints);
pnlDocuments.setLayout(new java.awt.GridBagLayout());
pnlHeaderDocuments.setBackground(new java.awt.Color(51, 51, 51));
pnlHeaderDocuments.setLayout(new java.awt.FlowLayout());
lblHeaderDocuments.setForeground(new java.awt.Color(255, 255, 255));
lblHeaderDocuments.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblHeaderDocuments.text")); // NOI18N
pnlHeaderDocuments.add(lblHeaderDocuments);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 0.1;
pnlDocuments.add(pnlHeaderDocuments, gridBagConstraints);
bgrDocument.add(togBild);
togBild.setSelected(true);
togBild.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.togBild.text")); // NOI18N
togBild.setEnabled(false);
togBild.setFocusPainted(false);
togBild.setMaximumSize(new java.awt.Dimension(49, 32));
togBild.setMinimumSize(new java.awt.Dimension(49, 32));
togBild.setPreferredSize(new java.awt.Dimension(49, 32));
togBild.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
togBildActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(5, 10, 2, 10);
pnlDocuments.add(togBild, gridBagConstraints);
bgrDocument.add(togGrenzniederschrift);
togGrenzniederschrift.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.togGrenzniederschrift.text")); // NOI18N
togGrenzniederschrift.setEnabled(false);
togGrenzniederschrift.setFocusPainted(false);
togGrenzniederschrift.setMaximumSize(new java.awt.Dimension(150, 32));
togGrenzniederschrift.setMinimumSize(new java.awt.Dimension(150, 32));
togGrenzniederschrift.setPreferredSize(new java.awt.Dimension(150, 32));
togGrenzniederschrift.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
togGrenzniederschriftActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(2, 10, 10, 10);
pnlDocuments.add(togGrenzniederschrift, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(10, 0, 5, 5);
add(pnlDocuments, gridBagConstraints);
pnlHeaderPages.setBackground(new java.awt.Color(51, 51, 51));
pnlHeaderPages.setLayout(new java.awt.FlowLayout());
lblHeaderPages.setForeground(new java.awt.Color(255, 255, 255));
lblHeaderPages.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblHeaderPages.text")); // NOI18N
pnlHeaderPages.add(lblHeaderPages);
pnlPages.add(pnlHeaderPages, java.awt.BorderLayout.PAGE_START);
scpPages.setBorder(javax.swing.BorderFactory.createEmptyBorder(10, 10, 10, 10));
scpPages.setMinimumSize(new java.awt.Dimension(31, 75));
scpPages.setOpaque(false);
scpPages.setPreferredSize(new java.awt.Dimension(85, 75));
lstPages.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
lstPages.setEnabled(false);
lstPages.setFixedCellWidth(75);
lstPages.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
@Override
public void valueChanged(final javax.swing.event.ListSelectionEvent evt) {
lstPagesValueChanged(evt);
}
});
scpPages.setViewportView(lstPages);
pnlPages.add(scpPages, java.awt.BorderLayout.CENTER);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 0, 5, 5);
add(pnlPages, gridBagConstraints);
pnlDocument.setLayout(new java.awt.GridBagLayout());
pnlHeaderDocument.setBackground(java.awt.Color.darkGray);
pnlHeaderDocument.setLayout(new java.awt.GridBagLayout());
lblHeaderDocument.setForeground(java.awt.Color.white);
lblHeaderDocument.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblHeaderDocument.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlHeaderDocument.add(lblHeaderDocument, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.1;
pnlDocument.add(pnlHeaderDocument, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 0.1;
pnlDocument.add(measuringComponent, gridBagConstraints);
lblErrorWhileLoadingBild.setBackground(java.awt.Color.white);
lblErrorWhileLoadingBild.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lblErrorWhileLoadingBild.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/missingRasterdocument.png"))); // NOI18N
lblErrorWhileLoadingBild.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblErrorWhileLoadingBild.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 0.1;
pnlDocument.add(lblErrorWhileLoadingBild, gridBagConstraints);
lblErrorWhileLoadingGrenzniederschrift.setBackground(java.awt.Color.white);
lblErrorWhileLoadingGrenzniederschrift.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lblErrorWhileLoadingGrenzniederschrift.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/missingRasterdocument.png"))); // NOI18N
lblErrorWhileLoadingGrenzniederschrift.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblErrorWhileLoadingGrenzniederschrift.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 0.1;
pnlDocument.add(lblErrorWhileLoadingGrenzniederschrift, gridBagConstraints);
lblMissingDocuments.setBackground(java.awt.Color.white);
lblMissingDocuments.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lblMissingDocuments.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/missingRasterdocument.png"))); // NOI18N
lblMissingDocuments.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblMissingDocuments.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 0.1;
pnlDocument.add(lblMissingDocuments, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridheight = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.1;
gridBagConstraints.insets = new java.awt.Insets(10, 5, 0, 0);
add(pnlDocument, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 0.1;
add(gluGapControls, gridBagConstraints);
bindingGroup.bind();
} // </editor-fold>//GEN-END:initComponents
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void togPanActionPerformed(final java.awt.event.ActionEvent evt) { //GEN-FIRST:event_togPanActionPerformed
measuringComponent.actionPan();
} //GEN-LAST:event_togPanActionPerformed
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void togZoomActionPerformed(final java.awt.event.ActionEvent evt) { //GEN-FIRST:event_togZoomActionPerformed
measuringComponent.actionZoom();
} //GEN-LAST:event_togZoomActionPerformed
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void btnHomeActionPerformed(final java.awt.event.ActionEvent evt) { //GEN-FIRST:event_btnHomeActionPerformed
measuringComponent.actionOverview();
} //GEN-LAST:event_btnHomeActionPerformed
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void btnOpenActionPerformed(final java.awt.event.ActionEvent evt) { //GEN-FIRST:event_btnOpenActionPerformed
if (currentDocument != NO_SELECTION) {
final String url = documentURLs[currentDocument].getKey().toExternalForm();
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
if (DownloadManagerDialog.showAskingForUserTitle(VermessungRissEditor.this)) {
final String filename = url.substring(url.lastIndexOf("/") + 1);
DownloadManager.instance()
.add(
new HttpDownload(
documentURLs[currentDocument].getKey(),
"",
DownloadManagerDialog.getJobname(),
(currentDocument == DOCUMENT_BILD) ? "Vermessungsriss"
: "Ergänzende Dokumente",
filename.substring(0, filename.lastIndexOf(".")),
filename.substring(filename.lastIndexOf("."))));
}
}
});
}
} //GEN-LAST:event_btnOpenActionPerformed
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void lstLandparcelsMouseClicked(final java.awt.event.MouseEvent evt) { //GEN-FIRST:event_lstLandparcelsMouseClicked
if (evt.getClickCount() <= 1) {
return;
}
final Object selectedObj = lstLandparcels.getSelectedValue();
if (selectedObj instanceof CidsBean) {
final CidsBean selectedBean = (CidsBean)selectedObj;
if ((selectedBean.getProperty("flurstueck") instanceof CidsBean)
&& (selectedBean.getProperty("flurstueck.flurstueck") instanceof CidsBean)) {
final MetaObject selMO = ((CidsBean)selectedBean.getProperty("flurstueck.flurstueck")).getMetaObject();
ComponentRegistry.getRegistry().getDescriptionPane().gotoMetaObject(selMO, "");
}
}
} //GEN-LAST:event_lstLandparcelsMouseClicked
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void lstPagesValueChanged(final javax.swing.event.ListSelectionEvent evt) { //GEN-FIRST:event_lstPagesValueChanged
if (!evt.getValueIsAdjusting()) {
final Object page = lstPages.getSelectedValue();
if (page instanceof Integer) {
loadPage(((Integer)page) - 1);
}
}
} //GEN-LAST:event_lstPagesValueChanged
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void togBildActionPerformed(final java.awt.event.ActionEvent evt) { //GEN-FIRST:event_togBildActionPerformed
loadBild();
} //GEN-LAST:event_togBildActionPerformed
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void togGrenzniederschriftActionPerformed(final java.awt.event.ActionEvent evt) { //GEN-FIRST:event_togGrenzniederschriftActionPerformed
loadGrenzniederschrift();
} //GEN-LAST:event_togGrenzniederschriftActionPerformed
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void btnAddLandparcelActionPerformed(final java.awt.event.ActionEvent evt) { //GEN-FIRST:event_btnAddLandparcelActionPerformed
flurstueckDialog.setCurrentListToAdd(CidsBeanSupport.getBeanCollectionFromProperty(
cidsBean,
"flurstuecksvermessung"));
StaticSwingTools.showDialog(StaticSwingTools.getParentFrame(this), flurstueckDialog, true);
} //GEN-LAST:event_btnAddLandparcelActionPerformed
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void btnRemoveLandparcelActionPerformed(final java.awt.event.ActionEvent evt) { //GEN-FIRST:event_btnRemoveLandparcelActionPerformed
final Object[] selection = lstLandparcels.getSelectedValues();
if ((selection != null) && (selection.length > 0)) {
final int answer = JOptionPane.showConfirmDialog(
StaticSwingTools.getParentFrame(this),
"Soll das Flurstück wirklich gelöscht werden?",
"Flurstück entfernen",
JOptionPane.YES_NO_OPTION);
if (answer == JOptionPane.YES_OPTION) {
final Collection flurstuecke = CidsBeanSupport.getBeanCollectionFromProperty(
cidsBean,
"flurstuecksvermessung");
if (flurstuecke != null) {
for (final Object flurstueckToRemove : selection) {
try {
flurstuecke.remove(flurstueckToRemove);
} catch (Exception e) {
ObjectRendererUtils.showExceptionWindowToUser("Fehler beim Löschen", e, this);
} finally {
btnCombineGeometries.setEnabled(lstLandparcels.getModel().getSize() > 0);
}
}
}
}
}
} //GEN-LAST:event_btnRemoveLandparcelActionPerformed
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void lstLandparcelsValueChanged(final javax.swing.event.ListSelectionEvent evt) { //GEN-FIRST:event_lstLandparcelsValueChanged
if (!evt.getValueIsAdjusting()) {
btnRemoveLandparcel.setEnabled(!readOnly && (lstLandparcels.getSelectedIndex() > -1));
}
} //GEN-LAST:event_lstLandparcelsValueChanged
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void btnCombineGeometriesActionPerformed(final java.awt.event.ActionEvent evt) { //GEN-FIRST:event_btnCombineGeometriesActionPerformed
if (cidsBean == null) {
return;
}
Geometry union = null;
final Collection<CidsBean> flurstuecksvermessungen = cidsBean.getBeanCollectionProperty(
"flurstuecksvermessung");
for (final CidsBean flurstuecksvermessung : flurstuecksvermessungen) {
if (flurstuecksvermessung.getProperty("flurstueck.flurstueck.umschreibendes_rechteck.geo_field")
instanceof Geometry) {
final Geometry geometry = (Geometry)flurstuecksvermessung.getProperty(
"flurstueck.flurstueck.umschreibendes_rechteck.geo_field");
final Geometry transformedGeometry = CrsTransformer.transformToGivenCrs(
geometry,
AlkisConstants.COMMONS.SRS_SERVICE);
if (union == null) {
union = transformedGeometry;
} else {
union = union.union(transformedGeometry);
}
}
}
if (union == null) {
LOG.warn("Could not find geometries on given landparcels. Did not attach a new geometry.");
JOptionPane.showMessageDialog(
StaticSwingTools.getParentFrame(this),
"Keines der betroffenen Flurstücke weist eine Geometrie auf.",
"Keine Geometrie erstellt",
JOptionPane.WARNING_MESSAGE);
return;
}
final Map<String, Object> properties = new HashMap<String, Object>();
properties.put("geo_field", union);
try {
final CidsBean geomBean = CidsBeanSupport.createNewCidsBeanFromTableName("geom", properties);
geomBean.persist();
cidsBean.setProperty("geometrie", geomBean);
} catch (Exception ex) {
// TODO: Tell user about error.
LOG.error("Could set new geometry: '" + union.toText() + "'.", ex);
}
} //GEN-LAST:event_btnCombineGeometriesActionPerformed
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void cmbGeometrieStatusActionPerformed(final java.awt.event.ActionEvent evt) { //GEN-FIRST:event_cmbGeometrieStatusActionPerformed
if (cmbGeometrieStatus.getSelectedItem() instanceof CidsBean) {
final CidsBean geometrieStatus = (CidsBean)cmbGeometrieStatus.getSelectedItem();
if (geometrieStatus.getProperty("id") instanceof Integer) {
cmbGeometrieStatus.setBackground(COLORS_GEOMETRIE_STATUS.get(
(Integer)geometrieStatus.getProperty("id")));
}
}
} //GEN-LAST:event_cmbGeometrieStatusActionPerformed
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
@Override
public CidsBean getCidsBean() {
return cidsBean;
}
/**
* DOCUMENT ME!
*
* @param cidsBean DOCUMENT ME!
*/
@Override
public void setCidsBean(final CidsBean cidsBean) {
bindingGroup.unbind();
if (cidsBean != null) {
this.cidsBean = cidsBean;
DefaultCustomObjectEditor.setMetaClassInformationToMetaClassStoreComponentsInBindingGroup(
bindingGroup,
this.cidsBean);
bindingGroup.bind();
lblTitle.setText(generateTitle());
btnCombineGeometries.setEnabled(lstLandparcels.getModel().getSize() > 0);
if ((cidsBean.getProperty("geometrie_status") instanceof CidsBean)
&& (cidsBean.getProperty("geometrie_status.id") instanceof Integer)) {
cmbGeometrieStatus.setBackground(COLORS_GEOMETRIE_STATUS.get(
(Integer)cidsBean.getProperty("geometrie_status.id")));
}
schluessel = cidsBean.getProperty("schluessel");
gemarkung = (cidsBean.getProperty("gemarkung") != null) ? cidsBean.getProperty("gemarkung.id") : null;
flur = cidsBean.getProperty("flur");
blatt = cidsBean.getProperty("blatt");
}
setCurrentDocumentNull();
EventQueue.invokeLater(new RefreshDocumentWorker());
}
/**
* DOCUMENT ME!
*/
@Override
public void dispose() {
bindingGroup.unbind();
// dispose panels here if necessary
measuringComponent.dispose();
if (flurstueckDialog != null) {
flurstueckDialog.dispose();
}
if (!readOnly) {
((DefaultCismapGeometryComboBoxEditor)cmbGeometrie).dispose();
}
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
@Override
public JComponent getTitleComponent() {
return pnlTitle;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
@Override
public JComponent getFooterComponent() {
return strFooter;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
@Override
public Border getTitleBorder() {
return new EmptyBorder(10, 10, 10, 10);
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
@Override
public Border getFooterBorder() {
return new EmptyBorder(5, 5, 5, 5);
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
@Override
public Border getCenterrBorder() {
return new EmptyBorder(0, 5, 0, 5);
}
/**
* DOCUMENT ME!
*
* @param event DOCUMENT ME!
*/
@Override
public void editorClosed(final EditorClosedEvent event) {
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
@Override
public boolean prepareForSave() {
boolean save = true;
final StringBuilder errorMessage = new StringBuilder();
if (cmbSchluessel.getSelectedItem() == null) {
LOG.warn("No 'schluessel' specified. Skip persisting.");
errorMessage.append(NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.prepareForSave().noSchluessel"));
}
if (cmbGemarkung.getSelectedItem() == null) {
LOG.warn("No 'gemarkung' specified. Skip persisting.");
errorMessage.append(NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.prepareForSave().noGemarkung"));
}
if ((txtFlur.getText() == null) || txtFlur.getText().trim().isEmpty()) {
LOG.warn("No 'flur' specified. Skip persisting.");
errorMessage.append(NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.prepareForSave().noFlur"));
} else if (txtFlur.getText().length() > 31) {
LOG.warn("Property 'flur' is too long. Skip persisting.");
errorMessage.append(NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.prepareForSave().tooLongFlur"));
}
if ((txtBlatt.getText() == null) || txtBlatt.getText().trim().isEmpty()) {
LOG.warn("No 'blatt' specified. Skip persisting.");
errorMessage.append(NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.prepareForSave().noBlatt"));
} else if (txtBlatt.getText().length() > 31) {
LOG.warn("Property 'blatt' is too long. Skip persisting.");
errorMessage.append(NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.prepareForSave().tooLongBlatt"));
}
if (errorMessage.length() > 0) {
save = false;
JOptionPane.showMessageDialog(
StaticSwingTools.getParentFrame(this),
NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.prepareForSave().JOptionPane.message.prefix")
+ errorMessage.toString()
+ NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.prepareForSave().JOptionPane.message.suffix"),
NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.prepareForSave().JOptionPane.title"),
JOptionPane.WARNING_MESSAGE);
}
final Object newSchluessel = cidsBean.getProperty("schluessel");
final Object newGemarkung = cidsBean.getProperty("gemarkung.id");
final Object newFlur = cidsBean.getProperty("flur");
final Object newBlatt = cidsBean.getProperty("blatt");
final CidsVermessungRissSearchStatement search = new CidsVermessungRissSearchStatement(
newSchluessel.toString(),
newGemarkung.toString(),
newFlur.toString(),
newBlatt.toString(),
null,
null,
null);
final Collection result;
try {
result = SessionManager.getProxy().customServerSearch(SessionManager.getSession().getUser(), search);
} catch (final ConnectionException ex) {
LOG.error("Could not check if the natural key of this measurement sketch is valid.", ex);
JOptionPane.showMessageDialog(
this,
NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.prepareForSave().noConnection.message"),
NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.prepareForSave().noConnection.title"),
JOptionPane.WARNING_MESSAGE);
return false;
}
if ((result != null) && !result.isEmpty()
&& !(newSchluessel.equals(schluessel) && newGemarkung.equals(gemarkung) && newFlur.equals(flur)
&& newBlatt.equals(blatt))) {
save = false;
if (LOG.isDebugEnabled()) {
LOG.debug("The given natural key of the measurement sketch already exists. Skip saving.");
}
JOptionPane.showMessageDialog(
this,
NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.prepareForSave().keyExists.message"),
NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.prepareForSave().keyExists.title"),
JOptionPane.WARNING_MESSAGE);
} else {
save = true;
try {
cidsBean.setProperty("letzteaenderung_datum", new Date(System.currentTimeMillis()));
cidsBean.setProperty("letzteaenderung_name", SessionManager.getSession().getUser().getName());
} catch (final Exception ex) {
LOG.warn("Could not save date and user of last change.", ex);
// TODO: User feedback?
}
}
return save;
}
/**
* DOCUMENT ME!
*
* @param host DOCUMENT ME!
* @param gemarkung DOCUMENT ME!
* @param flur DOCUMENT ME!
* @param schluessel DOCUMENT ME!
* @param blatt DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public static Map<URL, URL> getCorrespondingURLs(final String host,
final Integer gemarkung,
final String flur,
final String schluessel,
final String blatt) {
final Map<URL, URL> validURLs = new HashMap<URL, URL>();
String urlString = null;
try {
urlString = MessageFormat.format(
host,
schluessel,
gemarkung,
flur,
new Integer(Integer.parseInt(blatt)));
} catch (final Exception ex) {
LOG.warn("Can't build a valid URL for current measurement sketch.", ex);
return validURLs;
}
for (final String suffix : SUFFIXES) {
URL urlToTry = null;
URL urlToTryReducedSize = null;
try {
urlToTry = new URL(urlString + '.' + suffix);
} catch (final MalformedURLException ex) {
LOG.warn("The URL '" + urlString.toString() + '.' + suffix
+ "' is malformed. Can't load the corresponding picture.",
ex);
continue;
}
try {
urlToTryReducedSize = new URL(urlString + SUFFIX_REDUCED_SIZE + '.' + suffix);
} catch (final MalformedURLException ex) {
LOG.warn("The URL '" + urlString.toString() + SUFFIX_REDUCED_SIZE + '.' + suffix
+ "' is malformed. Can't load the corresponding picture.",
ex);
}
if (urlToTry != null) {
if (LOG.isDebugEnabled()) {
LOG.debug("URL '" + urlToTry.toExternalForm() + "' is valid.");
}
validURLs.put(urlToTry, null);
}
if (urlToTryReducedSize != null) {
if (LOG.isDebugEnabled()) {
LOG.debug("URL '" + urlToTry.toExternalForm() + "' is valid.");
}
validURLs.put(urlToTry, urlToTryReducedSize);
}
}
return validURLs;
}
/**
* DOCUMENT ME!
*
* @param property DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
protected String getSimplePropertyOfCurrentCidsBean(final String property) {
String result = "";
if (cidsBean != null) {
if (cidsBean.getProperty(property) != null) {
result = (String)cidsBean.getProperty(property).toString();
}
}
return result;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
protected String generateTitle() {
if (cidsBean == null) {
return "Bitte wählen Sie einen Vermessungsriss.";
}
final StringBuilder result = new StringBuilder();
final Object schluessel = cidsBean.getProperty("schluessel");
final Object flur = cidsBean.getProperty("flur");
final Object blatt = cidsBean.getProperty("blatt");
result.append("Schlüssel ");
if ((schluessel instanceof String) && (((String)schluessel).trim().length() > 0)) {
result.append(schluessel);
} else {
result.append("unbekannt");
}
result.append(" - ");
result.append("Gemarkung ");
String gemarkung = "unbekannt";
if ((cidsBean.getProperty("gemarkung") instanceof CidsBean)
&& (cidsBean.getProperty("gemarkung.name") instanceof String)) {
final String gemarkungFromBean = (String)cidsBean.getProperty("gemarkung.name");
if (gemarkungFromBean.trim().length() > 0) {
gemarkung = gemarkungFromBean;
}
}
result.append(gemarkung);
result.append(" - ");
result.append("Flur ");
if ((flur instanceof String) && (((String)flur).trim().length() > 0)) {
result.append(flur);
} else {
result.append("unbekannt");
}
result.append(" - ");
result.append("Blatt ");
if ((blatt instanceof String) && (((String)blatt).trim().length() > 0)) {
result.append(blatt);
} else {
result.append("unbekannt");
}
return result.toString();
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
protected Integer getGemarkungOfCurrentCidsBean() {
Integer result = Integer.valueOf(-1);
if (cidsBean != null) {
if (cidsBean.getProperty("gemarkung") != null) {
final Object gemarkung = cidsBean.getProperty("gemarkung.id");
if (gemarkung instanceof Integer) {
result = (Integer)gemarkung;
}
}
}
return result;
}
/**
* DOCUMENT ME!
*/
protected void loadBild() {
currentSelectedButton = togBild;
currentDocument = DOCUMENT_BILD;
final URL url;
if (documentURLs[currentDocument].getValue() != null) {
url = documentURLs[currentDocument].getValue();
lblHeaderDocument.setText(NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblHeaderDocument.text.vermessungsriss") + " "
+ NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblHeaderDocument.text.suffixWarningReducedSize"));
} else {
url = documentURLs[currentDocument].getKey();
lblHeaderDocument.setText(NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblHeaderDocument.text.vermessungsriss"));
}
EventQueue.invokeLater(new PictureReaderWorker(url));
}
/**
* DOCUMENT ME!
*/
protected void loadGrenzniederschrift() {
currentSelectedButton = togGrenzniederschrift;
currentDocument = DOCUMENT_GRENZNIEDERSCHRIFT;
final URL url;
if (documentURLs[currentDocument].getValue() != null) {
url = documentURLs[currentDocument].getValue();
lblHeaderDocument.setText(NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblHeaderDocument.text.ergaenzendeDokumente") + " "
+ NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblHeaderDocument.text.suffixWarningReducedSize"));
} else {
url = documentURLs[currentDocument].getKey();
lblHeaderDocument.setText(NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblHeaderDocument.text.ergaenzendeDokumente"));
}
EventQueue.invokeLater(new PictureReaderWorker(url));
}
/**
* DOCUMENT ME!
*
* @param page DOCUMENT ME!
*/
protected void loadPage(final int page) {
final PictureSelectWorker oldWorkerTest = currentPictureSelectWorker;
if (oldWorkerTest != null) {
oldWorkerTest.cancel(true);
}
currentPictureSelectWorker = new PictureSelectWorker(page);
EventQueue.invokeLater(currentPictureSelectWorker);
}
/**
* DOCUMENT ME!
*/
protected void setCurrentDocumentNull() {
currentDocument = NO_SELECTION;
setCurrentPageNull();
}
/**
* DOCUMENT ME!
*/
protected void setCurrentPageNull() {
currentPage = NO_SELECTION;
}
/**
* DOCUMENT ME!
*
* @param enabled DOCUMENT ME!
*/
protected void setDocumentControlsEnabled(final boolean enabled) {
for (int i = 0; i < documentURLs.length; i++) {
final JToggleButton current = documentButtons[i];
current.setEnabled((documentURLs[i] != null) && enabled);
}
}
/**
* DOCUMENT ME!
*
* @param errorOccurred DOCUMENT ME!
*/
protected void displayErrorOrEnableControls(final boolean errorOccurred) {
measuringComponent.setVisible(!errorOccurred);
btnHome.setEnabled(!errorOccurred);
btnOpen.setEnabled(!errorOccurred);
togPan.setEnabled(!errorOccurred);
togZoom.setEnabled(!errorOccurred);
lstPages.setEnabled(!errorOccurred);
lblMissingDocuments.setVisible(false);
lblErrorWhileLoadingBild.setVisible(false);
lblErrorWhileLoadingGrenzniederschrift.setVisible(false);
if (errorOccurred) {
lstPages.setModel(new DefaultListModel());
if (currentDocument == DOCUMENT_BILD) {
lblErrorWhileLoadingBild.setVisible(true);
} else if (currentDocument == DOCUMENT_GRENZNIEDERSCHRIFT) {
lblErrorWhileLoadingGrenzniederschrift.setVisible(true);
} else {
lblMissingDocuments.setVisible(true);
}
}
}
/**
* DOCUMENT ME!
*/
protected void closeReader() {
if (pictureReader != null) {
pictureReader.close();
pictureReader = null;
}
}
//~ Inner Classes ----------------------------------------------------------
//J-
//When Wupp decides to publish the correspoding files on a WebDAV server, use following three classes.
/**
* DOCUMENT ME!
*
* @version $Revision$, $Date$
*/
protected final class PictureReaderWorker extends SwingWorker<ListModel, Void> {
//~ Instance fields ----------------------------------------------------
private final URL url;
//~ Constructors -------------------------------------------------------
/**
* Creates a new PictureReaderWorker object.
*
* @param url DOCUMENT ME!
*/
public PictureReaderWorker(final URL url) {
this.url = url;
if (LOG.isDebugEnabled()) {
LOG.debug("Preparing picture reader for file " + this.url.toExternalForm());
}
lstPages.setModel(MODEL_LOAD);
measuringComponent.removeAllFeatures();
setDocumentControlsEnabled(false);
}
//~ Methods ------------------------------------------------------------
@Override
protected ListModel doInBackground() throws Exception {
final DefaultListModel model = new DefaultListModel();
closeReader();
try {
pictureReader = new MultiPagePictureReader(url, false, true);
} catch (final Exception e) {
LOG.error("Could not create a MultiPagePictureReader for URL '" + url.toExternalForm() + "'.", e);
return model;
}
final int numberOfPages = pictureReader.getNumberOfPages();
for (int i = 0; i < numberOfPages; ++i) {
model.addElement(i + 1);
}
return model;
}
@Override
protected void done() {
boolean enableControls = true;
try {
final ListModel model = get();
lstPages.setModel(model);
if (model.getSize() > 0) {
lstPages.setSelectedIndex(0);
enableControls = false;
} else {
lstPages.setModel(new DefaultListModel());
}
} catch (InterruptedException ex) {
setCurrentDocumentNull();
displayErrorOrEnableControls(true);
closeReader();
LOG.warn("Reading found pictures was interrupted.", ex);
} catch (ExecutionException ex) {
setCurrentDocumentNull();
displayErrorOrEnableControls(true);
closeReader();
LOG.error("Could not read found pictures.", ex);
} finally {
// We don't want to enable the controls if we set the selected index in lstPages. Calling
// lstPages.setSelectedIndex(0)
// invokes a PictureSelectWorker and thus disables the controls.
if (enableControls) {
setDocumentControlsEnabled(true);
}
}
}
}
/**
* DOCUMENT ME!
*
* @version $Revision$, $Date$
*/
protected final class PictureSelectWorker extends SwingWorker<BufferedImage, Void> {
//~ Instance fields ----------------------------------------------------
private final int pageNumber;
//~ Constructors -------------------------------------------------------
/**
* Creates a new PictureSelectWorker object.
*
* @param pageNumber DOCUMENT ME!
*/
public PictureSelectWorker(final int pageNumber) {
this.pageNumber = pageNumber;
setCurrentPageNull();
setDocumentControlsEnabled(false);
measuringComponent.reset();
btnHome.setEnabled(false);
btnOpen.setEnabled(false);
togPan.setEnabled(false);
togZoom.setEnabled(false);
lstPages.setEnabled(false);
}
//~ Methods ------------------------------------------------------------
@Override
protected BufferedImage doInBackground() throws Exception {
if (pictureReader != null) {
return pictureReader.loadPage(pageNumber);
}
throw new IllegalStateException("PictureReader is null!");
}
@Override
protected void done() {
try {
if (!isCancelled()) {
currentPage = pageNumber;
measuringComponent.addImage(get());
togPan.setSelected(true);
measuringComponent.zoomToFeatureCollection();
displayErrorOrEnableControls(false);
}
} catch (final InterruptedException ex) {
setCurrentPageNull();
displayErrorOrEnableControls(true);
LOG.warn("Was interrupted while setting new image.", ex);
} catch (final Exception ex) {
setCurrentPageNull();
displayErrorOrEnableControls(true);
LOG.error("Could not set new image.", ex);
} finally {
setDocumentControlsEnabled(true);
currentPictureSelectWorker = null;
}
}
}
/**
* DOCUMENT ME!
*
* @version $Revision$, $Date$
*/
protected final class RefreshDocumentWorker extends SwingWorker<Void, Object> {
//~ Constructors -------------------------------------------------------
/**
* Creates a new RefreshDocumentWorker object.
*/
public RefreshDocumentWorker() {
lblMissingDocuments.setVisible(false);
lblErrorWhileLoadingBild.setVisible(false);
lblErrorWhileLoadingGrenzniederschrift.setVisible(false);
togBild.setEnabled(false);
togGrenzniederschrift.setEnabled(false);
lstPages.setModel(MODEL_LOAD);
btnHome.setEnabled(false);
btnOpen.setEnabled(false);
togPan.setEnabled(false);
togZoom.setEnabled(false);
setCurrentDocumentNull();
}
//~ Methods ------------------------------------------------------------
@Override
protected Void doInBackground() throws Exception {
documentURLs[DOCUMENT_BILD] = null;
documentURLs[DOCUMENT_GRENZNIEDERSCHRIFT] = null;
final CidsBean cidsBean = getCidsBean();
if (cidsBean == null) {
return null;
}
final Map<URL, URL> validBildURLs = getCorrespondingURLs(
AlkisConstants.COMMONS.VERMESSUNG_HOST_BILDER,
getGemarkungOfCurrentCidsBean(),
getSimplePropertyOfCurrentCidsBean("flur"),
getSimplePropertyOfCurrentCidsBean("schluessel"),
getSimplePropertyOfCurrentCidsBean("blatt"));
final Map<URL, URL> validGrenzniederschriftURLs = getCorrespondingURLs(
AlkisConstants.COMMONS.VERMESSUNG_HOST_GRENZNIEDERSCHRIFTEN,
getGemarkungOfCurrentCidsBean(),
getSimplePropertyOfCurrentCidsBean("flur"),
getSimplePropertyOfCurrentCidsBean("schluessel"),
getSimplePropertyOfCurrentCidsBean("blatt"));
tryToLoadImageFromURLs(validBildURLs, DOCUMENT_BILD);
tryToLoadImageFromURLs(validGrenzniederschriftURLs, DOCUMENT_GRENZNIEDERSCHRIFT);
return null;
}
private void tryToLoadImageFromURLs(final Map<URL, URL> urls, final int type) {
InputStream streamToReadFrom = null;
//First we try to load an image of reduced size
for (final Map.Entry<URL, URL> urlEntry : urls.entrySet()) {
if(urlEntry.getValue() == null) {
continue;
}
try {
streamToReadFrom = WebAccessManager.getInstance().doRequest(urlEntry.getValue());
documentURLs[type] = urlEntry;
break;
} catch (final Exception ex) {
LOG.debug("An exception occurred while opening URL '" + urlEntry.getValue().toExternalForm()
+ "'. Skipping this url.", ex);
} finally {
if (streamToReadFrom != null) {
try {
streamToReadFrom.close();
} catch (final IOException ex) {
}
}
}
}
if(documentURLs[type] != null) {
// Found an image.
return;
}
for (final Map.Entry<URL, URL> urlEntry : urls.entrySet()) {
try {
streamToReadFrom = WebAccessManager.getInstance().doRequest(urlEntry.getKey());
documentURLs[type] = urlEntry;
break;
} catch (final Exception ex) {
LOG.debug("An exception occurred while opening URL '" + urlEntry.getKey().toExternalForm()
+ "'. Skipping this url.", ex);
} finally {
if (streamToReadFrom != null) {
try {
streamToReadFrom.close();
} catch (final IOException ex) {
}
}
}
}
if(documentURLs[type] != null) {
documentURLs[type].setValue(null);
}
}
@Override
protected void done() {
try {
if (!isCancelled()) {
get();
}
} catch (InterruptedException ex) {
LOG.warn("Was interrupted while refreshing document.", ex);
} catch (ExecutionException ex) {
LOG.warn("There was an exception while refreshing document.", ex);
}
if ((documentURLs[DOCUMENT_BILD] == null) && (documentURLs[DOCUMENT_GRENZNIEDERSCHRIFT] == null)) {
measuringComponent.setVisible(false);
lblMissingDocuments.setVisible(true);
lstPages.setModel(new DefaultListModel());
lstPages.setEnabled(false);
} else {
if (documentURLs[DOCUMENT_BILD] != null) {
togBild.setEnabled(true);
togBild.setSelected(true);
currentSelectedButton = togBild;
currentDocument = DOCUMENT_BILD;
}
if (documentURLs[DOCUMENT_GRENZNIEDERSCHRIFT] != null) {
togGrenzniederschrift.setEnabled(true);
if (currentDocument == NO_SELECTION) {
togGrenzniederschrift.setSelected(true);
currentSelectedButton = togGrenzniederschrift;
currentDocument = DOCUMENT_GRENZNIEDERSCHRIFT;
}
}
if(currentDocument == DOCUMENT_BILD) {
loadBild();
} else if(currentDocument == DOCUMENT_GRENZNIEDERSCHRIFT) {
loadGrenzniederschrift();
}
}
}
}
//J+
/**
* DOCUMENT ME!
*
* @version $Revision$, $Date$
*/
protected class EnableCombineGeometriesButton extends WindowAdapter {
//~ Methods ------------------------------------------------------------
/**
* DOCUMENT ME!
*
* @param e DOCUMENT ME!
*/
@Override
public void windowDeactivated(final WindowEvent e) {
super.windowDeactivated(e);
btnCombineGeometries.setEnabled(lstLandparcels.getModel().getSize() > 0);
}
/**
* DOCUMENT ME!
*
* @param e DOCUMENT ME!
*/
@Override
public void windowClosed(final WindowEvent e) {
super.windowClosed(e);
btnCombineGeometries.setEnabled(lstLandparcels.getModel().getSize() > 0);
}
}
/**
* DOCUMENT ME!
*
* @version $Revision$, $Date$
*/
protected class HighlightReferencingFlurstueckeCellRenderer extends JLabel implements ListCellRenderer {
//~ Methods ------------------------------------------------------------
/**
* DOCUMENT ME!
*
* @param list DOCUMENT ME!
* @param value DOCUMENT ME!
* @param index DOCUMENT ME!
* @param isSelected DOCUMENT ME!
* @param cellHasFocus DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
@Override
public Component getListCellRendererComponent(final JList list,
final Object value,
final int index,
final boolean isSelected,
final boolean cellHasFocus) {
setOpaque(true);
if (isSelected) {
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
} else {
setBackground(list.getBackground());
setForeground(list.getForeground());
}
final String errorWhileLoading = "Fehler beim Laden des Flurstücks";
final StringBuilder result = new StringBuilder();
if (value instanceof CidsBean) {
final CidsBean vermessung = (CidsBean)value;
if (vermessung.getProperty("flurstueck") instanceof CidsBean) {
final CidsBean flurstueck = (CidsBean)vermessung.getProperty("flurstueck");
if (flurstueck.getProperty("gemarkung") != null) {
final Object gemarkung = flurstueck.getProperty("gemarkung.name");
if ((gemarkung instanceof String) && (((String)gemarkung).trim().length() > 0)) {
result.append(gemarkung);
} else {
result.append(flurstueck.getProperty("gemarkung.id"));
}
} else {
result.append("Unbekannte Gemarkung");
}
result.append("-");
result.append(flurstueck.getProperty("flur"));
result.append("-");
result.append(flurstueck.getProperty("zaehler"));
final Object nenner = flurstueck.getProperty("nenner");
result.append('/');
if (nenner != null) {
result.append(nenner);
} else {
result.append('0');
}
if (flurstueck.getProperty("flurstueck") instanceof CidsBean) {
if (isSelected) {
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
} else {
setBackground(list.getBackground());
setForeground(Color.blue);
}
}
} else {
result.append(errorWhileLoading);
}
if (vermessung.getProperty("veraenderungsart") != null) {
result.append(" (");
final Object vermessungsart = vermessung.getProperty("veraenderungsart.name");
if ((vermessungsart instanceof String) && (((String)vermessungsart).trim().length() > 0)) {
result.append(vermessungsart);
} else {
result.append(vermessung.getProperty("veraenderungsart.code"));
}
result.append(')');
}
} else {
result.append(errorWhileLoading);
}
setText(result.toString());
return this;
}
}
/**
* DOCUMENT ME!
*
* @version $Revision$, $Date$
*/
protected class GeometrieStatusRenderer implements ListCellRenderer {
//~ Instance fields ----------------------------------------------------
private ListCellRenderer originalRenderer;
//~ Constructors -------------------------------------------------------
/**
* Creates a new GeometrieStatusRenderer object.
*
* @param originalRenderer DOCUMENT ME!
*/
public GeometrieStatusRenderer(final ListCellRenderer originalRenderer) {
this.originalRenderer = originalRenderer;
}
//~ Methods ------------------------------------------------------------
/**
* DOCUMENT ME!
*
* @param list DOCUMENT ME!
* @param value DOCUMENT ME!
* @param index DOCUMENT ME!
* @param isSelected DOCUMENT ME!
* @param cellHasFocus DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
@Override
public Component getListCellRendererComponent(final JList list,
final Object value,
final int index,
final boolean isSelected,
final boolean cellHasFocus) {
final Component result = originalRenderer.getListCellRendererComponent(
list,
value,
index,
isSelected,
cellHasFocus);
if (isSelected) {
result.setBackground(list.getSelectionBackground());
result.setForeground(list.getSelectionForeground());
} else {
result.setBackground(list.getBackground());
result.setForeground(list.getForeground());
if (value instanceof CidsBean) {
final CidsBean geometrieStatus = (CidsBean)value;
if (geometrieStatus.getProperty("id") instanceof Integer) {
result.setBackground(COLORS_GEOMETRIE_STATUS.get((Integer)geometrieStatus.getProperty("id")));
}
}
}
return result;
}
}
//J-
private final class DocumentSizeFilter extends DocumentFilter {
@Override
public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
if ((fb.getDocument().getLength() + string.length()) <= 31) {
super.insertString(fb, offset, string, attr);
}
}
@Override
public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
if ((fb.getDocument().getLength() + text.length() - length) <= 31) {
super.replace(fb, offset, length, text, attrs);
}
}
}
//J+
}
| false | true | private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
bindingGroup = new org.jdesktop.beansbinding.BindingGroup();
strFooter = new javax.swing.Box.Filler(new java.awt.Dimension(0, 22),
new java.awt.Dimension(0, 22),
new java.awt.Dimension(32767, 22));
pnlTitle = new javax.swing.JPanel();
lblTitle = new javax.swing.JLabel();
bgrControls = new javax.swing.ButtonGroup();
bgrDocument = new javax.swing.ButtonGroup();
ifrWarningReducedSize = new javax.swing.JInternalFrame();
lblWarningReducedSize = new javax.swing.JLabel();
pnlContainer = new javax.swing.JPanel();
pnlGeneralInformation = new de.cismet.tools.gui.RoundedPanel();
pnlHeaderGeneralInformation = new de.cismet.tools.gui.SemiRoundedPanel();
lblGeneralInformation = new javax.swing.JLabel();
lblJahr = new javax.swing.JLabel();
txtJahr = new javax.swing.JTextField();
lblFormat = new javax.swing.JLabel();
cmbFormat = new DefaultBindableReferenceCombo();
lblLetzteAenderungName = new javax.swing.JLabel();
txtLetzteaenderungName = new javax.swing.JTextField();
lblLetzteAenderungDatum = new javax.swing.JLabel();
txtLetzteaenderungDatum = new javax.swing.JTextField();
lblGeometrie = new javax.swing.JLabel();
if (!readOnly) {
cmbGeometrie = new DefaultCismapGeometryComboBoxEditor();
}
btnCombineGeometries = new javax.swing.JButton();
gluGeneralInformationGap = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0),
new java.awt.Dimension(0, 0),
new java.awt.Dimension(0, 32767));
lblGeometrieStatus = new javax.swing.JLabel();
cmbGeometrieStatus = new DefaultBindableReferenceCombo();
lblSchluessel = new javax.swing.JLabel();
cmbSchluessel = new javax.swing.JComboBox();
lblGemarkung = new javax.swing.JLabel();
cmbGemarkung = new DefaultBindableReferenceCombo();
lblFlur = new javax.swing.JLabel();
txtFlur = new javax.swing.JTextField();
lblBlatt = new javax.swing.JLabel();
txtBlatt = new javax.swing.JTextField();
pnlLandparcels = new de.cismet.tools.gui.RoundedPanel();
pnlHeaderLandparcels = new de.cismet.tools.gui.SemiRoundedPanel();
lblHeaderLandparcels = new javax.swing.JLabel();
scpLandparcels = new javax.swing.JScrollPane();
lstLandparcels = new javax.swing.JList();
btnAddLandparcel = new javax.swing.JButton();
btnRemoveLandparcel = new javax.swing.JButton();
pnlControls = new de.cismet.tools.gui.RoundedPanel();
togPan = new javax.swing.JToggleButton();
togZoom = new javax.swing.JToggleButton();
btnHome = new javax.swing.JButton();
pnlHeaderControls = new de.cismet.tools.gui.SemiRoundedPanel();
lblHeaderControls = new javax.swing.JLabel();
btnOpen = new javax.swing.JButton();
pnlDocuments = new de.cismet.tools.gui.RoundedPanel();
pnlHeaderDocuments = new de.cismet.tools.gui.SemiRoundedPanel();
lblHeaderDocuments = new javax.swing.JLabel();
togBild = new javax.swing.JToggleButton();
togGrenzniederschrift = new javax.swing.JToggleButton();
pnlPages = new de.cismet.tools.gui.RoundedPanel();
pnlHeaderPages = new de.cismet.tools.gui.SemiRoundedPanel();
lblHeaderPages = new javax.swing.JLabel();
scpPages = new javax.swing.JScrollPane();
lstPages = new javax.swing.JList();
pnlDocument = new de.cismet.tools.gui.RoundedPanel();
pnlHeaderDocument = new de.cismet.tools.gui.SemiRoundedPanel();
lblHeaderDocument = new javax.swing.JLabel();
measuringComponent = new MeasuringComponent(INITIAL_BOUNDINGBOX, CRS);
lblErrorWhileLoadingBild = new javax.swing.JLabel();
lblErrorWhileLoadingGrenzniederschrift = new javax.swing.JLabel();
lblMissingDocuments = new javax.swing.JLabel();
gluGapControls = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0),
new java.awt.Dimension(0, 0),
new java.awt.Dimension(0, 32767));
pnlTitle.setOpaque(false);
pnlTitle.setLayout(new java.awt.GridBagLayout());
lblTitle.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
lblTitle.setForeground(java.awt.Color.white);
lblTitle.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblTitle.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.1;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlTitle.add(lblTitle, gridBagConstraints);
ifrWarningReducedSize.setResizable(true);
ifrWarningReducedSize.setVisible(true);
lblWarningReducedSize.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/warningReducedSize.png"))); // NOI18N
lblWarningReducedSize.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblWarningReducedSize.text")); // NOI18N
ifrWarningReducedSize.getContentPane().add(lblWarningReducedSize, java.awt.BorderLayout.CENTER);
setLayout(new java.awt.GridBagLayout());
pnlContainer.setOpaque(false);
pnlContainer.setLayout(new java.awt.GridBagLayout());
pnlGeneralInformation.setLayout(new java.awt.GridBagLayout());
pnlHeaderGeneralInformation.setBackground(new java.awt.Color(51, 51, 51));
pnlHeaderGeneralInformation.setLayout(new java.awt.FlowLayout());
lblGeneralInformation.setForeground(new java.awt.Color(255, 255, 255));
lblGeneralInformation.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblGeneralInformation.text")); // NOI18N
pnlHeaderGeneralInformation.add(lblGeneralInformation);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 0.1;
pnlGeneralInformation.add(pnlHeaderGeneralInformation, gridBagConstraints);
lblJahr.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblJahr.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5);
pnlGeneralInformation.add(lblJahr, gridBagConstraints);
org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.jahr}"),
txtJahr,
org.jdesktop.beansbinding.BeanProperty.create("text"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 7);
pnlGeneralInformation.add(txtJahr, gridBagConstraints);
lblFormat.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblFormat.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5);
pnlGeneralInformation.add(lblFormat, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.format}"),
cmbFormat,
org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 7);
pnlGeneralInformation.add(cmbFormat, gridBagConstraints);
lblLetzteAenderungName.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblLetzteAenderungName.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 7, 5, 5);
pnlGeneralInformation.add(lblLetzteAenderungName, gridBagConstraints);
txtLetzteaenderungName.setEditable(false);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.letzteaenderung_name}"),
txtLetzteaenderungName,
org.jdesktop.beansbinding.BeanProperty.create("text"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10);
pnlGeneralInformation.add(txtLetzteaenderungName, gridBagConstraints);
lblLetzteAenderungDatum.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblLetzteAenderungDatum.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 7, 5, 5);
pnlGeneralInformation.add(lblLetzteAenderungDatum, gridBagConstraints);
txtLetzteaenderungDatum.setEditable(false);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.letzteaenderung_datum}"),
txtLetzteaenderungDatum,
org.jdesktop.beansbinding.BeanProperty.create("text"));
binding.setConverter(new SqlDateToStringConverter());
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10);
pnlGeneralInformation.add(txtLetzteaenderungDatum, gridBagConstraints);
lblGeometrie.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblGeometrie.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 5;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlGeneralInformation.add(lblGeometrie, gridBagConstraints);
if (!readOnly) {
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.geometrie}"),
cmbGeometrie,
org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
binding.setConverter(((DefaultCismapGeometryComboBoxEditor)cmbGeometrie).getConverter());
bindingGroup.addBinding(binding);
}
if (!readOnly) {
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 5;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10);
pnlGeneralInformation.add(cmbGeometrie, gridBagConstraints);
}
btnCombineGeometries.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/wizard.png"))); // NOI18N
btnCombineGeometries.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnCombineGeometries.text")); // NOI18N
btnCombineGeometries.setToolTipText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnCombineGeometries.toolTipText")); // NOI18N
btnCombineGeometries.setEnabled(false);
btnCombineGeometries.setFocusPainted(false);
btnCombineGeometries.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
btnCombineGeometriesActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 6;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 10, 10);
pnlGeneralInformation.add(btnCombineGeometries, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 7;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 0.1;
pnlGeneralInformation.add(gluGeneralInformationGap, gridBagConstraints);
lblGeometrieStatus.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblGeometrieStatus.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 5;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlGeneralInformation.add(lblGeometrieStatus, gridBagConstraints);
cmbGeometrieStatus.setRenderer(new GeometrieStatusRenderer(cmbGeometrieStatus.getRenderer()));
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.geometrie_status}"),
cmbGeometrieStatus,
org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
bindingGroup.addBinding(binding);
cmbGeometrieStatus.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmbGeometrieStatusActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 5;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10);
pnlGeneralInformation.add(cmbGeometrieStatus, gridBagConstraints);
lblSchluessel.setLabelFor(cmbSchluessel);
lblSchluessel.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblSchluessel.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(10, 10, 5, 5);
pnlGeneralInformation.add(lblSchluessel, gridBagConstraints);
cmbSchluessel.setModel(new javax.swing.DefaultComboBoxModel(
new String[] { "501", "502", "503", "504", "505", "506", "507", "508", "600", "605" }));
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.schluessel}"),
cmbSchluessel,
org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.25;
gridBagConstraints.insets = new java.awt.Insets(10, 5, 5, 5);
pnlGeneralInformation.add(cmbSchluessel, gridBagConstraints);
lblGemarkung.setLabelFor(cmbGemarkung);
lblGemarkung.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblGemarkung.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(10, 5, 5, 5);
pnlGeneralInformation.add(lblGemarkung, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.gemarkung}"),
cmbGemarkung,
org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.25;
gridBagConstraints.insets = new java.awt.Insets(10, 5, 5, 10);
pnlGeneralInformation.add(cmbGemarkung, gridBagConstraints);
lblFlur.setLabelFor(txtFlur);
lblFlur.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblFlur.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5);
pnlGeneralInformation.add(lblFlur, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.flur}"),
txtFlur,
org.jdesktop.beansbinding.BeanProperty.create("text"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlGeneralInformation.add(txtFlur, gridBagConstraints);
lblBlatt.setLabelFor(txtBlatt);
lblBlatt.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblBlatt.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlGeneralInformation.add(lblBlatt, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.blatt}"),
txtBlatt,
org.jdesktop.beansbinding.BeanProperty.create("text"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10);
pnlGeneralInformation.add(txtBlatt, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.75;
gridBagConstraints.weighty = 0.1;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 5, 5);
pnlContainer.add(pnlGeneralInformation, gridBagConstraints);
pnlLandparcels.setLayout(new java.awt.GridBagLayout());
pnlHeaderLandparcels.setBackground(new java.awt.Color(51, 51, 51));
pnlHeaderLandparcels.setLayout(new java.awt.FlowLayout());
lblHeaderLandparcels.setForeground(new java.awt.Color(255, 255, 255));
lblHeaderLandparcels.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblHeaderLandparcels.text")); // NOI18N
pnlHeaderLandparcels.add(lblHeaderLandparcels);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.1;
pnlLandparcels.add(pnlHeaderLandparcels, gridBagConstraints);
scpLandparcels.setBorder(javax.swing.BorderFactory.createEmptyBorder(10, 10, 10, 10));
scpLandparcels.setMinimumSize(new java.awt.Dimension(266, 138));
scpLandparcels.setOpaque(false);
lstLandparcels.setCellRenderer(new HighlightReferencingFlurstueckeCellRenderer());
final org.jdesktop.beansbinding.ELProperty eLProperty = org.jdesktop.beansbinding.ELProperty.create(
"${cidsBean.flurstuecksvermessung}");
final org.jdesktop.swingbinding.JListBinding jListBinding = org.jdesktop.swingbinding.SwingBindings
.createJListBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
eLProperty,
lstLandparcels);
bindingGroup.addBinding(jListBinding);
lstLandparcels.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked(final java.awt.event.MouseEvent evt) {
lstLandparcelsMouseClicked(evt);
}
});
lstLandparcels.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
@Override
public void valueChanged(final javax.swing.event.ListSelectionEvent evt) {
lstLandparcelsValueChanged(evt);
}
});
scpLandparcels.setViewportView(lstLandparcels);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weighty = 0.1;
pnlLandparcels.add(scpLandparcels, gridBagConstraints);
btnAddLandparcel.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit_add_mini.png"))); // NOI18N
btnAddLandparcel.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnAddLandparcel.text")); // NOI18N
btnAddLandparcel.setToolTipText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnAddLandparcel.toolTipText")); // NOI18N
btnAddLandparcel.setFocusPainted(false);
btnAddLandparcel.setMaximumSize(new java.awt.Dimension(43, 25));
btnAddLandparcel.setMinimumSize(new java.awt.Dimension(43, 25));
btnAddLandparcel.setPreferredSize(new java.awt.Dimension(43, 25));
btnAddLandparcel.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
btnAddLandparcelActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LAST_LINE_END;
gridBagConstraints.weightx = 0.1;
gridBagConstraints.insets = new java.awt.Insets(5, 0, 10, 2);
pnlLandparcels.add(btnAddLandparcel, gridBagConstraints);
btnRemoveLandparcel.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit_remove_mini.png"))); // NOI18N
btnRemoveLandparcel.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnRemoveLandparcel.text")); // NOI18N
btnRemoveLandparcel.setToolTipText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnRemoveLandparcel.toolTipText")); // NOI18N
btnRemoveLandparcel.setEnabled(false);
btnRemoveLandparcel.setFocusPainted(false);
btnRemoveLandparcel.setMaximumSize(new java.awt.Dimension(43, 25));
btnRemoveLandparcel.setMinimumSize(new java.awt.Dimension(43, 25));
btnRemoveLandparcel.setPreferredSize(new java.awt.Dimension(43, 25));
btnRemoveLandparcel.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
btnRemoveLandparcelActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 2, 10, 10);
pnlLandparcels.add(btnRemoveLandparcel, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridheight = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.25;
gridBagConstraints.weighty = 0.1;
gridBagConstraints.insets = new java.awt.Insets(0, 5, 5, 0);
pnlContainer.add(pnlLandparcels, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weighty = 0.1;
add(pnlContainer, gridBagConstraints);
pnlControls.setLayout(new java.awt.GridBagLayout());
bgrControls.add(togPan);
togPan.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/pan.gif"))); // NOI18N
togPan.setSelected(true);
togPan.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.togPan.text")); // NOI18N
togPan.setToolTipText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.togPan.toolTipText")); // NOI18N
togPan.setEnabled(false);
togPan.setFocusPainted(false);
togPan.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
togPan.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
togPanActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(2, 10, 3, 10);
pnlControls.add(togPan, gridBagConstraints);
bgrControls.add(togZoom);
togZoom.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/zoom.gif"))); // NOI18N
togZoom.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.togZoom.text")); // NOI18N
togZoom.setToolTipText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.togZoom.toolTipText")); // NOI18N
togZoom.setEnabled(false);
togZoom.setFocusPainted(false);
togZoom.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
togZoom.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
togZoomActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(2, 10, 3, 10);
pnlControls.add(togZoom, gridBagConstraints);
btnHome.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/home.gif"))); // NOI18N
btnHome.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnHome.text")); // NOI18N
btnHome.setToolTipText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnHome.toolTipText")); // NOI18N
btnHome.setEnabled(false);
btnHome.setFocusPainted(false);
btnHome.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
btnHome.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
btnHomeActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(5, 10, 3, 10);
pnlControls.add(btnHome, gridBagConstraints);
pnlHeaderControls.setBackground(new java.awt.Color(51, 51, 51));
pnlHeaderControls.setLayout(new java.awt.FlowLayout());
lblHeaderControls.setForeground(new java.awt.Color(255, 255, 255));
lblHeaderControls.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblHeaderControls.text")); // NOI18N
pnlHeaderControls.add(lblHeaderControls);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
pnlControls.add(pnlHeaderControls, gridBagConstraints);
btnOpen.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/folder-image.png"))); // NOI18N
btnOpen.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnOpen.text")); // NOI18N
btnOpen.setToolTipText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnOpen.toolTipText")); // NOI18N
btnOpen.setEnabled(false);
btnOpen.setFocusPainted(false);
btnOpen.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
btnOpen.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
btnOpenActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(2, 10, 8, 10);
pnlControls.add(btnOpen, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 0, 0, 5);
add(pnlControls, gridBagConstraints);
pnlDocuments.setLayout(new java.awt.GridBagLayout());
pnlHeaderDocuments.setBackground(new java.awt.Color(51, 51, 51));
pnlHeaderDocuments.setLayout(new java.awt.FlowLayout());
lblHeaderDocuments.setForeground(new java.awt.Color(255, 255, 255));
lblHeaderDocuments.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblHeaderDocuments.text")); // NOI18N
pnlHeaderDocuments.add(lblHeaderDocuments);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 0.1;
pnlDocuments.add(pnlHeaderDocuments, gridBagConstraints);
bgrDocument.add(togBild);
togBild.setSelected(true);
togBild.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.togBild.text")); // NOI18N
togBild.setEnabled(false);
togBild.setFocusPainted(false);
togBild.setMaximumSize(new java.awt.Dimension(49, 32));
togBild.setMinimumSize(new java.awt.Dimension(49, 32));
togBild.setPreferredSize(new java.awt.Dimension(49, 32));
togBild.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
togBildActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(5, 10, 2, 10);
pnlDocuments.add(togBild, gridBagConstraints);
bgrDocument.add(togGrenzniederschrift);
togGrenzniederschrift.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.togGrenzniederschrift.text")); // NOI18N
togGrenzniederschrift.setEnabled(false);
togGrenzniederschrift.setFocusPainted(false);
togGrenzniederschrift.setMaximumSize(new java.awt.Dimension(150, 32));
togGrenzniederschrift.setMinimumSize(new java.awt.Dimension(150, 32));
togGrenzniederschrift.setPreferredSize(new java.awt.Dimension(150, 32));
togGrenzniederschrift.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
togGrenzniederschriftActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(2, 10, 10, 10);
pnlDocuments.add(togGrenzniederschrift, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(10, 0, 5, 5);
add(pnlDocuments, gridBagConstraints);
pnlHeaderPages.setBackground(new java.awt.Color(51, 51, 51));
pnlHeaderPages.setLayout(new java.awt.FlowLayout());
lblHeaderPages.setForeground(new java.awt.Color(255, 255, 255));
lblHeaderPages.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblHeaderPages.text")); // NOI18N
pnlHeaderPages.add(lblHeaderPages);
pnlPages.add(pnlHeaderPages, java.awt.BorderLayout.PAGE_START);
scpPages.setBorder(javax.swing.BorderFactory.createEmptyBorder(10, 10, 10, 10));
scpPages.setMinimumSize(new java.awt.Dimension(31, 75));
scpPages.setOpaque(false);
scpPages.setPreferredSize(new java.awt.Dimension(85, 75));
lstPages.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
lstPages.setEnabled(false);
lstPages.setFixedCellWidth(75);
lstPages.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
@Override
public void valueChanged(final javax.swing.event.ListSelectionEvent evt) {
lstPagesValueChanged(evt);
}
});
scpPages.setViewportView(lstPages);
pnlPages.add(scpPages, java.awt.BorderLayout.CENTER);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 0, 5, 5);
add(pnlPages, gridBagConstraints);
pnlDocument.setLayout(new java.awt.GridBagLayout());
pnlHeaderDocument.setBackground(java.awt.Color.darkGray);
pnlHeaderDocument.setLayout(new java.awt.GridBagLayout());
lblHeaderDocument.setForeground(java.awt.Color.white);
lblHeaderDocument.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblHeaderDocument.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlHeaderDocument.add(lblHeaderDocument, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.1;
pnlDocument.add(pnlHeaderDocument, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 0.1;
pnlDocument.add(measuringComponent, gridBagConstraints);
lblErrorWhileLoadingBild.setBackground(java.awt.Color.white);
lblErrorWhileLoadingBild.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lblErrorWhileLoadingBild.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/missingRasterdocument.png"))); // NOI18N
lblErrorWhileLoadingBild.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblErrorWhileLoadingBild.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 0.1;
pnlDocument.add(lblErrorWhileLoadingBild, gridBagConstraints);
lblErrorWhileLoadingGrenzniederschrift.setBackground(java.awt.Color.white);
lblErrorWhileLoadingGrenzniederschrift.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lblErrorWhileLoadingGrenzniederschrift.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/missingRasterdocument.png"))); // NOI18N
lblErrorWhileLoadingGrenzniederschrift.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblErrorWhileLoadingGrenzniederschrift.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 0.1;
pnlDocument.add(lblErrorWhileLoadingGrenzniederschrift, gridBagConstraints);
lblMissingDocuments.setBackground(java.awt.Color.white);
lblMissingDocuments.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lblMissingDocuments.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/missingRasterdocument.png"))); // NOI18N
lblMissingDocuments.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblMissingDocuments.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 0.1;
pnlDocument.add(lblMissingDocuments, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridheight = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.1;
gridBagConstraints.insets = new java.awt.Insets(10, 5, 0, 0);
add(pnlDocument, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 0.1;
add(gluGapControls, gridBagConstraints);
bindingGroup.bind();
} // </editor-fold>//GEN-END:initComponents
| private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
bindingGroup = new org.jdesktop.beansbinding.BindingGroup();
strFooter = new javax.swing.Box.Filler(new java.awt.Dimension(0, 22),
new java.awt.Dimension(0, 22),
new java.awt.Dimension(32767, 22));
pnlTitle = new javax.swing.JPanel();
lblTitle = new javax.swing.JLabel();
bgrControls = new javax.swing.ButtonGroup();
bgrDocument = new javax.swing.ButtonGroup();
ifrWarningReducedSize = new javax.swing.JInternalFrame();
lblWarningReducedSize = new javax.swing.JLabel();
pnlContainer = new javax.swing.JPanel();
pnlGeneralInformation = new de.cismet.tools.gui.RoundedPanel();
pnlHeaderGeneralInformation = new de.cismet.tools.gui.SemiRoundedPanel();
lblGeneralInformation = new javax.swing.JLabel();
lblJahr = new javax.swing.JLabel();
txtJahr = new javax.swing.JTextField();
lblFormat = new javax.swing.JLabel();
cmbFormat = new DefaultBindableReferenceCombo();
lblLetzteAenderungName = new javax.swing.JLabel();
txtLetzteaenderungName = new javax.swing.JTextField();
lblLetzteAenderungDatum = new javax.swing.JLabel();
txtLetzteaenderungDatum = new javax.swing.JTextField();
lblGeometrie = new javax.swing.JLabel();
if (!readOnly) {
cmbGeometrie = new DefaultCismapGeometryComboBoxEditor();
}
btnCombineGeometries = new javax.swing.JButton();
gluGeneralInformationGap = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0),
new java.awt.Dimension(0, 0),
new java.awt.Dimension(0, 32767));
lblGeometrieStatus = new javax.swing.JLabel();
cmbGeometrieStatus = new DefaultBindableReferenceCombo();
lblSchluessel = new javax.swing.JLabel();
cmbSchluessel = new javax.swing.JComboBox();
lblGemarkung = new javax.swing.JLabel();
cmbGemarkung = new DefaultBindableReferenceCombo();
lblFlur = new javax.swing.JLabel();
txtFlur = new javax.swing.JTextField();
lblBlatt = new javax.swing.JLabel();
txtBlatt = new javax.swing.JTextField();
pnlLandparcels = new de.cismet.tools.gui.RoundedPanel();
pnlHeaderLandparcels = new de.cismet.tools.gui.SemiRoundedPanel();
lblHeaderLandparcels = new javax.swing.JLabel();
scpLandparcels = new javax.swing.JScrollPane();
lstLandparcels = new javax.swing.JList();
btnAddLandparcel = new javax.swing.JButton();
btnRemoveLandparcel = new javax.swing.JButton();
pnlControls = new de.cismet.tools.gui.RoundedPanel();
togPan = new javax.swing.JToggleButton();
togZoom = new javax.swing.JToggleButton();
btnHome = new javax.swing.JButton();
pnlHeaderControls = new de.cismet.tools.gui.SemiRoundedPanel();
lblHeaderControls = new javax.swing.JLabel();
btnOpen = new javax.swing.JButton();
pnlDocuments = new de.cismet.tools.gui.RoundedPanel();
pnlHeaderDocuments = new de.cismet.tools.gui.SemiRoundedPanel();
lblHeaderDocuments = new javax.swing.JLabel();
togBild = new javax.swing.JToggleButton();
togGrenzniederschrift = new javax.swing.JToggleButton();
pnlPages = new de.cismet.tools.gui.RoundedPanel();
pnlHeaderPages = new de.cismet.tools.gui.SemiRoundedPanel();
lblHeaderPages = new javax.swing.JLabel();
scpPages = new javax.swing.JScrollPane();
lstPages = new javax.swing.JList();
pnlDocument = new de.cismet.tools.gui.RoundedPanel();
pnlHeaderDocument = new de.cismet.tools.gui.SemiRoundedPanel();
lblHeaderDocument = new javax.swing.JLabel();
measuringComponent = new MeasuringComponent(INITIAL_BOUNDINGBOX, CRS);
lblErrorWhileLoadingBild = new javax.swing.JLabel();
lblErrorWhileLoadingGrenzniederschrift = new javax.swing.JLabel();
lblMissingDocuments = new javax.swing.JLabel();
gluGapControls = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0),
new java.awt.Dimension(0, 0),
new java.awt.Dimension(0, 32767));
pnlTitle.setOpaque(false);
pnlTitle.setLayout(new java.awt.GridBagLayout());
lblTitle.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
lblTitle.setForeground(java.awt.Color.white);
lblTitle.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblTitle.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.1;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlTitle.add(lblTitle, gridBagConstraints);
ifrWarningReducedSize.setResizable(true);
ifrWarningReducedSize.setVisible(true);
lblWarningReducedSize.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/warningReducedSize.png"))); // NOI18N
lblWarningReducedSize.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblWarningReducedSize.text")); // NOI18N
ifrWarningReducedSize.getContentPane().add(lblWarningReducedSize, java.awt.BorderLayout.CENTER);
setLayout(new java.awt.GridBagLayout());
pnlContainer.setOpaque(false);
pnlContainer.setLayout(new java.awt.GridBagLayout());
pnlGeneralInformation.setLayout(new java.awt.GridBagLayout());
pnlHeaderGeneralInformation.setBackground(new java.awt.Color(51, 51, 51));
pnlHeaderGeneralInformation.setLayout(new java.awt.FlowLayout());
lblGeneralInformation.setForeground(new java.awt.Color(255, 255, 255));
lblGeneralInformation.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblGeneralInformation.text")); // NOI18N
pnlHeaderGeneralInformation.add(lblGeneralInformation);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 0.1;
pnlGeneralInformation.add(pnlHeaderGeneralInformation, gridBagConstraints);
lblJahr.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblJahr.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5);
pnlGeneralInformation.add(lblJahr, gridBagConstraints);
org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.jahr}"),
txtJahr,
org.jdesktop.beansbinding.BeanProperty.create("text"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.5;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 7);
pnlGeneralInformation.add(txtJahr, gridBagConstraints);
lblFormat.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblFormat.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5);
pnlGeneralInformation.add(lblFormat, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.format}"),
cmbFormat,
org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
gridBagConstraints.weightx = 0.5;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 7);
pnlGeneralInformation.add(cmbFormat, gridBagConstraints);
lblLetzteAenderungName.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblLetzteAenderungName.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 7, 5, 5);
pnlGeneralInformation.add(lblLetzteAenderungName, gridBagConstraints);
txtLetzteaenderungName.setEditable(false);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.letzteaenderung_name}"),
txtLetzteaenderungName,
org.jdesktop.beansbinding.BeanProperty.create("text"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.5;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10);
pnlGeneralInformation.add(txtLetzteaenderungName, gridBagConstraints);
lblLetzteAenderungDatum.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblLetzteAenderungDatum.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 7, 5, 5);
pnlGeneralInformation.add(lblLetzteAenderungDatum, gridBagConstraints);
txtLetzteaenderungDatum.setEditable(false);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.letzteaenderung_datum}"),
txtLetzteaenderungDatum,
org.jdesktop.beansbinding.BeanProperty.create("text"));
binding.setConverter(new SqlDateToStringConverter());
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.5;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10);
pnlGeneralInformation.add(txtLetzteaenderungDatum, gridBagConstraints);
lblGeometrie.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblGeometrie.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 5;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlGeneralInformation.add(lblGeometrie, gridBagConstraints);
if (!readOnly) {
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.geometrie}"),
cmbGeometrie,
org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
binding.setConverter(((DefaultCismapGeometryComboBoxEditor)cmbGeometrie).getConverter());
bindingGroup.addBinding(binding);
}
if (!readOnly) {
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 5;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
gridBagConstraints.weightx = 0.5;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10);
pnlGeneralInformation.add(cmbGeometrie, gridBagConstraints);
}
btnCombineGeometries.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/wizard.png"))); // NOI18N
btnCombineGeometries.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnCombineGeometries.text")); // NOI18N
btnCombineGeometries.setToolTipText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnCombineGeometries.toolTipText")); // NOI18N
btnCombineGeometries.setEnabled(false);
btnCombineGeometries.setFocusPainted(false);
btnCombineGeometries.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
btnCombineGeometriesActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 6;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 10, 10);
pnlGeneralInformation.add(btnCombineGeometries, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 7;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 0.1;
pnlGeneralInformation.add(gluGeneralInformationGap, gridBagConstraints);
lblGeometrieStatus.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblGeometrieStatus.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 5;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlGeneralInformation.add(lblGeometrieStatus, gridBagConstraints);
cmbGeometrieStatus.setRenderer(new GeometrieStatusRenderer(cmbGeometrieStatus.getRenderer()));
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.geometrie_status}"),
cmbGeometrieStatus,
org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
bindingGroup.addBinding(binding);
cmbGeometrieStatus.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmbGeometrieStatusActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 5;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
gridBagConstraints.weightx = 0.5;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10);
pnlGeneralInformation.add(cmbGeometrieStatus, gridBagConstraints);
lblSchluessel.setLabelFor(cmbSchluessel);
lblSchluessel.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblSchluessel.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(10, 10, 5, 5);
pnlGeneralInformation.add(lblSchluessel, gridBagConstraints);
cmbSchluessel.setModel(new javax.swing.DefaultComboBoxModel(
new String[] { "501", "502", "503", "504", "505", "506", "507", "508", "600", "605" }));
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.schluessel}"),
cmbSchluessel,
org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.5;
gridBagConstraints.insets = new java.awt.Insets(10, 5, 5, 5);
pnlGeneralInformation.add(cmbSchluessel, gridBagConstraints);
lblGemarkung.setLabelFor(cmbGemarkung);
lblGemarkung.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblGemarkung.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(10, 5, 5, 5);
pnlGeneralInformation.add(lblGemarkung, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.gemarkung}"),
cmbGemarkung,
org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.5;
gridBagConstraints.insets = new java.awt.Insets(10, 5, 5, 10);
pnlGeneralInformation.add(cmbGemarkung, gridBagConstraints);
lblFlur.setLabelFor(txtFlur);
lblFlur.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblFlur.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5);
pnlGeneralInformation.add(lblFlur, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.flur}"),
txtFlur,
org.jdesktop.beansbinding.BeanProperty.create("text"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.5;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlGeneralInformation.add(txtFlur, gridBagConstraints);
lblBlatt.setLabelFor(txtBlatt);
lblBlatt.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblBlatt.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlGeneralInformation.add(lblBlatt, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.blatt}"),
txtBlatt,
org.jdesktop.beansbinding.BeanProperty.create("text"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.5;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10);
pnlGeneralInformation.add(txtBlatt, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.75;
gridBagConstraints.weighty = 0.1;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 5, 5);
pnlContainer.add(pnlGeneralInformation, gridBagConstraints);
pnlLandparcels.setLayout(new java.awt.GridBagLayout());
pnlHeaderLandparcels.setBackground(new java.awt.Color(51, 51, 51));
pnlHeaderLandparcels.setLayout(new java.awt.FlowLayout());
lblHeaderLandparcels.setForeground(new java.awt.Color(255, 255, 255));
lblHeaderLandparcels.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblHeaderLandparcels.text")); // NOI18N
pnlHeaderLandparcels.add(lblHeaderLandparcels);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.1;
pnlLandparcels.add(pnlHeaderLandparcels, gridBagConstraints);
scpLandparcels.setBorder(javax.swing.BorderFactory.createEmptyBorder(10, 10, 10, 10));
scpLandparcels.setMinimumSize(new java.awt.Dimension(266, 138));
scpLandparcels.setOpaque(false);
lstLandparcels.setCellRenderer(new HighlightReferencingFlurstueckeCellRenderer());
final org.jdesktop.beansbinding.ELProperty eLProperty = org.jdesktop.beansbinding.ELProperty.create(
"${cidsBean.flurstuecksvermessung}");
final org.jdesktop.swingbinding.JListBinding jListBinding = org.jdesktop.swingbinding.SwingBindings
.createJListBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
eLProperty,
lstLandparcels);
bindingGroup.addBinding(jListBinding);
lstLandparcels.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked(final java.awt.event.MouseEvent evt) {
lstLandparcelsMouseClicked(evt);
}
});
lstLandparcels.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
@Override
public void valueChanged(final javax.swing.event.ListSelectionEvent evt) {
lstLandparcelsValueChanged(evt);
}
});
scpLandparcels.setViewportView(lstLandparcels);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weighty = 0.1;
pnlLandparcels.add(scpLandparcels, gridBagConstraints);
btnAddLandparcel.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit_add_mini.png"))); // NOI18N
btnAddLandparcel.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnAddLandparcel.text")); // NOI18N
btnAddLandparcel.setToolTipText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnAddLandparcel.toolTipText")); // NOI18N
btnAddLandparcel.setFocusPainted(false);
btnAddLandparcel.setMaximumSize(new java.awt.Dimension(43, 25));
btnAddLandparcel.setMinimumSize(new java.awt.Dimension(43, 25));
btnAddLandparcel.setPreferredSize(new java.awt.Dimension(43, 25));
btnAddLandparcel.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
btnAddLandparcelActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LAST_LINE_END;
gridBagConstraints.weightx = 0.1;
gridBagConstraints.insets = new java.awt.Insets(5, 0, 10, 2);
pnlLandparcels.add(btnAddLandparcel, gridBagConstraints);
btnRemoveLandparcel.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit_remove_mini.png"))); // NOI18N
btnRemoveLandparcel.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnRemoveLandparcel.text")); // NOI18N
btnRemoveLandparcel.setToolTipText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnRemoveLandparcel.toolTipText")); // NOI18N
btnRemoveLandparcel.setEnabled(false);
btnRemoveLandparcel.setFocusPainted(false);
btnRemoveLandparcel.setMaximumSize(new java.awt.Dimension(43, 25));
btnRemoveLandparcel.setMinimumSize(new java.awt.Dimension(43, 25));
btnRemoveLandparcel.setPreferredSize(new java.awt.Dimension(43, 25));
btnRemoveLandparcel.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
btnRemoveLandparcelActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 2, 10, 10);
pnlLandparcels.add(btnRemoveLandparcel, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridheight = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.25;
gridBagConstraints.weighty = 0.1;
gridBagConstraints.insets = new java.awt.Insets(0, 5, 5, 0);
pnlContainer.add(pnlLandparcels, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weighty = 0.1;
add(pnlContainer, gridBagConstraints);
pnlControls.setLayout(new java.awt.GridBagLayout());
bgrControls.add(togPan);
togPan.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/pan.gif"))); // NOI18N
togPan.setSelected(true);
togPan.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.togPan.text")); // NOI18N
togPan.setToolTipText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.togPan.toolTipText")); // NOI18N
togPan.setEnabled(false);
togPan.setFocusPainted(false);
togPan.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
togPan.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
togPanActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(2, 10, 3, 10);
pnlControls.add(togPan, gridBagConstraints);
bgrControls.add(togZoom);
togZoom.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/zoom.gif"))); // NOI18N
togZoom.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.togZoom.text")); // NOI18N
togZoom.setToolTipText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.togZoom.toolTipText")); // NOI18N
togZoom.setEnabled(false);
togZoom.setFocusPainted(false);
togZoom.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
togZoom.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
togZoomActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(2, 10, 3, 10);
pnlControls.add(togZoom, gridBagConstraints);
btnHome.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/home.gif"))); // NOI18N
btnHome.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnHome.text")); // NOI18N
btnHome.setToolTipText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnHome.toolTipText")); // NOI18N
btnHome.setEnabled(false);
btnHome.setFocusPainted(false);
btnHome.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
btnHome.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
btnHomeActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(5, 10, 3, 10);
pnlControls.add(btnHome, gridBagConstraints);
pnlHeaderControls.setBackground(new java.awt.Color(51, 51, 51));
pnlHeaderControls.setLayout(new java.awt.FlowLayout());
lblHeaderControls.setForeground(new java.awt.Color(255, 255, 255));
lblHeaderControls.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblHeaderControls.text")); // NOI18N
pnlHeaderControls.add(lblHeaderControls);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
pnlControls.add(pnlHeaderControls, gridBagConstraints);
btnOpen.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/folder-image.png"))); // NOI18N
btnOpen.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnOpen.text")); // NOI18N
btnOpen.setToolTipText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnOpen.toolTipText")); // NOI18N
btnOpen.setEnabled(false);
btnOpen.setFocusPainted(false);
btnOpen.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
btnOpen.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
btnOpenActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(2, 10, 8, 10);
pnlControls.add(btnOpen, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 0, 0, 5);
add(pnlControls, gridBagConstraints);
pnlDocuments.setLayout(new java.awt.GridBagLayout());
pnlHeaderDocuments.setBackground(new java.awt.Color(51, 51, 51));
pnlHeaderDocuments.setLayout(new java.awt.FlowLayout());
lblHeaderDocuments.setForeground(new java.awt.Color(255, 255, 255));
lblHeaderDocuments.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblHeaderDocuments.text")); // NOI18N
pnlHeaderDocuments.add(lblHeaderDocuments);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 0.1;
pnlDocuments.add(pnlHeaderDocuments, gridBagConstraints);
bgrDocument.add(togBild);
togBild.setSelected(true);
togBild.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.togBild.text")); // NOI18N
togBild.setEnabled(false);
togBild.setFocusPainted(false);
togBild.setMaximumSize(new java.awt.Dimension(49, 32));
togBild.setMinimumSize(new java.awt.Dimension(49, 32));
togBild.setPreferredSize(new java.awt.Dimension(49, 32));
togBild.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
togBildActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(5, 10, 2, 10);
pnlDocuments.add(togBild, gridBagConstraints);
bgrDocument.add(togGrenzniederschrift);
togGrenzniederschrift.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.togGrenzniederschrift.text")); // NOI18N
togGrenzniederschrift.setEnabled(false);
togGrenzniederschrift.setFocusPainted(false);
togGrenzniederschrift.setMaximumSize(new java.awt.Dimension(150, 32));
togGrenzniederschrift.setMinimumSize(new java.awt.Dimension(150, 32));
togGrenzniederschrift.setPreferredSize(new java.awt.Dimension(150, 32));
togGrenzniederschrift.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
togGrenzniederschriftActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(2, 10, 10, 10);
pnlDocuments.add(togGrenzniederschrift, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(10, 0, 5, 5);
add(pnlDocuments, gridBagConstraints);
pnlHeaderPages.setBackground(new java.awt.Color(51, 51, 51));
pnlHeaderPages.setLayout(new java.awt.FlowLayout());
lblHeaderPages.setForeground(new java.awt.Color(255, 255, 255));
lblHeaderPages.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblHeaderPages.text")); // NOI18N
pnlHeaderPages.add(lblHeaderPages);
pnlPages.add(pnlHeaderPages, java.awt.BorderLayout.PAGE_START);
scpPages.setBorder(javax.swing.BorderFactory.createEmptyBorder(10, 10, 10, 10));
scpPages.setMinimumSize(new java.awt.Dimension(31, 75));
scpPages.setOpaque(false);
scpPages.setPreferredSize(new java.awt.Dimension(85, 75));
lstPages.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
lstPages.setEnabled(false);
lstPages.setFixedCellWidth(75);
lstPages.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
@Override
public void valueChanged(final javax.swing.event.ListSelectionEvent evt) {
lstPagesValueChanged(evt);
}
});
scpPages.setViewportView(lstPages);
pnlPages.add(scpPages, java.awt.BorderLayout.CENTER);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 0, 5, 5);
add(pnlPages, gridBagConstraints);
pnlDocument.setLayout(new java.awt.GridBagLayout());
pnlHeaderDocument.setBackground(java.awt.Color.darkGray);
pnlHeaderDocument.setLayout(new java.awt.GridBagLayout());
lblHeaderDocument.setForeground(java.awt.Color.white);
lblHeaderDocument.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblHeaderDocument.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlHeaderDocument.add(lblHeaderDocument, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.1;
pnlDocument.add(pnlHeaderDocument, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 0.1;
pnlDocument.add(measuringComponent, gridBagConstraints);
lblErrorWhileLoadingBild.setBackground(java.awt.Color.white);
lblErrorWhileLoadingBild.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lblErrorWhileLoadingBild.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/missingRasterdocument.png"))); // NOI18N
lblErrorWhileLoadingBild.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblErrorWhileLoadingBild.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 0.1;
pnlDocument.add(lblErrorWhileLoadingBild, gridBagConstraints);
lblErrorWhileLoadingGrenzniederschrift.setBackground(java.awt.Color.white);
lblErrorWhileLoadingGrenzniederschrift.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lblErrorWhileLoadingGrenzniederschrift.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/missingRasterdocument.png"))); // NOI18N
lblErrorWhileLoadingGrenzniederschrift.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblErrorWhileLoadingGrenzniederschrift.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 0.1;
pnlDocument.add(lblErrorWhileLoadingGrenzniederschrift, gridBagConstraints);
lblMissingDocuments.setBackground(java.awt.Color.white);
lblMissingDocuments.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lblMissingDocuments.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/missingRasterdocument.png"))); // NOI18N
lblMissingDocuments.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblMissingDocuments.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 0.1;
pnlDocument.add(lblMissingDocuments, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridheight = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.1;
gridBagConstraints.insets = new java.awt.Insets(10, 5, 0, 0);
add(pnlDocument, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 0.1;
add(gluGapControls, gridBagConstraints);
bindingGroup.bind();
} // </editor-fold>//GEN-END:initComponents
|
diff --git a/trunk/java/com/xerox/amazonws/sdb/SimpleDB.java b/trunk/java/com/xerox/amazonws/sdb/SimpleDB.java
index 201ac5d..577fcaa 100755
--- a/trunk/java/com/xerox/amazonws/sdb/SimpleDB.java
+++ b/trunk/java/com/xerox/amazonws/sdb/SimpleDB.java
@@ -1,229 +1,229 @@
//
// typica - A client library for Amazon Web Services
// Copyright (C) 2007 Xerox Corporation
//
// 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.xerox.amazonws.sdb;
import java.io.InputStream;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.JAXBException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import com.xerox.amazonws.common.AWSQueryConnection;
import com.xerox.amazonws.typica.sdb.jaxb.CreateDomainResponse;
import com.xerox.amazonws.typica.sdb.jaxb.DeleteDomainResponse;
import com.xerox.amazonws.typica.sdb.jaxb.ListDomainsResponse;
/**
* This class provides an interface with the Amazon SDB service. It provides high level
* methods for listing and creating and deleting domains.
*
* @author D. Kavanagh
* @author [email protected]
*/
public class SimpleDB extends AWSQueryConnection {
private static Log logger = LogFactory.getLog(SimpleDB.class);
/**
* Initializes the sdb service with your AWS login information.
*
* @param awsAccessId The your user key into AWS
* @param awsSecretKey The secret string used to generate signatures for authentication.
*/
public SimpleDB(String awsAccessId, String awsSecretAccessKey) {
this(awsAccessId, awsSecretAccessKey, true);
}
/**
* Initializes the sdb service with your AWS login information.
*
* @param awsAccessId The your user key into AWS
* @param awsSecretKey The secret string used to generate signatures for authentication.
* @param isSecure True if the data should be encrypted on the wire on the way to or from SDB.
*/
public SimpleDB(String awsAccessId, String awsSecretAccessKey, boolean isSecure) {
this(awsAccessId, awsSecretAccessKey, isSecure, "sds.amazonaws.com");
}
/**
* Initializes the sdb service with your AWS login information.
*
* @param awsAccessId The your user key into AWS
* @param awsSecretKey The secret string used to generate signatures for authentication.
* @param isSecure True if the data should be encrypted on the wire on the way to or from SDB.
* @param server Which host to connect to. Usually, this will be s3.amazonaws.com
*/
public SimpleDB(String awsAccessId, String awsSecretAccessKey, boolean isSecure,
String server)
{
this(awsAccessId, awsSecretAccessKey, isSecure, server,
isSecure ? 443 : 80);
}
/**
* Initializes the sdb service with your AWS login information.
*
* @param awsAccessId The your user key into AWS
* @param awsSecretKey The secret string used to generate signatures for authentication.
* @param isSecure True if the data should be encrypted on the wire on the way to or from SDB.
* @param server Which host to connect to. Usually, this will be s3.amazonaws.com
* @param port Which port to use.
*/
public SimpleDB(String awsAccessKeyId, String awsSecretAccessKey, boolean isSecure,
String server, int port)
{
super(awsAccessKeyId, awsSecretAccessKey, isSecure, server, port);
ArrayList vals = new ArrayList();
vals.add("2007-11-07");
super.headers.put("Version", vals);
}
/**
* Terminates a selection of running instances.
*
* @return A list of {@link Domain} instances.
* @throws SDBException wraps checked exceptions
*/
public ListDomainsResult listDomains() throws SDBException {
return this.listDomains(null);
}
/**
* Terminates a selection of running instances.
*
* @param instanceIds A list of instances ({@link ReservationDescription.Instance#instanceId}.
* @return A list of {@link Domain} instances.
* @throws SDBException wraps checked exceptions
*/
public ListDomainsResult listDomains(String nextToken) throws SDBException {
return this.listDomains(nextToken, 0);
}
/**
* Creates a domain. If domain already exists, no error is thrown.
*
* @param name name of the new domain
* @throws SDBException wraps checked exceptions
*/
public Domain createDomain(String name) throws SDBException {
Map<String, String> params = new HashMap<String, String>();
params.put("DomainName", name);
GetMethod method = new GetMethod();
try {
CreateDomainResponse response =
makeRequest(method, "CreateDomain", params, CreateDomainResponse.class);
return new Domain(name, getAwsAccessKeyId(), getSecretAccessKey(),
isSecure(), getServer());
} catch (JAXBException ex) {
throw new SDBException("Problem parsing returned message.", ex);
} catch (HttpException ex) {
throw new SDBException(ex.getMessage(), ex);
} catch (IOException ex) {
throw new SDBException(ex.getMessage(), ex);
} finally {
method.releaseConnection();
}
}
/**
* Deletes a domain.
*
* @param domain the domain to be deleted
* @throws SDBException wraps checked exceptions
*/
public void deleteDomain(Domain domain) throws SDBException {
deleteDomain(domain.getName());
}
/**
* Deletes a domain.
*
* @param name the name of the domain to be deleted
* @throws SDBException wraps checked exceptions
*/
public void deleteDomain(String name) throws SDBException {
Map<String, String> params = new HashMap<String, String>();
params.put("DomainName", name);
GetMethod method = new GetMethod();
try {
DeleteDomainResponse response =
makeRequest(method, "DeleteDomain", params, DeleteDomainResponse.class);
} catch (JAXBException ex) {
throw new SDBException("Problem parsing returned message.", ex);
} catch (HttpException ex) {
throw new SDBException(ex.getMessage(), ex);
} catch (IOException ex) {
throw new SDBException(ex.getMessage(), ex);
} finally {
method.releaseConnection();
}
}
/**
* Method for getting a Domain object without getting a list of them.
*
* @param domainName the name of the domain to be returned
* @throws SDBException wraps checked exceptions
*/
public Domain getDomain(String domainName) throws SDBException {
return new Domain(domainName, getAwsAccessKeyId(), getSecretAccessKey(),
isSecure(), getServer());
}
/**
* Gets a list of domains
*
* @param nextToken token to use when retrieving next results
* @param maxResults the max number of results to return (0 means no max defined)
* @throws SDBException wraps checked exceptions
*/
public ListDomainsResult listDomains(String nextToken, int maxResults) throws SDBException {
Map<String, String> params = new HashMap<String, String>();
if (nextToken != null) {
params.put("NextToken", nextToken);
}
if (maxResults > 0) {
- params.put("MaxResults", ""+maxResults);
+ params.put("MaxNumberOfDomains", ""+maxResults);
}
GetMethod method = new GetMethod();
try {
ListDomainsResponse response =
makeRequest(method, "ListDomains", params, ListDomainsResponse.class);
return new ListDomainsResult(response.getListDomainsResult().getNextToken(),
Domain.createList(response.getListDomainsResult().getDomainNames().toArray(new String[] {}),
getAwsAccessKeyId(), getSecretAccessKey(),
isSecure(), getServer()));
} catch (JAXBException ex) {
throw new SDBException("Problem parsing returned message.", ex);
} catch (HttpException ex) {
throw new SDBException(ex.getMessage(), ex);
} catch (IOException ex) {
throw new SDBException(ex.getMessage(), ex);
} finally {
method.releaseConnection();
}
}
}
| true | true | public ListDomainsResult listDomains(String nextToken, int maxResults) throws SDBException {
Map<String, String> params = new HashMap<String, String>();
if (nextToken != null) {
params.put("NextToken", nextToken);
}
if (maxResults > 0) {
params.put("MaxResults", ""+maxResults);
}
GetMethod method = new GetMethod();
try {
ListDomainsResponse response =
makeRequest(method, "ListDomains", params, ListDomainsResponse.class);
return new ListDomainsResult(response.getListDomainsResult().getNextToken(),
Domain.createList(response.getListDomainsResult().getDomainNames().toArray(new String[] {}),
getAwsAccessKeyId(), getSecretAccessKey(),
isSecure(), getServer()));
} catch (JAXBException ex) {
throw new SDBException("Problem parsing returned message.", ex);
} catch (HttpException ex) {
throw new SDBException(ex.getMessage(), ex);
} catch (IOException ex) {
throw new SDBException(ex.getMessage(), ex);
} finally {
method.releaseConnection();
}
}
| public ListDomainsResult listDomains(String nextToken, int maxResults) throws SDBException {
Map<String, String> params = new HashMap<String, String>();
if (nextToken != null) {
params.put("NextToken", nextToken);
}
if (maxResults > 0) {
params.put("MaxNumberOfDomains", ""+maxResults);
}
GetMethod method = new GetMethod();
try {
ListDomainsResponse response =
makeRequest(method, "ListDomains", params, ListDomainsResponse.class);
return new ListDomainsResult(response.getListDomainsResult().getNextToken(),
Domain.createList(response.getListDomainsResult().getDomainNames().toArray(new String[] {}),
getAwsAccessKeyId(), getSecretAccessKey(),
isSecure(), getServer()));
} catch (JAXBException ex) {
throw new SDBException("Problem parsing returned message.", ex);
} catch (HttpException ex) {
throw new SDBException(ex.getMessage(), ex);
} catch (IOException ex) {
throw new SDBException(ex.getMessage(), ex);
} finally {
method.releaseConnection();
}
}
|
diff --git a/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleEmitter.java b/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleEmitter.java
index 9690b8cef..0b2029028 100644
--- a/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleEmitter.java
+++ b/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleEmitter.java
@@ -1,1298 +1,1294 @@
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.graphics.g2d;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Writer;
import java.util.BitSet;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.utils.BooleanArray;
// BOZO - Javadoc.
// BOZO - Add a duplicate emitter button.
public class ParticleEmitter {
static private final int UPDATE_SCALE = 1 << 0;
static private final int UPDATE_ANGLE = 1 << 1;
static private final int UPDATE_ROTATION = 1 << 2;
static private final int UPDATE_VELOCITY = 1 << 3;
static private final int UPDATE_WIND = 1 << 4;
static private final int UPDATE_GRAVITY = 1 << 5;
static private final int UPDATE_TINT = 1 << 6;
private RangedNumericValue delayValue = new RangedNumericValue();
private ScaledNumericValue lifeOffsetValue = new ScaledNumericValue();
private RangedNumericValue durationValue = new RangedNumericValue();
private ScaledNumericValue lifeValue = new ScaledNumericValue();
private ScaledNumericValue emissionValue = new ScaledNumericValue();
private ScaledNumericValue scaleValue = new ScaledNumericValue();
private ScaledNumericValue rotationValue = new ScaledNumericValue();
private ScaledNumericValue velocityValue = new ScaledNumericValue();
private ScaledNumericValue angleValue = new ScaledNumericValue();
private ScaledNumericValue windValue = new ScaledNumericValue();
private ScaledNumericValue gravityValue = new ScaledNumericValue();
private ScaledNumericValue transparencyValue = new ScaledNumericValue();
private GradientColorValue tintValue = new GradientColorValue();
private RangedNumericValue xOffsetValue = new ScaledNumericValue();
private RangedNumericValue yOffsetValue = new ScaledNumericValue();
private ScaledNumericValue spawnWidthValue = new ScaledNumericValue();
private ScaledNumericValue spawnHeightValue = new ScaledNumericValue();
private SpawnShapeValue spawnShapeValue = new SpawnShapeValue();
private float accumulator;
private Sprite sprite;
private Particle[] particles;
private int minParticleCount, maxParticleCount = 4;
private float x, y;
private String name;
private String imagePath;
private int activeCount;
private boolean[] active;
private boolean firstUpdate;
private boolean flipX, flipY;
private int updateFlags;
private boolean allowCompletion;
private int emission, emissionDiff, emissionDelta;
private int lifeOffset, lifeOffsetDiff;
private int life, lifeDiff;
private float spawnWidth, spawnWidthDiff;
private float spawnHeight, spawnHeightDiff;
public float duration = 1, durationTimer;
private float delay, delayTimer;
private boolean attached;
private boolean continuous;
private boolean aligned;
private boolean behind;
private boolean additive = true;
public ParticleEmitter () {
initialize();
}
public ParticleEmitter (BufferedReader reader) throws IOException {
initialize();
load(reader);
}
public ParticleEmitter (ParticleEmitter emitter) {
sprite = emitter.sprite;
name = emitter.name;
setMaxParticleCount(emitter.maxParticleCount);
minParticleCount = emitter.minParticleCount;
delayValue.load(emitter.delayValue);
durationValue.load(emitter.durationValue);
emissionValue.load(emitter.emissionValue);
lifeValue.load(emitter.lifeValue);
lifeOffsetValue.load(emitter.lifeOffsetValue);
scaleValue.load(emitter.scaleValue);
rotationValue.load(emitter.rotationValue);
velocityValue.load(emitter.velocityValue);
angleValue.load(emitter.angleValue);
windValue.load(emitter.windValue);
gravityValue.load(emitter.gravityValue);
transparencyValue.load(emitter.transparencyValue);
tintValue.load(emitter.tintValue);
xOffsetValue.load(emitter.xOffsetValue);
yOffsetValue.load(emitter.yOffsetValue);
spawnWidthValue.load(emitter.spawnWidthValue);
spawnHeightValue.load(emitter.spawnHeightValue);
spawnShapeValue.load(emitter.spawnShapeValue);
attached = emitter.attached;
continuous = emitter.continuous;
aligned = emitter.aligned;
behind = emitter.behind;
additive = emitter.additive;
}
private void initialize () {
durationValue.setAlwaysActive(true);
emissionValue.setAlwaysActive(true);
lifeValue.setAlwaysActive(true);
scaleValue.setAlwaysActive(true);
transparencyValue.setAlwaysActive(true);
spawnShapeValue.setAlwaysActive(true);
spawnWidthValue.setAlwaysActive(true);
spawnHeightValue.setAlwaysActive(true);
}
public void setMaxParticleCount (int maxParticleCount) {
this.maxParticleCount = maxParticleCount;
active = new boolean[maxParticleCount];
activeCount = 0;
particles = new Particle[maxParticleCount];
}
public void addParticle () {
int activeCount = this.activeCount;
if (activeCount == maxParticleCount) return;
boolean[] active = this.active;
for (int i = 0, n = active.length; i < n; i++) {
if (!active[i]) {
activateParticle(i);
active[i] = true;
this.activeCount = activeCount + 1;
break;
}
}
}
public void addParticles (int count) {
count = Math.min(count, maxParticleCount - activeCount);
if (count == 0) return;
boolean[] active = this.active;
int index = 0, n = active.length;
outer:
for (int i = 0; i < count; i++) {
for (; index < n; index++) {
if (!active[index]) {
activateParticle(index);
active[index++] = true;
continue outer;
}
}
break;
}
this.activeCount += count;
}
public void update (float delta) {
accumulator += Math.min(delta * 1000, 250);
if (accumulator < 1) return;
int deltaMillis = (int)accumulator;
accumulator -= deltaMillis;
boolean[] active = this.active;
int activeCount = this.activeCount;
for (int i = 0, n = active.length; i < n; i++) {
if (active[i] && !updateParticle(particles[i], delta, deltaMillis)) {
active[i] = false;
activeCount--;
}
}
this.activeCount = activeCount;
if (delayTimer < delay) {
delayTimer += deltaMillis;
return;
}
if (firstUpdate) {
firstUpdate = false;
addParticle();
}
if (durationTimer < duration)
durationTimer += deltaMillis;
else {
if (!continuous || allowCompletion) return;
restart();
}
emissionDelta += deltaMillis;
float emissionTime = emission + emissionDiff * emissionValue.getScale(durationTimer / (float)duration);
if (emissionTime > 0) {
emissionTime = 1000 / emissionTime;
if (emissionDelta >= emissionTime) {
int emitCount = (int)(emissionDelta / emissionTime);
emitCount = Math.min(emitCount, maxParticleCount - activeCount);
emissionDelta -= emitCount * emissionTime;
emissionDelta %= emissionTime;
addParticles(emitCount);
}
}
if (activeCount < minParticleCount) addParticles(minParticleCount - activeCount);
}
public void draw (SpriteBatch spriteBatch) {
if (additive) spriteBatch.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE);
Particle[] particles = this.particles;
boolean[] active = this.active;
int activeCount = this.activeCount;
for (int i = 0, n = active.length; i < n; i++)
if (active[i]) particles[i].draw(spriteBatch);
this.activeCount = activeCount;
if (additive) spriteBatch.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
}
/** Updates and draws the particles. This is slightly more efficient than calling {@link #update(float)} and
* {@link #draw(SpriteBatch)} separately. */
public void draw (SpriteBatch spriteBatch, float delta) {
accumulator += Math.min(delta * 1000, 250);
if (accumulator < 1) {
draw(spriteBatch);
return;
}
int deltaMillis = (int)accumulator;
accumulator -= deltaMillis;
if (additive) spriteBatch.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE);
Particle[] particles = this.particles;
boolean[] active = this.active;
int activeCount = this.activeCount;
for (int i = 0, n = active.length; i < n; i++) {
if (active[i]) {
Particle particle = particles[i];
if (updateParticle(particle, delta, deltaMillis))
particle.draw(spriteBatch);
else {
active[i] = false;
activeCount--;
}
}
}
this.activeCount = activeCount;
if (additive) spriteBatch.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
if (delayTimer < delay) {
delayTimer += deltaMillis;
return;
}
if (firstUpdate) {
firstUpdate = false;
addParticle();
}
if (durationTimer < duration)
durationTimer += deltaMillis;
else {
if (!continuous || allowCompletion) return;
restart();
}
emissionDelta += deltaMillis;
float emissionTime = emission + emissionDiff * emissionValue.getScale(durationTimer / (float)duration);
if (emissionTime > 0) {
emissionTime = 1000 / emissionTime;
if (emissionDelta >= emissionTime) {
int emitCount = (int)(emissionDelta / emissionTime);
emitCount = Math.min(emitCount, maxParticleCount - activeCount);
emissionDelta -= emitCount * emissionTime;
emissionDelta %= emissionTime;
addParticles(emitCount);
}
}
if (activeCount < minParticleCount) addParticles(minParticleCount - activeCount);
}
public void start () {
firstUpdate = true;
allowCompletion = false;
restart();
}
public void reset () {
emissionDelta = 0;
durationTimer = 0;
start();
}
private void restart () {
delay = delayValue.active ? delayValue.newLowValue() : 0;
delayTimer = 0;
durationTimer -= duration;
duration = durationValue.newLowValue();
emission = (int)emissionValue.newLowValue();
emissionDiff = (int)emissionValue.newHighValue();
if (!emissionValue.isRelative()) emissionDiff -= emission;
life = (int)lifeValue.newLowValue();
lifeDiff = (int)lifeValue.newHighValue();
if (!lifeValue.isRelative()) lifeDiff -= life;
lifeOffset = lifeOffsetValue.active ? (int)lifeOffsetValue.newLowValue() : 0;
lifeOffsetDiff = (int)lifeOffsetValue.newHighValue();
if (!lifeOffsetValue.isRelative()) lifeOffsetDiff -= lifeOffset;
spawnWidth = spawnWidthValue.newLowValue();
spawnWidthDiff = spawnWidthValue.newHighValue();
if (!spawnWidthValue.isRelative()) spawnWidthDiff -= spawnWidth;
spawnHeight = spawnHeightValue.newLowValue();
spawnHeightDiff = spawnHeightValue.newHighValue();
if (!spawnHeightValue.isRelative()) spawnHeightDiff -= spawnHeight;
updateFlags = 0;
if (angleValue.active && angleValue.timeline.length > 1) updateFlags |= UPDATE_ANGLE;
if (velocityValue.active && velocityValue.active) updateFlags |= UPDATE_VELOCITY;
if (scaleValue.timeline.length > 1) updateFlags |= UPDATE_SCALE;
if (rotationValue.active && rotationValue.timeline.length > 1) updateFlags |= UPDATE_ROTATION;
if (windValue.active) updateFlags |= UPDATE_WIND;
if (gravityValue.active) updateFlags |= UPDATE_GRAVITY;
if (tintValue.timeline.length > 1) updateFlags |= UPDATE_TINT;
}
protected Particle newParticle (Sprite sprite) {
return new Particle(sprite);
}
private void activateParticle (int index) {
Particle particle = particles[index];
if (particle == null) {
particles[index] = particle = newParticle(sprite);
particle.flip(flipX, flipY);
}
float percent = durationTimer / (float)duration;
int updateFlags = this.updateFlags;
float offsetTime = lifeOffset + lifeOffsetDiff * lifeOffsetValue.getScale(percent);
particle.life = particle.currentLife = life + (int)(lifeDiff * lifeValue.getScale(percent));
if (velocityValue.active) {
particle.velocity = velocityValue.newLowValue();
particle.velocityDiff = velocityValue.newHighValue();
if (!velocityValue.isRelative()) particle.velocityDiff -= particle.velocity;
}
particle.angle = angleValue.newLowValue();
particle.angleDiff = angleValue.newHighValue();
if (!angleValue.isRelative()) particle.angleDiff -= particle.angle;
float angle = 0;
if ((updateFlags & UPDATE_ANGLE) == 0) {
angle = particle.angle + particle.angleDiff * angleValue.getScale(0);
particle.angle = angle;
particle.angleCos = MathUtils.cosDeg(angle);
particle.angleSin = MathUtils.sinDeg(angle);
}
float spriteWidth = sprite.getWidth();
particle.scale = scaleValue.newLowValue() / spriteWidth;
particle.scaleDiff = scaleValue.newHighValue() / spriteWidth;
if (!scaleValue.isRelative()) particle.scaleDiff -= particle.scale;
- if ((updateFlags & UPDATE_SCALE) == 0) particle.setScale(particle.scale + particle.scaleDiff * scaleValue.getScale(0));
+ particle.setScale(particle.scale + particle.scaleDiff * scaleValue.getScale(0));
if (rotationValue.active) {
particle.rotation = rotationValue.newLowValue();
particle.rotationDiff = rotationValue.newHighValue();
if (!rotationValue.isRelative()) particle.rotationDiff -= particle.rotation;
- if ((updateFlags & UPDATE_ROTATION) == 0) {
- float rotation = particle.rotation + particle.rotationDiff * rotationValue.getScale(0);
- if (aligned) rotation += angle;
- particle.setRotation(rotation);
- }
+ float rotation = particle.rotation + particle.rotationDiff * rotationValue.getScale(0);
+ if (aligned) rotation += angle;
+ particle.setRotation(rotation);
}
if (windValue.active) {
particle.wind = windValue.newLowValue();
particle.windDiff = windValue.newHighValue();
if (!windValue.isRelative()) particle.windDiff -= particle.wind;
}
if (gravityValue.active) {
particle.gravity = gravityValue.newLowValue();
particle.gravityDiff = gravityValue.newHighValue();
if (!gravityValue.isRelative()) particle.gravityDiff -= particle.gravity;
}
- if ((updateFlags & UPDATE_TINT) == 0) {
- float[] color = particle.tint;
- if (color == null) particle.tint = color = new float[3];
- float[] temp = tintValue.getColor(0);
- color[0] = temp[0];
- color[1] = temp[1];
- color[2] = temp[2];
- }
+ float[] color = particle.tint;
+ if (color == null) particle.tint = color = new float[3];
+ float[] temp = tintValue.getColor(0);
+ color[0] = temp[0];
+ color[1] = temp[1];
+ color[2] = temp[2];
particle.transparency = transparencyValue.newLowValue();
particle.transparencyDiff = transparencyValue.newHighValue() - particle.transparency;
// Spawn.
float x = this.x;
if (xOffsetValue.active) x += xOffsetValue.newLowValue();
float y = this.y;
if (yOffsetValue.active) y += yOffsetValue.newLowValue();
switch (spawnShapeValue.shape) {
case square: {
float width = spawnWidth + (spawnWidthDiff * spawnWidthValue.getScale(percent));
float height = spawnHeight + (spawnHeightDiff * spawnHeightValue.getScale(percent));
x += MathUtils.random(width) - width / 2;
y += MathUtils.random(height) - height / 2;
break;
}
case ellipse: {
float width = spawnWidth + (spawnWidthDiff * spawnWidthValue.getScale(percent));
float height = spawnHeight + (spawnHeightDiff * spawnHeightValue.getScale(percent));
float radiusX = width / 2;
float radiusY = height / 2;
if (radiusX == 0 || radiusY == 0) break;
float scaleY = radiusX / (float)radiusY;
if (spawnShapeValue.edges) {
float spawnAngle;
switch (spawnShapeValue.side) {
case top:
spawnAngle = -MathUtils.random(179f);
break;
case bottom:
spawnAngle = MathUtils.random(179f);
break;
default:
spawnAngle = MathUtils.random(360f);
break;
}
float cosDeg = MathUtils.cosDeg(spawnAngle);
float sinDeg = MathUtils.sinDeg(spawnAngle);
x += cosDeg * radiusX;
y += sinDeg * radiusX / scaleY;
if ((updateFlags & UPDATE_ANGLE) == 0) {
particle.angle = spawnAngle;
particle.angleCos = cosDeg;
particle.angleSin = sinDeg;
}
} else {
float radius2 = radiusX * radiusX;
while (true) {
float px = MathUtils.random(width) - radiusX;
float py = MathUtils.random(width) - radiusX;
if (px * px + py * py <= radius2) {
x += px;
y += py / scaleY;
break;
}
}
}
break;
}
case line: {
float width = spawnWidth + (spawnWidthDiff * spawnWidthValue.getScale(percent));
float height = spawnHeight + (spawnHeightDiff * spawnHeightValue.getScale(percent));
if (width != 0) {
float lineX = width * MathUtils.random();
x += lineX;
y += lineX * (height / (float)width);
} else
y += height * MathUtils.random();
break;
}
}
float spriteHeight = sprite.getHeight();
particle.setBounds(x - spriteWidth / 2, y - spriteHeight / 2, spriteWidth, spriteHeight);
}
private boolean updateParticle (Particle particle, float delta, int deltaMillis) {
int life = particle.currentLife - deltaMillis;
if (life <= 0) return false;
particle.currentLife = life;
float percent = 1 - particle.currentLife / (float)particle.life;
int updateFlags = this.updateFlags;
if ((updateFlags & UPDATE_SCALE) != 0)
particle.setScale(particle.scale + particle.scaleDiff * scaleValue.getScale(percent));
if ((updateFlags & UPDATE_VELOCITY) != 0) {
float velocity = (particle.velocity + particle.velocityDiff * velocityValue.getScale(percent)) * delta;
float velocityX, velocityY;
if ((updateFlags & UPDATE_ANGLE) != 0) {
float angle = particle.angle + particle.angleDiff * angleValue.getScale(percent);
velocityX = velocity * MathUtils.cosDeg(angle);
velocityY = velocity * MathUtils.sinDeg(angle);
if ((updateFlags & UPDATE_ROTATION) != 0) {
float rotation = particle.rotation + particle.rotationDiff * rotationValue.getScale(percent);
if (aligned) rotation += angle;
particle.setRotation(rotation);
}
} else {
velocityX = velocity * particle.angleCos;
velocityY = velocity * particle.angleSin;
if (aligned || (updateFlags & UPDATE_ROTATION) != 0) {
float rotation = particle.rotation + particle.rotationDiff * rotationValue.getScale(percent);
if (aligned) rotation += particle.angle;
particle.setRotation(rotation);
}
}
if ((updateFlags & UPDATE_WIND) != 0)
velocityX += (particle.wind + particle.windDiff * windValue.getScale(percent)) * delta;
if ((updateFlags & UPDATE_GRAVITY) != 0)
velocityY += (particle.gravity + particle.gravityDiff * gravityValue.getScale(percent)) * delta;
particle.translate(velocityX, velocityY);
} else {
if ((updateFlags & UPDATE_ROTATION) != 0)
particle.setRotation(particle.rotation + particle.rotationDiff * rotationValue.getScale(percent));
}
float[] color;
if ((updateFlags & UPDATE_TINT) != 0)
color = tintValue.getColor(percent);
else
color = particle.tint;
particle.setColor(color[0], color[1], color[2],
particle.transparency + particle.transparencyDiff * transparencyValue.getScale(percent));
return true;
}
public void setPosition (float x, float y) {
if (attached) {
float xAmount = x - this.x;
float yAmount = y - this.y;
boolean[] active = this.active;
for (int i = 0, n = active.length; i < n; i++)
if (active[i]) particles[i].translate(xAmount, yAmount);
}
this.x = x;
this.y = y;
}
public void setSprite (Sprite sprite) {
this.sprite = sprite;
if (sprite == null) return;
float originX = sprite.getOriginX();
float originY = sprite.getOriginY();
Texture texture = sprite.getTexture();
for (int i = 0, n = particles.length; i < n; i++) {
Particle particle = particles[i];
if (particle == null) break;
particle.setTexture(texture);
particle.setOrigin(originX, originY);
}
}
/** Ignores the {@link #setContinuous(boolean) continuous} setting until the emitter is started again. This allows the emitter
* to stop smoothly. */
public void allowCompletion () {
allowCompletion = true;
durationTimer = duration;
}
public Sprite getSprite () {
return sprite;
}
public String getName () {
return name;
}
public void setName (String name) {
this.name = name;
}
public ScaledNumericValue getLife () {
return lifeValue;
}
public ScaledNumericValue getScale () {
return scaleValue;
}
public ScaledNumericValue getRotation () {
return rotationValue;
}
public GradientColorValue getTint () {
return tintValue;
}
public ScaledNumericValue getVelocity () {
return velocityValue;
}
public ScaledNumericValue getWind () {
return windValue;
}
public ScaledNumericValue getGravity () {
return gravityValue;
}
public ScaledNumericValue getAngle () {
return angleValue;
}
public ScaledNumericValue getEmission () {
return emissionValue;
}
public ScaledNumericValue getTransparency () {
return transparencyValue;
}
public RangedNumericValue getDuration () {
return durationValue;
}
public RangedNumericValue getDelay () {
return delayValue;
}
public ScaledNumericValue getLifeOffset () {
return lifeOffsetValue;
}
public RangedNumericValue getXOffsetValue () {
return xOffsetValue;
}
public RangedNumericValue getYOffsetValue () {
return yOffsetValue;
}
public ScaledNumericValue getSpawnWidth () {
return spawnWidthValue;
}
public ScaledNumericValue getSpawnHeight () {
return spawnHeightValue;
}
public SpawnShapeValue getSpawnShape () {
return spawnShapeValue;
}
public boolean isAttached () {
return attached;
}
public void setAttached (boolean attached) {
this.attached = attached;
}
public boolean isContinuous () {
return continuous;
}
public void setContinuous (boolean continuous) {
this.continuous = continuous;
}
public boolean isAligned () {
return aligned;
}
public void setAligned (boolean aligned) {
this.aligned = aligned;
}
public boolean isAdditive () {
return additive;
}
public void setAdditive (boolean additive) {
this.additive = additive;
}
public boolean isBehind () {
return behind;
}
public void setBehind (boolean behind) {
this.behind = behind;
}
public int getMinParticleCount () {
return minParticleCount;
}
public void setMinParticleCount (int minParticleCount) {
this.minParticleCount = minParticleCount;
}
public int getMaxParticleCount () {
return maxParticleCount;
}
public boolean isComplete () {
if (delayTimer < delay) return false;
return durationTimer >= duration && activeCount == 0;
}
public float getPercentComplete () {
if (delayTimer < delay) return 0;
return Math.min(1, durationTimer / (float)duration);
}
public float getX () {
return x;
}
public float getY () {
return y;
}
public int getActiveCount () {
return activeCount;
}
public String getImagePath () {
return imagePath;
}
public void setImagePath (String imagePath) {
this.imagePath = imagePath;
}
public void setFlip (boolean flipX, boolean flipY) {
this.flipX = flipX;
this.flipY = flipY;
if (particles == null) return;
for (int i = 0, n = particles.length; i < n; i++) {
Particle particle = particles[i];
if (particle != null) particle.flip(flipX, flipY);
}
}
public void save (Writer output) throws IOException {
output.write(name + "\n");
output.write("- Delay -\n");
delayValue.save(output);
output.write("- Duration - \n");
durationValue.save(output);
output.write("- Count - \n");
output.write("min: " + minParticleCount + "\n");
output.write("max: " + maxParticleCount + "\n");
output.write("- Emission - \n");
emissionValue.save(output);
output.write("- Life - \n");
lifeValue.save(output);
output.write("- Life Offset - \n");
lifeOffsetValue.save(output);
output.write("- X Offset - \n");
xOffsetValue.save(output);
output.write("- Y Offset - \n");
yOffsetValue.save(output);
output.write("- Spawn Shape - \n");
spawnShapeValue.save(output);
output.write("- Spawn Width - \n");
spawnWidthValue.save(output);
output.write("- Spawn Height - \n");
spawnHeightValue.save(output);
output.write("- Scale - \n");
scaleValue.save(output);
output.write("- Velocity - \n");
velocityValue.save(output);
output.write("- Angle - \n");
angleValue.save(output);
output.write("- Rotation - \n");
rotationValue.save(output);
output.write("- Wind - \n");
windValue.save(output);
output.write("- Gravity - \n");
gravityValue.save(output);
output.write("- Tint - \n");
tintValue.save(output);
output.write("- Transparency - \n");
transparencyValue.save(output);
output.write("- Options - \n");
output.write("attached: " + attached + "\n");
output.write("continuous: " + continuous + "\n");
output.write("aligned: " + aligned + "\n");
output.write("additive: " + additive + "\n");
output.write("behind: " + behind + "\n");
}
public void load (BufferedReader reader) throws IOException {
try {
name = readString(reader, "name");
reader.readLine();
delayValue.load(reader);
reader.readLine();
durationValue.load(reader);
reader.readLine();
setMinParticleCount(readInt(reader, "minParticleCount"));
setMaxParticleCount(readInt(reader, "maxParticleCount"));
reader.readLine();
emissionValue.load(reader);
reader.readLine();
lifeValue.load(reader);
reader.readLine();
lifeOffsetValue.load(reader);
reader.readLine();
xOffsetValue.load(reader);
reader.readLine();
yOffsetValue.load(reader);
reader.readLine();
spawnShapeValue.load(reader);
reader.readLine();
spawnWidthValue.load(reader);
reader.readLine();
spawnHeightValue.load(reader);
reader.readLine();
scaleValue.load(reader);
reader.readLine();
velocityValue.load(reader);
reader.readLine();
angleValue.load(reader);
reader.readLine();
rotationValue.load(reader);
reader.readLine();
windValue.load(reader);
reader.readLine();
gravityValue.load(reader);
reader.readLine();
tintValue.load(reader);
reader.readLine();
transparencyValue.load(reader);
reader.readLine();
attached = readBoolean(reader, "attached");
continuous = readBoolean(reader, "continuous");
aligned = readBoolean(reader, "aligned");
additive = readBoolean(reader, "additive");
behind = readBoolean(reader, "behind");
} catch (RuntimeException ex) {
if (name == null) throw ex;
throw new RuntimeException("Error parsing emitter: " + name, ex);
}
}
static String readString (BufferedReader reader, String name) throws IOException {
String line = reader.readLine();
if (line == null) throw new IOException("Missing value: " + name);
return line.substring(line.indexOf(":") + 1).trim();
}
static boolean readBoolean (BufferedReader reader, String name) throws IOException {
return Boolean.parseBoolean(readString(reader, name));
}
static int readInt (BufferedReader reader, String name) throws IOException {
return Integer.parseInt(readString(reader, name));
}
static float readFloat (BufferedReader reader, String name) throws IOException {
return Float.parseFloat(readString(reader, name));
}
static class Particle extends Sprite {
int life, currentLife;
float scale, scaleDiff;
float rotation, rotationDiff;
float velocity, velocityDiff;
float angle, angleDiff;
float angleCos, angleSin;
float transparency, transparencyDiff;
float wind, windDiff;
float gravity, gravityDiff;
float[] tint;
public Particle (Sprite sprite) {
super(sprite);
}
}
static public class ParticleValue {
boolean active;
boolean alwaysActive;
public void setAlwaysActive (boolean alwaysActive) {
this.alwaysActive = alwaysActive;
}
public boolean isAlwaysActive () {
return alwaysActive;
}
public boolean isActive () {
return active;
}
public void setActive (boolean active) {
this.active = active;
}
public void save (Writer output) throws IOException {
if (!alwaysActive)
output.write("active: " + active + "\n");
else
active = true;
}
public void load (BufferedReader reader) throws IOException {
if (!alwaysActive)
active = readBoolean(reader, "active");
else
active = true;
}
public void load (ParticleValue value) {
active = value.active;
alwaysActive = value.alwaysActive;
}
}
static public class NumericValue extends ParticleValue {
private float value;
public float getValue () {
return value;
}
public void setValue (float value) {
this.value = value;
}
public void save (Writer output) throws IOException {
super.save(output);
if (!active) return;
output.write("value: " + value + "\n");
}
public void load (BufferedReader reader) throws IOException {
super.load(reader);
if (!active) return;
value = readFloat(reader, "value");
}
public void load (NumericValue value) {
super.load(value);
this.value = value.value;
}
}
static public class RangedNumericValue extends ParticleValue {
private float lowMin, lowMax;
public float newLowValue () {
return lowMin + (lowMax - lowMin) * MathUtils.random();
}
public void setLow (float value) {
lowMin = value;
lowMax = value;
}
public void setLow (float min, float max) {
lowMin = min;
lowMax = max;
}
public float getLowMin () {
return lowMin;
}
public void setLowMin (float lowMin) {
this.lowMin = lowMin;
}
public float getLowMax () {
return lowMax;
}
public void setLowMax (float lowMax) {
this.lowMax = lowMax;
}
public void save (Writer output) throws IOException {
super.save(output);
if (!active) return;
output.write("lowMin: " + lowMin + "\n");
output.write("lowMax: " + lowMax + "\n");
}
public void load (BufferedReader reader) throws IOException {
super.load(reader);
if (!active) return;
lowMin = readFloat(reader, "lowMin");
lowMax = readFloat(reader, "lowMax");
}
public void load (RangedNumericValue value) {
super.load(value);
lowMax = value.lowMax;
lowMin = value.lowMin;
}
}
static public class ScaledNumericValue extends RangedNumericValue {
private float[] scaling = {1};
float[] timeline = {0};
private float highMin, highMax;
private boolean relative;
public float newHighValue () {
return highMin + (highMax - highMin) * MathUtils.random();
}
public void setHigh (float value) {
highMin = value;
highMax = value;
}
public void setHigh (float min, float max) {
highMin = min;
highMax = max;
}
public float getHighMin () {
return highMin;
}
public void setHighMin (float highMin) {
this.highMin = highMin;
}
public float getHighMax () {
return highMax;
}
public void setHighMax (float highMax) {
this.highMax = highMax;
}
public float[] getScaling () {
return scaling;
}
public void setScaling (float[] values) {
this.scaling = values;
}
public float[] getTimeline () {
return timeline;
}
public void setTimeline (float[] timeline) {
this.timeline = timeline;
}
public boolean isRelative () {
return relative;
}
public void setRelative (boolean relative) {
this.relative = relative;
}
public float getScale (float percent) {
int endIndex = -1;
float[] timeline = this.timeline;
int n = timeline.length;
for (int i = 1; i < n; i++) {
float t = timeline[i];
if (t > percent) {
endIndex = i;
break;
}
}
if (endIndex == -1) return scaling[n - 1];
float[] scaling = this.scaling;
int startIndex = endIndex - 1;
float startValue = scaling[startIndex];
float startTime = timeline[startIndex];
return startValue + (scaling[endIndex] - startValue) * ((percent - startTime) / (timeline[endIndex] - startTime));
}
public void save (Writer output) throws IOException {
super.save(output);
if (!active) return;
output.write("highMin: " + highMin + "\n");
output.write("highMax: " + highMax + "\n");
output.write("relative: " + relative + "\n");
output.write("scalingCount: " + scaling.length + "\n");
for (int i = 0; i < scaling.length; i++)
output.write("scaling" + i + ": " + scaling[i] + "\n");
output.write("timelineCount: " + timeline.length + "\n");
for (int i = 0; i < timeline.length; i++)
output.write("timeline" + i + ": " + timeline[i] + "\n");
}
public void load (BufferedReader reader) throws IOException {
super.load(reader);
if (!active) return;
highMin = readFloat(reader, "highMin");
highMax = readFloat(reader, "highMax");
relative = readBoolean(reader, "relative");
scaling = new float[readInt(reader, "scalingCount")];
for (int i = 0; i < scaling.length; i++)
scaling[i] = readFloat(reader, "scaling" + i);
timeline = new float[readInt(reader, "timelineCount")];
for (int i = 0; i < timeline.length; i++)
timeline[i] = readFloat(reader, "timeline" + i);
}
public void load (ScaledNumericValue value) {
super.load(value);
highMax = value.highMax;
highMin = value.highMin;
scaling = new float[value.scaling.length];
System.arraycopy(value.scaling, 0, scaling, 0, scaling.length);
timeline = new float[value.timeline.length];
System.arraycopy(value.timeline, 0, timeline, 0, timeline.length);
relative = value.relative;
}
}
static public class GradientColorValue extends ParticleValue {
static private float[] temp = new float[4];
private float[] colors = {1, 1, 1};
float[] timeline = {0};
public GradientColorValue () {
alwaysActive = true;
}
public float[] getTimeline () {
return timeline;
}
public void setTimeline (float[] timeline) {
this.timeline = timeline;
}
public float[] getColors () {
return colors;
}
public void setColors (float[] colors) {
this.colors = colors;
}
public float[] getColor (float percent) {
int startIndex = 0, endIndex = -1;
float[] timeline = this.timeline;
int n = timeline.length;
for (int i = 1; i < n; i++) {
float t = timeline[i];
if (t > percent) {
endIndex = i;
break;
}
startIndex = i;
}
float startTime = timeline[startIndex];
startIndex *= 3;
float r1 = colors[startIndex];
float g1 = colors[startIndex + 1];
float b1 = colors[startIndex + 2];
if (endIndex == -1) {
temp[0] = r1;
temp[1] = g1;
temp[2] = b1;
return temp;
}
float factor = (percent - startTime) / (timeline[endIndex] - startTime);
endIndex *= 3;
temp[0] = r1 + (colors[endIndex] - r1) * factor;
temp[1] = g1 + (colors[endIndex + 1] - g1) * factor;
temp[2] = b1 + (colors[endIndex + 2] - b1) * factor;
return temp;
}
public void save (Writer output) throws IOException {
super.save(output);
if (!active) return;
output.write("colorsCount: " + colors.length + "\n");
for (int i = 0; i < colors.length; i++)
output.write("colors" + i + ": " + colors[i] + "\n");
output.write("timelineCount: " + timeline.length + "\n");
for (int i = 0; i < timeline.length; i++)
output.write("timeline" + i + ": " + timeline[i] + "\n");
}
public void load (BufferedReader reader) throws IOException {
super.load(reader);
if (!active) return;
colors = new float[readInt(reader, "colorsCount")];
for (int i = 0; i < colors.length; i++)
colors[i] = readFloat(reader, "colors" + i);
timeline = new float[readInt(reader, "timelineCount")];
for (int i = 0; i < timeline.length; i++)
timeline[i] = readFloat(reader, "timeline" + i);
}
public void load (GradientColorValue value) {
super.load(value);
colors = new float[value.colors.length];
System.arraycopy(value.colors, 0, colors, 0, colors.length);
timeline = new float[value.timeline.length];
System.arraycopy(value.timeline, 0, timeline, 0, timeline.length);
}
}
static public class SpawnShapeValue extends ParticleValue {
SpawnShape shape = SpawnShape.point;
boolean edges;
SpawnEllipseSide side = SpawnEllipseSide.both;
public SpawnShape getShape () {
return shape;
}
public void setShape (SpawnShape shape) {
this.shape = shape;
}
public boolean isEdges () {
return edges;
}
public void setEdges (boolean edges) {
this.edges = edges;
}
public SpawnEllipseSide getSide () {
return side;
}
public void setSide (SpawnEllipseSide side) {
this.side = side;
}
public void save (Writer output) throws IOException {
super.save(output);
if (!active) return;
output.write("shape: " + shape + "\n");
if (shape == SpawnShape.ellipse) {
output.write("edges: " + edges + "\n");
output.write("side: " + side + "\n");
}
}
public void load (BufferedReader reader) throws IOException {
super.load(reader);
if (!active) return;
shape = SpawnShape.valueOf(readString(reader, "shape"));
if (shape == SpawnShape.ellipse) {
edges = readBoolean(reader, "edges");
side = SpawnEllipseSide.valueOf(readString(reader, "side"));
}
}
public void load (SpawnShapeValue value) {
super.load(value);
shape = value.shape;
edges = value.edges;
side = value.side;
}
}
static public enum SpawnShape {
point, line, square, ellipse
}
static public enum SpawnEllipseSide {
both, top, bottom
}
}
| false | true | private void activateParticle (int index) {
Particle particle = particles[index];
if (particle == null) {
particles[index] = particle = newParticle(sprite);
particle.flip(flipX, flipY);
}
float percent = durationTimer / (float)duration;
int updateFlags = this.updateFlags;
float offsetTime = lifeOffset + lifeOffsetDiff * lifeOffsetValue.getScale(percent);
particle.life = particle.currentLife = life + (int)(lifeDiff * lifeValue.getScale(percent));
if (velocityValue.active) {
particle.velocity = velocityValue.newLowValue();
particle.velocityDiff = velocityValue.newHighValue();
if (!velocityValue.isRelative()) particle.velocityDiff -= particle.velocity;
}
particle.angle = angleValue.newLowValue();
particle.angleDiff = angleValue.newHighValue();
if (!angleValue.isRelative()) particle.angleDiff -= particle.angle;
float angle = 0;
if ((updateFlags & UPDATE_ANGLE) == 0) {
angle = particle.angle + particle.angleDiff * angleValue.getScale(0);
particle.angle = angle;
particle.angleCos = MathUtils.cosDeg(angle);
particle.angleSin = MathUtils.sinDeg(angle);
}
float spriteWidth = sprite.getWidth();
particle.scale = scaleValue.newLowValue() / spriteWidth;
particle.scaleDiff = scaleValue.newHighValue() / spriteWidth;
if (!scaleValue.isRelative()) particle.scaleDiff -= particle.scale;
if ((updateFlags & UPDATE_SCALE) == 0) particle.setScale(particle.scale + particle.scaleDiff * scaleValue.getScale(0));
if (rotationValue.active) {
particle.rotation = rotationValue.newLowValue();
particle.rotationDiff = rotationValue.newHighValue();
if (!rotationValue.isRelative()) particle.rotationDiff -= particle.rotation;
if ((updateFlags & UPDATE_ROTATION) == 0) {
float rotation = particle.rotation + particle.rotationDiff * rotationValue.getScale(0);
if (aligned) rotation += angle;
particle.setRotation(rotation);
}
}
if (windValue.active) {
particle.wind = windValue.newLowValue();
particle.windDiff = windValue.newHighValue();
if (!windValue.isRelative()) particle.windDiff -= particle.wind;
}
if (gravityValue.active) {
particle.gravity = gravityValue.newLowValue();
particle.gravityDiff = gravityValue.newHighValue();
if (!gravityValue.isRelative()) particle.gravityDiff -= particle.gravity;
}
if ((updateFlags & UPDATE_TINT) == 0) {
float[] color = particle.tint;
if (color == null) particle.tint = color = new float[3];
float[] temp = tintValue.getColor(0);
color[0] = temp[0];
color[1] = temp[1];
color[2] = temp[2];
}
particle.transparency = transparencyValue.newLowValue();
particle.transparencyDiff = transparencyValue.newHighValue() - particle.transparency;
// Spawn.
float x = this.x;
if (xOffsetValue.active) x += xOffsetValue.newLowValue();
float y = this.y;
if (yOffsetValue.active) y += yOffsetValue.newLowValue();
switch (spawnShapeValue.shape) {
case square: {
float width = spawnWidth + (spawnWidthDiff * spawnWidthValue.getScale(percent));
float height = spawnHeight + (spawnHeightDiff * spawnHeightValue.getScale(percent));
x += MathUtils.random(width) - width / 2;
y += MathUtils.random(height) - height / 2;
break;
}
case ellipse: {
float width = spawnWidth + (spawnWidthDiff * spawnWidthValue.getScale(percent));
float height = spawnHeight + (spawnHeightDiff * spawnHeightValue.getScale(percent));
float radiusX = width / 2;
float radiusY = height / 2;
if (radiusX == 0 || radiusY == 0) break;
float scaleY = radiusX / (float)radiusY;
if (spawnShapeValue.edges) {
float spawnAngle;
switch (spawnShapeValue.side) {
case top:
spawnAngle = -MathUtils.random(179f);
break;
case bottom:
spawnAngle = MathUtils.random(179f);
break;
default:
spawnAngle = MathUtils.random(360f);
break;
}
float cosDeg = MathUtils.cosDeg(spawnAngle);
float sinDeg = MathUtils.sinDeg(spawnAngle);
x += cosDeg * radiusX;
y += sinDeg * radiusX / scaleY;
if ((updateFlags & UPDATE_ANGLE) == 0) {
particle.angle = spawnAngle;
particle.angleCos = cosDeg;
particle.angleSin = sinDeg;
}
} else {
float radius2 = radiusX * radiusX;
while (true) {
float px = MathUtils.random(width) - radiusX;
float py = MathUtils.random(width) - radiusX;
if (px * px + py * py <= radius2) {
x += px;
y += py / scaleY;
break;
}
}
}
break;
}
case line: {
float width = spawnWidth + (spawnWidthDiff * spawnWidthValue.getScale(percent));
float height = spawnHeight + (spawnHeightDiff * spawnHeightValue.getScale(percent));
if (width != 0) {
float lineX = width * MathUtils.random();
x += lineX;
y += lineX * (height / (float)width);
} else
y += height * MathUtils.random();
break;
}
}
float spriteHeight = sprite.getHeight();
particle.setBounds(x - spriteWidth / 2, y - spriteHeight / 2, spriteWidth, spriteHeight);
}
| private void activateParticle (int index) {
Particle particle = particles[index];
if (particle == null) {
particles[index] = particle = newParticle(sprite);
particle.flip(flipX, flipY);
}
float percent = durationTimer / (float)duration;
int updateFlags = this.updateFlags;
float offsetTime = lifeOffset + lifeOffsetDiff * lifeOffsetValue.getScale(percent);
particle.life = particle.currentLife = life + (int)(lifeDiff * lifeValue.getScale(percent));
if (velocityValue.active) {
particle.velocity = velocityValue.newLowValue();
particle.velocityDiff = velocityValue.newHighValue();
if (!velocityValue.isRelative()) particle.velocityDiff -= particle.velocity;
}
particle.angle = angleValue.newLowValue();
particle.angleDiff = angleValue.newHighValue();
if (!angleValue.isRelative()) particle.angleDiff -= particle.angle;
float angle = 0;
if ((updateFlags & UPDATE_ANGLE) == 0) {
angle = particle.angle + particle.angleDiff * angleValue.getScale(0);
particle.angle = angle;
particle.angleCos = MathUtils.cosDeg(angle);
particle.angleSin = MathUtils.sinDeg(angle);
}
float spriteWidth = sprite.getWidth();
particle.scale = scaleValue.newLowValue() / spriteWidth;
particle.scaleDiff = scaleValue.newHighValue() / spriteWidth;
if (!scaleValue.isRelative()) particle.scaleDiff -= particle.scale;
particle.setScale(particle.scale + particle.scaleDiff * scaleValue.getScale(0));
if (rotationValue.active) {
particle.rotation = rotationValue.newLowValue();
particle.rotationDiff = rotationValue.newHighValue();
if (!rotationValue.isRelative()) particle.rotationDiff -= particle.rotation;
float rotation = particle.rotation + particle.rotationDiff * rotationValue.getScale(0);
if (aligned) rotation += angle;
particle.setRotation(rotation);
}
if (windValue.active) {
particle.wind = windValue.newLowValue();
particle.windDiff = windValue.newHighValue();
if (!windValue.isRelative()) particle.windDiff -= particle.wind;
}
if (gravityValue.active) {
particle.gravity = gravityValue.newLowValue();
particle.gravityDiff = gravityValue.newHighValue();
if (!gravityValue.isRelative()) particle.gravityDiff -= particle.gravity;
}
float[] color = particle.tint;
if (color == null) particle.tint = color = new float[3];
float[] temp = tintValue.getColor(0);
color[0] = temp[0];
color[1] = temp[1];
color[2] = temp[2];
particle.transparency = transparencyValue.newLowValue();
particle.transparencyDiff = transparencyValue.newHighValue() - particle.transparency;
// Spawn.
float x = this.x;
if (xOffsetValue.active) x += xOffsetValue.newLowValue();
float y = this.y;
if (yOffsetValue.active) y += yOffsetValue.newLowValue();
switch (spawnShapeValue.shape) {
case square: {
float width = spawnWidth + (spawnWidthDiff * spawnWidthValue.getScale(percent));
float height = spawnHeight + (spawnHeightDiff * spawnHeightValue.getScale(percent));
x += MathUtils.random(width) - width / 2;
y += MathUtils.random(height) - height / 2;
break;
}
case ellipse: {
float width = spawnWidth + (spawnWidthDiff * spawnWidthValue.getScale(percent));
float height = spawnHeight + (spawnHeightDiff * spawnHeightValue.getScale(percent));
float radiusX = width / 2;
float radiusY = height / 2;
if (radiusX == 0 || radiusY == 0) break;
float scaleY = radiusX / (float)radiusY;
if (spawnShapeValue.edges) {
float spawnAngle;
switch (spawnShapeValue.side) {
case top:
spawnAngle = -MathUtils.random(179f);
break;
case bottom:
spawnAngle = MathUtils.random(179f);
break;
default:
spawnAngle = MathUtils.random(360f);
break;
}
float cosDeg = MathUtils.cosDeg(spawnAngle);
float sinDeg = MathUtils.sinDeg(spawnAngle);
x += cosDeg * radiusX;
y += sinDeg * radiusX / scaleY;
if ((updateFlags & UPDATE_ANGLE) == 0) {
particle.angle = spawnAngle;
particle.angleCos = cosDeg;
particle.angleSin = sinDeg;
}
} else {
float radius2 = radiusX * radiusX;
while (true) {
float px = MathUtils.random(width) - radiusX;
float py = MathUtils.random(width) - radiusX;
if (px * px + py * py <= radius2) {
x += px;
y += py / scaleY;
break;
}
}
}
break;
}
case line: {
float width = spawnWidth + (spawnWidthDiff * spawnWidthValue.getScale(percent));
float height = spawnHeight + (spawnHeightDiff * spawnHeightValue.getScale(percent));
if (width != 0) {
float lineX = width * MathUtils.random();
x += lineX;
y += lineX * (height / (float)width);
} else
y += height * MathUtils.random();
break;
}
}
float spriteHeight = sprite.getHeight();
particle.setBounds(x - spriteWidth / 2, y - spriteHeight / 2, spriteWidth, spriteHeight);
}
|
diff --git a/src/org/rsbot/security/RestrictedSecurityManager.java b/src/org/rsbot/security/RestrictedSecurityManager.java
index c0874928..2e291f9c 100644
--- a/src/org/rsbot/security/RestrictedSecurityManager.java
+++ b/src/org/rsbot/security/RestrictedSecurityManager.java
@@ -1,261 +1,261 @@
package org.rsbot.security;
import java.io.File;
import java.io.FileDescriptor;
import java.net.InetAddress;
import java.security.Permission;
import java.util.ArrayList;
import org.rsbot.Application;
import org.rsbot.gui.BotGUI;
import org.rsbot.script.Script;
import org.rsbot.service.ScriptDeliveryNetwork;
import org.rsbot.util.AccountStore;
import org.rsbot.util.GlobalConfiguration;
/**
* @author Paris
*/
public class RestrictedSecurityManager extends SecurityManager {
private String getCallingClass() {
final String prefix = Application.class.getPackage().getName() + ".";
for (StackTraceElement s : Thread.currentThread().getStackTrace()) {
final String name = s.getClassName();
if (name.startsWith(prefix) && !name.equals(RestrictedSecurityManager.class.getName())) {
return name;
}
}
return "";
}
private boolean isCallerScript() {
final StackTraceElement[] s = Thread.currentThread().getStackTrace();
for (int i = s.length - 1; i > -1; i--) {
if (s[i].getClassName().startsWith(Script.class.getName()))
return true;
}
return false;
}
public void checkAccept(String host, int port) {
throw new SecurityException();
}
public void checkConnect(String host, int port) {
if (host.equalsIgnoreCase("localhost") || host.equals("127.0.0.1"))
throw new SecurityException();
// ports other than HTTP (80), HTTPS (443) and unknown (-1) are automatically denied
if (!(port == -1 || port == 80 || port == 443)) {
throw new SecurityException();
}
if (isCallerScript()) {
ArrayList<String> whitelist = new ArrayList<String>();
// NOTE: if whitelist item starts with a dot "." then it is checked at the end of the host
whitelist.add(".imageshack.us");
whitelist.add(".tinypic.com");
whitelist.add(".photobucket.com");
whitelist.add(".imgur.com");
whitelist.add(".powerbot.org");
whitelist.add(".runescape.com");
whitelist.add("shadowscripting.org"); // iDungeon
whitelist.add("shadowscripting.wordpress.com"); // iDungeon
whitelist.add(".glorb.nl"); // SXForce - Swamp Lizzy Paid, Snake Killah
whitelist.add("scripts.johnkeech.com"); // MrSneaky - SneakyFarmerPro
whitelist.add("myrsdatabase.x10.mx"); // gravemindx - BPestControl, GhoulKiller
whitelist.add("hedealer.site11.com"); // XscripterzX - PiratePlanker, DealerTanner
whitelist.add("elyzianpirate.web44.net"); // XscripterzX (see above)
whitelist.add(".wikia.com"); // common assets and images
whitelist.add("jtryba.com"); // jtryba - autoCook, monkR8per
whitelist.add("tehgamer.info"); // TehGamer - iMiner
// connecting to a raw IP address blocked because a fake reverse DNS is easy to set
if (isIpAddress(host))
throw new SecurityException();
boolean allowed = false;
for (String check : whitelist) {
if (check.startsWith(".")) {
if (host.endsWith(check) || check.equals("." + host))
allowed = true;
} else if (host.equals(check)) {
allowed = true;
}
- if (allowed = true)
+ if (allowed == true)
break;
}
if (!allowed) {
throw new SecurityException();
}
}
super.checkConnect(host, port);
}
private boolean isIpAddress(String check) {
final int l = check.length();
if (l < 7 || l > 15) {
return false;
}
String[] parts = check.split("\\.", 4);
if (parts.length != 4) {
return false;
}
for (int i = 0; i < 4; i++) {
int n = Integer.parseInt(parts[i]);
if (n < 0 || n > 255) {
return false;
}
}
return true;
}
public void checkConnect(String host, int port, Object context) {
checkConnect(host, port);
}
public void checkCreateClassLoader() {
super.checkCreateClassLoader();
}
public void checkDelete(String file) {
checkFilePath(file);
super.checkDelete(file);
}
public void checkExec(String cmd) {
final String calling = getCallingClass();
if (calling.equals(ScriptDeliveryNetwork.class.getName()) || calling.equals(BotGUI.class.getName())) {
super.checkExec(cmd);
} else {
throw new SecurityException();
}
}
public void checkExit(int status) {
final String calling = getCallingClass();
if (calling.equals(BotGUI.class.getName())) {
super.checkExit(status);
} else {
throw new SecurityException();
}
}
public void checkLink(String lib) {
super.checkLink(lib);
}
public void checkListen(int port) {
throw new SecurityException();
}
public void checkMemberAccess(Class<?> clazz, int which) {
super.checkMemberAccess(clazz, which);
}
public void checkMulticast(InetAddress maddr) {
throw new SecurityException();
}
public void checkMulticast(InetAddress maddr, byte ttl) {
throw new SecurityException();
}
public void checkPackageAccess(String pkg) {
super.checkPackageAccess(pkg);
}
public void checkPackageDefinition(String pkg) {
super.checkPackageDefinition(pkg);
}
public void checkPermission(Permission perm) {
//super.checkPermission(perm);
}
public void checkPermission(Permission perm, Object context) {
//super.checkPermission(perm, context);
}
public void checkPrintJobAccess() {
throw new SecurityException();
}
public void checkPropertiesAccess() {
super.checkPropertiesAccess();
}
public void checkPropertyAccess(String key) {
super.checkPropertyAccess(key);
}
public void checkRead(FileDescriptor fd) {
if (isCallerScript()) {
throw new SecurityException();
}
super.checkRead(fd);
}
public void checkRead(String file) {
checkSuperFilePath(file);
super.checkRead(file);
}
public void checkRead(String file, Object context) {
checkRead(file);
}
public void checkSecurityAccess(String target) {
super.checkSecurityAccess(target);
}
public void checkSetFactory() {
super.checkSetFactory();
}
public void checkSystemClipboardAccess() {
throw new SecurityException();
}
public boolean checkTopLevelWindow(Object window) {
return super.checkTopLevelWindow(window);
}
public void checkWrite(FileDescriptor fd) {
if (isCallerScript()) {
throw new SecurityException();
}
super.checkWrite(fd);
}
public void checkWrite(String file) {
checkFilePath(file);
super.checkWrite(file);
}
private void checkSuperFilePath(String path) {
path = new File(path).getAbsolutePath();
if (path.equalsIgnoreCase(new File(GlobalConfiguration.Paths.getAccountsFile()).getAbsolutePath())) {
for (StackTraceElement s : Thread.currentThread().getStackTrace()) {
final String name = s.getClassName();
if (name.equals(AccountStore.class.getName()))
return;
}
throw new SecurityException();
}
}
private void checkFilePath(String path) {
checkSuperFilePath(path);
path = new File(path).getAbsolutePath();
if (isCallerScript()) {
if (!path.startsWith(GlobalConfiguration.Paths.getScriptCacheDirectory()))
throw new SecurityException();
}
}
}
| true | true | public void checkConnect(String host, int port) {
if (host.equalsIgnoreCase("localhost") || host.equals("127.0.0.1"))
throw new SecurityException();
// ports other than HTTP (80), HTTPS (443) and unknown (-1) are automatically denied
if (!(port == -1 || port == 80 || port == 443)) {
throw new SecurityException();
}
if (isCallerScript()) {
ArrayList<String> whitelist = new ArrayList<String>();
// NOTE: if whitelist item starts with a dot "." then it is checked at the end of the host
whitelist.add(".imageshack.us");
whitelist.add(".tinypic.com");
whitelist.add(".photobucket.com");
whitelist.add(".imgur.com");
whitelist.add(".powerbot.org");
whitelist.add(".runescape.com");
whitelist.add("shadowscripting.org"); // iDungeon
whitelist.add("shadowscripting.wordpress.com"); // iDungeon
whitelist.add(".glorb.nl"); // SXForce - Swamp Lizzy Paid, Snake Killah
whitelist.add("scripts.johnkeech.com"); // MrSneaky - SneakyFarmerPro
whitelist.add("myrsdatabase.x10.mx"); // gravemindx - BPestControl, GhoulKiller
whitelist.add("hedealer.site11.com"); // XscripterzX - PiratePlanker, DealerTanner
whitelist.add("elyzianpirate.web44.net"); // XscripterzX (see above)
whitelist.add(".wikia.com"); // common assets and images
whitelist.add("jtryba.com"); // jtryba - autoCook, monkR8per
whitelist.add("tehgamer.info"); // TehGamer - iMiner
// connecting to a raw IP address blocked because a fake reverse DNS is easy to set
if (isIpAddress(host))
throw new SecurityException();
boolean allowed = false;
for (String check : whitelist) {
if (check.startsWith(".")) {
if (host.endsWith(check) || check.equals("." + host))
allowed = true;
} else if (host.equals(check)) {
allowed = true;
}
if (allowed = true)
break;
}
if (!allowed) {
throw new SecurityException();
}
}
super.checkConnect(host, port);
}
| public void checkConnect(String host, int port) {
if (host.equalsIgnoreCase("localhost") || host.equals("127.0.0.1"))
throw new SecurityException();
// ports other than HTTP (80), HTTPS (443) and unknown (-1) are automatically denied
if (!(port == -1 || port == 80 || port == 443)) {
throw new SecurityException();
}
if (isCallerScript()) {
ArrayList<String> whitelist = new ArrayList<String>();
// NOTE: if whitelist item starts with a dot "." then it is checked at the end of the host
whitelist.add(".imageshack.us");
whitelist.add(".tinypic.com");
whitelist.add(".photobucket.com");
whitelist.add(".imgur.com");
whitelist.add(".powerbot.org");
whitelist.add(".runescape.com");
whitelist.add("shadowscripting.org"); // iDungeon
whitelist.add("shadowscripting.wordpress.com"); // iDungeon
whitelist.add(".glorb.nl"); // SXForce - Swamp Lizzy Paid, Snake Killah
whitelist.add("scripts.johnkeech.com"); // MrSneaky - SneakyFarmerPro
whitelist.add("myrsdatabase.x10.mx"); // gravemindx - BPestControl, GhoulKiller
whitelist.add("hedealer.site11.com"); // XscripterzX - PiratePlanker, DealerTanner
whitelist.add("elyzianpirate.web44.net"); // XscripterzX (see above)
whitelist.add(".wikia.com"); // common assets and images
whitelist.add("jtryba.com"); // jtryba - autoCook, monkR8per
whitelist.add("tehgamer.info"); // TehGamer - iMiner
// connecting to a raw IP address blocked because a fake reverse DNS is easy to set
if (isIpAddress(host))
throw new SecurityException();
boolean allowed = false;
for (String check : whitelist) {
if (check.startsWith(".")) {
if (host.endsWith(check) || check.equals("." + host))
allowed = true;
} else if (host.equals(check)) {
allowed = true;
}
if (allowed == true)
break;
}
if (!allowed) {
throw new SecurityException();
}
}
super.checkConnect(host, port);
}
|
diff --git a/src/hl7v3util/src/com/vangent/hieos/hl7v3util/model/subject/CodedValue.java b/src/hl7v3util/src/com/vangent/hieos/hl7v3util/model/subject/CodedValue.java
index a859b9ec..bd92be02 100644
--- a/src/hl7v3util/src/com/vangent/hieos/hl7v3util/model/subject/CodedValue.java
+++ b/src/hl7v3util/src/com/vangent/hieos/hl7v3util/model/subject/CodedValue.java
@@ -1,120 +1,120 @@
/*
* This code is subject to the HIEOS License, Version 1.0
*
* Copyright(c) 2010 Vangent, Inc. All rights reserved.
*
* 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.vangent.hieos.hl7v3util.model.subject;
/**
*
* @author Bernie Thuman
*/
public class CodedValue {
private String code;
private String codeSystem;
private String codeSystemName;
private String codeSystemVersion;
private String displayName;
/**
*
* @return
*/
public String getCode() {
return code;
}
/**
*
* @param code
*/
public void setCode(String code) {
this.code = code;
}
/**
*
* @return
*/
public String getCodeSystem() {
return codeSystem;
}
/**
*
* @param codeSystem
*/
public void setCodeSystem(String codeSystem) {
this.codeSystem = codeSystem;
}
/**
*
* @return
*/
public String getCodeSystemName() {
return codeSystemName;
}
/**
*
* @param codeSystemName
*/
public void setCodeSystemName(String codeSystemName) {
this.codeSystemName = codeSystemName;
}
/**
*
* @return
*/
public String getCodeSystemVersion() {
return codeSystemVersion;
}
/**
*
* @param codeSystemVersion
*/
public void setCodeSystemVersion(String codeSystemVersion) {
this.codeSystemVersion = codeSystemVersion;
}
/**
*
* @return
*/
public String getDisplayName() {
return displayName;
}
/**
*
* @param displayName
*/
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
/**
*
* @return
*/
public String getCNEFormatted() {
if (code == null) {
return "UNKNOWN_CODE";
}
if (codeSystem == null || codeSystem.isEmpty()) {
return code;
}
- return code + "^" + codeSystem;
+ return code + "^^" + codeSystem;
}
}
| true | true | public String getCNEFormatted() {
if (code == null) {
return "UNKNOWN_CODE";
}
if (codeSystem == null || codeSystem.isEmpty()) {
return code;
}
return code + "^" + codeSystem;
}
| public String getCNEFormatted() {
if (code == null) {
return "UNKNOWN_CODE";
}
if (codeSystem == null || codeSystem.isEmpty()) {
return code;
}
return code + "^^" + codeSystem;
}
|
diff --git a/tubular-core/src/test/java/org/trancecode/xproc/XProcTestSuiteReportBuilder.java b/tubular-core/src/test/java/org/trancecode/xproc/XProcTestSuiteReportBuilder.java
index 9173e6a6..bb35d601 100644
--- a/tubular-core/src/test/java/org/trancecode/xproc/XProcTestSuiteReportBuilder.java
+++ b/tubular-core/src/test/java/org/trancecode/xproc/XProcTestSuiteReportBuilder.java
@@ -1,228 +1,228 @@
/*
* Copyright (C) 2010 Herve Quiroz
*
* 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 org.trancecode.xproc;
import com.google.common.base.Preconditions;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import com.google.common.io.Closeables;
import java.io.File;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import net.sf.saxon.s9api.Processor;
import net.sf.saxon.s9api.SaxonApiException;
import net.sf.saxon.s9api.Serializer;
import net.sf.saxon.s9api.Serializer.Property;
import org.trancecode.TcAssert.XdmNodeCompareAssertionError;
import org.trancecode.io.Files;
import org.trancecode.xml.saxon.SaxonBuilder;
import org.trancecode.xproc.XProcTestReportXmlModel.Attributes;
import org.trancecode.xproc.XProcTestReportXmlModel.Elements;
/**
* @author Herve Quiroz
*/
public final class XProcTestSuiteReportBuilder
{
private final Multimap<String, TestResult> results = ArrayListMultimap.create();
public static final class TestResult
{
private final XProcTestCase test;
private final Throwable error;
public TestResult(final XProcTestCase test, final Throwable error)
{
this.test = Preconditions.checkNotNull(test);
this.error = error;
}
public boolean failed()
{
return (error != null
&& !(error instanceof XProcException && ((XProcException) error).getName().equals(test.getError()))) ||
(error == null && test.getError() != null);
}
}
private static void writeProcessorInformation(final SaxonBuilder builder)
{
builder.startElement(Elements.PROCESSOR);
builder.startElement(Elements.NAME);
builder.text(Tubular.productName());
builder.endElement();
builder.startElement(Elements.VENDOR);
builder.text(Tubular.vendor());
builder.endElement();
builder.startElement(Elements.VENDOR_URI);
builder.text(Tubular.vendorUri());
builder.endElement();
builder.startElement(Elements.VERSION);
builder.text(Tubular.version());
builder.endElement();
builder.startElement(Elements.LANGUAGE);
builder.text("en_US");
builder.endElement();
builder.startElement(Elements.XPROC_VERSION);
builder.text(Tubular.xprocVersion());
builder.endElement();
builder.startElement(Elements.XPATH_VERSION);
builder.text(Tubular.xpathVersion());
builder.endElement();
builder.startElement(Elements.PSVI_SUPPORTED);
builder.text("false");
builder.endElement();
builder.endElement();
}
public TestResult result(final XProcTestCase test, final Throwable error)
{
final TestResult result = new TestResult(test, error);
if (test.testSuite() != null)
{
results.put(test.testSuite(), result);
}
return result;
}
public void write(final File file)
{
final Processor processor = new Processor(false);
final SaxonBuilder builder = new SaxonBuilder(processor.getUnderlyingConfiguration());
builder.startDocument();
builder.startElement(Elements.TEST_REPORT);
builder.startElement(Elements.TITLE);
builder.text("XProc Test Results for Tubular");
builder.endElement();
builder.startElement(Elements.DATE);
builder.text(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(new Date()));
builder.endElement();
writeProcessorInformation(builder);
for (final String testSuite : results.keySet())
{
builder.startElement(Elements.TEST_SUITE);
builder.startElement(Elements.TITLE);
builder.text(testSuite);
builder.endElement();
for (final TestResult result : results.get(testSuite))
{
assert result.test.testSuite().equals(testSuite);
if (result.failed())
{
builder.startElement(Elements.FAIL);
}
else
{
builder.startElement(Elements.PASS);
}
builder.attribute(Attributes.URI, result.test.url().toString());
builder.startElement(Elements.TITLE);
builder.text(result.test.getTitle());
builder.endElement();
if (result.error != null)
{
builder.startElement(Elements.ERROR);
if (result.test.getError() != null)
{
builder.attribute(Attributes.EXPECTED, result.test.getError().toString());
}
if (result.error instanceof XProcException)
{
- builder.text(((XProcException) result.error).getName().getClarkName());
+ builder.text(((XProcException) result.error).getName().toString());
}
else
{
builder.text(result.error.getClass().getSimpleName());
}
builder.endElement();
if (result.error instanceof XdmNodeCompareAssertionError)
{
final XdmNodeCompareAssertionError comparisonError = (XdmNodeCompareAssertionError) result.error;
builder.startElement(Elements.EXPECTED);
builder.text(comparisonError.expected().toString());
builder.endElement();
builder.startElement(Elements.ACTUAL);
builder.text(comparisonError.actual().toString());
builder.endElement();
}
}
if (result.error != null && !(result.error instanceof XdmNodeCompareAssertionError))
{
builder.startElement(Elements.MESSAGE);
if (result.error.getMessage() != null)
{
builder.text(result.error.getMessage());
}
else
{
builder.text(result.error.getClass().getName());
}
builder.endElement();
}
builder.endElement();
}
builder.endElement();
}
builder.endElement();
builder.endDocument();
// Write report to file
final OutputStream reportOut = Files.newFileOutputStream(file);
final Serializer serializer = new Serializer();
serializer.setOutputStream(reportOut);
serializer.setOutputProperty(Property.INDENT, "yes");
try
{
processor.writeXdmValue(builder.getNode(), serializer);
}
catch (final SaxonApiException e)
{
throw new IllegalStateException(e);
}
finally
{
Closeables.closeQuietly(reportOut);
}
}
}
| true | true | public void write(final File file)
{
final Processor processor = new Processor(false);
final SaxonBuilder builder = new SaxonBuilder(processor.getUnderlyingConfiguration());
builder.startDocument();
builder.startElement(Elements.TEST_REPORT);
builder.startElement(Elements.TITLE);
builder.text("XProc Test Results for Tubular");
builder.endElement();
builder.startElement(Elements.DATE);
builder.text(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(new Date()));
builder.endElement();
writeProcessorInformation(builder);
for (final String testSuite : results.keySet())
{
builder.startElement(Elements.TEST_SUITE);
builder.startElement(Elements.TITLE);
builder.text(testSuite);
builder.endElement();
for (final TestResult result : results.get(testSuite))
{
assert result.test.testSuite().equals(testSuite);
if (result.failed())
{
builder.startElement(Elements.FAIL);
}
else
{
builder.startElement(Elements.PASS);
}
builder.attribute(Attributes.URI, result.test.url().toString());
builder.startElement(Elements.TITLE);
builder.text(result.test.getTitle());
builder.endElement();
if (result.error != null)
{
builder.startElement(Elements.ERROR);
if (result.test.getError() != null)
{
builder.attribute(Attributes.EXPECTED, result.test.getError().toString());
}
if (result.error instanceof XProcException)
{
builder.text(((XProcException) result.error).getName().getClarkName());
}
else
{
builder.text(result.error.getClass().getSimpleName());
}
builder.endElement();
if (result.error instanceof XdmNodeCompareAssertionError)
{
final XdmNodeCompareAssertionError comparisonError = (XdmNodeCompareAssertionError) result.error;
builder.startElement(Elements.EXPECTED);
builder.text(comparisonError.expected().toString());
builder.endElement();
builder.startElement(Elements.ACTUAL);
builder.text(comparisonError.actual().toString());
builder.endElement();
}
}
if (result.error != null && !(result.error instanceof XdmNodeCompareAssertionError))
{
builder.startElement(Elements.MESSAGE);
if (result.error.getMessage() != null)
{
builder.text(result.error.getMessage());
}
else
{
builder.text(result.error.getClass().getName());
}
builder.endElement();
}
builder.endElement();
}
builder.endElement();
}
builder.endElement();
builder.endDocument();
// Write report to file
final OutputStream reportOut = Files.newFileOutputStream(file);
final Serializer serializer = new Serializer();
serializer.setOutputStream(reportOut);
serializer.setOutputProperty(Property.INDENT, "yes");
try
{
processor.writeXdmValue(builder.getNode(), serializer);
}
catch (final SaxonApiException e)
{
throw new IllegalStateException(e);
}
finally
{
Closeables.closeQuietly(reportOut);
}
}
| public void write(final File file)
{
final Processor processor = new Processor(false);
final SaxonBuilder builder = new SaxonBuilder(processor.getUnderlyingConfiguration());
builder.startDocument();
builder.startElement(Elements.TEST_REPORT);
builder.startElement(Elements.TITLE);
builder.text("XProc Test Results for Tubular");
builder.endElement();
builder.startElement(Elements.DATE);
builder.text(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(new Date()));
builder.endElement();
writeProcessorInformation(builder);
for (final String testSuite : results.keySet())
{
builder.startElement(Elements.TEST_SUITE);
builder.startElement(Elements.TITLE);
builder.text(testSuite);
builder.endElement();
for (final TestResult result : results.get(testSuite))
{
assert result.test.testSuite().equals(testSuite);
if (result.failed())
{
builder.startElement(Elements.FAIL);
}
else
{
builder.startElement(Elements.PASS);
}
builder.attribute(Attributes.URI, result.test.url().toString());
builder.startElement(Elements.TITLE);
builder.text(result.test.getTitle());
builder.endElement();
if (result.error != null)
{
builder.startElement(Elements.ERROR);
if (result.test.getError() != null)
{
builder.attribute(Attributes.EXPECTED, result.test.getError().toString());
}
if (result.error instanceof XProcException)
{
builder.text(((XProcException) result.error).getName().toString());
}
else
{
builder.text(result.error.getClass().getSimpleName());
}
builder.endElement();
if (result.error instanceof XdmNodeCompareAssertionError)
{
final XdmNodeCompareAssertionError comparisonError = (XdmNodeCompareAssertionError) result.error;
builder.startElement(Elements.EXPECTED);
builder.text(comparisonError.expected().toString());
builder.endElement();
builder.startElement(Elements.ACTUAL);
builder.text(comparisonError.actual().toString());
builder.endElement();
}
}
if (result.error != null && !(result.error instanceof XdmNodeCompareAssertionError))
{
builder.startElement(Elements.MESSAGE);
if (result.error.getMessage() != null)
{
builder.text(result.error.getMessage());
}
else
{
builder.text(result.error.getClass().getName());
}
builder.endElement();
}
builder.endElement();
}
builder.endElement();
}
builder.endElement();
builder.endDocument();
// Write report to file
final OutputStream reportOut = Files.newFileOutputStream(file);
final Serializer serializer = new Serializer();
serializer.setOutputStream(reportOut);
serializer.setOutputProperty(Property.INDENT, "yes");
try
{
processor.writeXdmValue(builder.getNode(), serializer);
}
catch (final SaxonApiException e)
{
throw new IllegalStateException(e);
}
finally
{
Closeables.closeQuietly(reportOut);
}
}
|
diff --git a/src/main/java/com/radonsky/monkeysched/Main.java b/src/main/java/com/radonsky/monkeysched/Main.java
index 6172c8e..9add252 100644
--- a/src/main/java/com/radonsky/monkeysched/Main.java
+++ b/src/main/java/com/radonsky/monkeysched/Main.java
@@ -1,24 +1,24 @@
package com.radonsky.monkeysched;
import static org.joda.time.DateTime.now;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
TimeRule timeRule = RuleEngine.getDefault().getTimeRule();
DateTime currentTime = now();
DateTimeFormatter fmt = DateTimeFormat.fullDateTime();
System.out.println("The current time is " + fmt.print(currentTime));
boolean canRun = timeRule.apply(currentTime);
if (canRun) {
System.out.println("Monkeys can cause havoc now!");
} else {
- System.out.println("Monkeys should sleep now.");
+ System.out.println("Monkeys should be sleeping now.");
}
}
}
| true | true | public static void main(String[] args) {
TimeRule timeRule = RuleEngine.getDefault().getTimeRule();
DateTime currentTime = now();
DateTimeFormatter fmt = DateTimeFormat.fullDateTime();
System.out.println("The current time is " + fmt.print(currentTime));
boolean canRun = timeRule.apply(currentTime);
if (canRun) {
System.out.println("Monkeys can cause havoc now!");
} else {
System.out.println("Monkeys should sleep now.");
}
}
| public static void main(String[] args) {
TimeRule timeRule = RuleEngine.getDefault().getTimeRule();
DateTime currentTime = now();
DateTimeFormatter fmt = DateTimeFormat.fullDateTime();
System.out.println("The current time is " + fmt.print(currentTime));
boolean canRun = timeRule.apply(currentTime);
if (canRun) {
System.out.println("Monkeys can cause havoc now!");
} else {
System.out.println("Monkeys should be sleeping now.");
}
}
|
diff --git a/src/org/jruby/RubyBigDecimal.java b/src/org/jruby/RubyBigDecimal.java
index eb551a6a1..e1772fa95 100644
--- a/src/org/jruby/RubyBigDecimal.java
+++ b/src/org/jruby/RubyBigDecimal.java
@@ -1,525 +1,525 @@
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2006 Ola Bini <[email protected]>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
/**
* $Id: $
*/
package org.jruby;
import java.math.BigDecimal;
import org.jruby.runtime.CallbackFactory;
import org.jruby.runtime.builtin.IRubyObject;
/**
* @author <a href="mailto:[email protected]">Ola Bini</a>
* @version $Revision: 1.2 $
*/
public class RubyBigDecimal extends RubyNumeric {
public static RubyClass createBigDecimal(IRuby runtime) {
RubyClass result = runtime.defineClass("BigDecimal",runtime.getClass("Numeric"));
result.setConstant("ROUND_DOWN",RubyNumeric.int2fix(runtime,BigDecimal.ROUND_DOWN));
result.setConstant("SIGN_POSITIVE_INFINITE",RubyNumeric.int2fix(runtime,3));
result.setConstant("EXCEPTION_OVERFLOW",RubyNumeric.int2fix(runtime,1));
result.setConstant("SIGN_POSITIVE_ZERO",RubyNumeric.int2fix(runtime,1));
result.setConstant("EXCEPTION_ALL",RubyNumeric.int2fix(runtime,255));
result.setConstant("ROUND_CEILING",RubyNumeric.int2fix(runtime,BigDecimal.ROUND_CEILING));
result.setConstant("ROUND_UP",RubyNumeric.int2fix(runtime,BigDecimal.ROUND_UP));
result.setConstant("SIGN_NEGATIVE_FINITE",RubyNumeric.int2fix(runtime,-2));
result.setConstant("EXCEPTION_UNDERFLOW",RubyNumeric.int2fix(runtime, 4));
result.setConstant("SIGN_NaN",RubyNumeric.int2fix(runtime, 0));
result.setConstant("BASE",RubyNumeric.int2fix(runtime,10000));
result.setConstant("ROUND_HALF_DOWN",RubyNumeric.int2fix(runtime,BigDecimal.ROUND_HALF_DOWN));
result.setConstant("ROUND_MODE",RubyNumeric.int2fix(runtime,256));
result.setConstant("SIGN_POSITIVE_FINITE",RubyNumeric.int2fix(runtime,2));
result.setConstant("EXCEPTION_INFINITY",RubyNumeric.int2fix(runtime,1));
result.setConstant("ROUND_HALF_EVEN",RubyNumeric.int2fix(runtime,BigDecimal.ROUND_HALF_EVEN));
result.setConstant("ROUND_HALF_UP",RubyNumeric.int2fix(runtime,BigDecimal.ROUND_HALF_UP));
result.setConstant("SIGN_NEGATIVE_INFINITE",RubyNumeric.int2fix(runtime,-3));
result.setConstant("EXCEPTION_ZERODIVIDE",RubyNumeric.int2fix(runtime,1));
result.setConstant("SIGN_NEGATIVE_ZERO",RubyNumeric.int2fix(runtime,-1));
result.setConstant("EXCEPTION_NaN",RubyNumeric.int2fix(runtime,2));
result.setConstant("ROUND_FLOOR",RubyNumeric.int2fix(runtime,BigDecimal.ROUND_FLOOR));
CallbackFactory callbackFactory = runtime.callbackFactory(RubyBigDecimal.class);
runtime.getModule("Kernel").defineModuleFunction("BigDecimal",callbackFactory.getOptSingletonMethod("newCreate"));
result.defineSingletonMethod("new", callbackFactory.getOptSingletonMethod("newCreate"));
result.defineSingletonMethod("ver", callbackFactory.getSingletonMethod("ver"));
result.defineSingletonMethod("_load", callbackFactory.getSingletonMethod("_load",IRubyObject.class));
result.defineSingletonMethod("double_fig", callbackFactory.getSingletonMethod("double_fig"));
result.defineSingletonMethod("limit", callbackFactory.getSingletonMethod("limit",RubyFixnum.class));
result.defineSingletonMethod("mode", callbackFactory.getSingletonMethod("mode",RubyFixnum.class,RubyFixnum.class));
result.defineMethod("initialize", callbackFactory.getOptMethod("initialize"));
result.defineMethod("%", callbackFactory.getMethod("mod",IRubyObject.class));
result.defineMethod("modulo", callbackFactory.getMethod("mod",IRubyObject.class));
result.defineMethod("*", callbackFactory.getOptMethod("mult"));
result.defineMethod("mult", callbackFactory.getOptMethod("mult"));
result.defineMethod("**", callbackFactory.getMethod("power",RubyInteger.class));
result.defineMethod("power", callbackFactory.getMethod("power",RubyInteger.class));
result.defineMethod("+", callbackFactory.getOptMethod("add"));
result.defineMethod("add", callbackFactory.getOptMethod("add"));
result.defineMethod("-", callbackFactory.getOptMethod("sub"));
result.defineMethod("sub", callbackFactory.getOptMethod("sub"));
result.defineMethod("/", callbackFactory.getOptMethod("div"));
result.defineMethod("div", callbackFactory.getOptMethod("div"));
result.defineMethod("quo", callbackFactory.getOptMethod("div"));
result.defineMethod("<=>", callbackFactory.getMethod("spaceship",IRubyObject.class));
result.defineMethod("==", callbackFactory.getMethod("eql_p",IRubyObject.class));
result.defineMethod("===", callbackFactory.getMethod("eql_p",IRubyObject.class));
result.defineMethod("eql?", callbackFactory.getMethod("eql_p",IRubyObject.class));
result.defineMethod("!=", callbackFactory.getMethod("ne",IRubyObject.class));
result.defineMethod("<", callbackFactory.getMethod("lt",IRubyObject.class));
result.defineMethod("<=", callbackFactory.getMethod("le",IRubyObject.class));
result.defineMethod(">", callbackFactory.getMethod("gt",IRubyObject.class));
result.defineMethod(">=", callbackFactory.getMethod("ge",IRubyObject.class));
result.defineMethod("abs", callbackFactory.getMethod("abs"));
result.defineMethod("ceil", callbackFactory.getMethod("ceil",RubyInteger.class));
result.defineMethod("coerce", callbackFactory.getMethod("coerce",IRubyObject.class));
result.defineMethod("divmod", callbackFactory.getMethod("divmod",IRubyObject.class));
result.defineMethod("exponent", callbackFactory.getMethod("exponent"));
result.defineMethod("finite?", callbackFactory.getMethod("finite_p"));
result.defineMethod("fix", callbackFactory.getMethod("fix"));
result.defineMethod("floor", callbackFactory.getMethod("floor",RubyInteger.class));
result.defineMethod("frac", callbackFactory.getMethod("frac"));
result.defineMethod("infinite?", callbackFactory.getMethod("infinite_p"));
result.defineMethod("inspect", callbackFactory.getMethod("inspect"));
result.defineMethod("nan?", callbackFactory.getMethod("nan_p"));
result.defineMethod("nonzero?", callbackFactory.getMethod("nonzero_p"));
result.defineMethod("precs", callbackFactory.getMethod("precs"));
result.defineMethod("remainder", callbackFactory.getMethod("remainder",IRubyObject.class));
result.defineMethod("round", callbackFactory.getOptMethod("round"));
result.defineMethod("sign", callbackFactory.getMethod("sign"));
result.defineMethod("split", callbackFactory.getMethod("split"));
result.defineMethod("sqrt", callbackFactory.getOptMethod("sqrt"));
result.defineMethod("to_f", callbackFactory.getMethod("to_f"));
result.defineMethod("to_i", callbackFactory.getMethod("to_i"));
result.defineMethod("to_int", callbackFactory.getMethod("to_int"));
result.defineMethod("to_s", callbackFactory.getOptMethod("to_s"));
result.defineMethod("truncate", callbackFactory.getOptMethod("truncate"));
result.defineMethod("zero?", callbackFactory.getMethod("zero_p"));
return result;
}
private BigDecimal value;
public RubyBigDecimal(IRuby runtime) {
this(runtime, new BigDecimal("0"));
}
public RubyBigDecimal(IRuby runtime, BigDecimal value) {
super(runtime,runtime.getClass("BigDecimal"));
this.value = value;
}
public static RubyBigDecimal newCreate(IRubyObject recv, IRubyObject[] args) {
RubyBigDecimal result = new RubyBigDecimal(recv.getRuntime());
result.callInit(args);
return result;
}
public static IRubyObject ver(IRubyObject recv) {
return recv.getRuntime().newString("1.0.1");
}
public static IRubyObject _load(IRubyObject recv, IRubyObject p1) {
// TODO: implement
return null;
}
public static IRubyObject double_fig(IRubyObject recv) {
return recv.getRuntime().newFixnum(20);
}
public static IRubyObject limit(IRubyObject recv, RubyFixnum p1) {
// TODO: implement
return null;
}
public static IRubyObject mode(IRubyObject recv, RubyFixnum mode, RubyFixnum value) {
// TODO: implement
return null;
}
public IRubyObject initialize(IRubyObject[] args) {
String ss = args[0].toString();
if(ss.trim().equals("")) {
ss = "0";
}
this.value = new BigDecimal(ss);
return this;
}
public IRubyObject mod(IRubyObject arg) {
// TODO: implement
return this;
}
public IRubyObject mult(IRubyObject[] args) {
// TODO: better implementation
RubyBigDecimal val = null;
if(args[0] instanceof RubyBigDecimal) {
val = (RubyBigDecimal)args[0];
} else {
val = (RubyBigDecimal)args[0].callMethod(getRuntime().getCurrentContext(), "to_d");
}
return new RubyBigDecimal(getRuntime(),value.multiply(val.value));
}
public IRubyObject power(RubyInteger arg) {
// TODO: MUCH better implementation
BigDecimal val = value;
for(int i=0,j=RubyNumeric.fix2int(arg);i<j;i++) {
val = val.multiply(val);
}
return new RubyBigDecimal(getRuntime(),val);
}
public IRubyObject add(IRubyObject[] args) {
// TODO: better implementation
RubyBigDecimal val = null;
if(args[0] instanceof RubyBigDecimal) {
val = (RubyBigDecimal)args[0];
} else {
val = (RubyBigDecimal)args[0].callMethod(getRuntime().getCurrentContext(), "to_d");
}
return new RubyBigDecimal(getRuntime(),value.add(val.value));
}
public IRubyObject sub(IRubyObject[] args) {
// TODO: better implementation
RubyBigDecimal val = null;
if(args[0] instanceof RubyBigDecimal) {
val = (RubyBigDecimal)args[0];
} else {
val = (RubyBigDecimal)args[0].callMethod(getRuntime().getCurrentContext(), "to_d");
}
return new RubyBigDecimal(getRuntime(),value.subtract(val.value));
}
public IRubyObject div(IRubyObject[] args) {
// TODO: better implementation
RubyBigDecimal val = null;
if(args[0] instanceof RubyBigDecimal) {
val = (RubyBigDecimal)args[0];
} else {
val = (RubyBigDecimal)args[0].callMethod(getRuntime().getCurrentContext(), "to_d");
}
return new RubyBigDecimal(getRuntime(),value.divide(val.value,BigDecimal.ROUND_HALF_EVEN));
}
private IRubyObject cmp(IRubyObject r, char op) {
int e = 0;
if(!(r instanceof RubyBigDecimal)) {
e = RubyNumeric.fix2int(callCoerced("<=>",r));
} else {
RubyBigDecimal rb = (RubyBigDecimal)r;
e = value.compareTo(rb.value);
}
switch(op) {
case '*': return getRuntime().newFixnum(e);
case '=': return (e==0)?getRuntime().getTrue():getRuntime().getFalse();
case '!': return (e!=0)?getRuntime().getTrue():getRuntime().getFalse();
case 'G': return (e>=0)?getRuntime().getTrue():getRuntime().getFalse();
case '>': return (e> 0)?getRuntime().getTrue():getRuntime().getFalse();
case 'L': return (e<=0)?getRuntime().getTrue():getRuntime().getFalse();
case '<': return (e< 0)?getRuntime().getTrue():getRuntime().getFalse();
}
return getRuntime().getNil();
}
public IRubyObject spaceship(IRubyObject arg) {
return cmp(arg,'*');
}
public IRubyObject eql_p(IRubyObject arg) {
return cmp(arg,'=');
}
public IRubyObject ne(IRubyObject arg) {
return cmp(arg,'!');
}
public IRubyObject lt(IRubyObject arg) {
return cmp(arg,'<');
}
public IRubyObject le(IRubyObject arg) {
return cmp(arg,'L');
}
public IRubyObject gt(IRubyObject arg) {
return cmp(arg,'>');
}
public IRubyObject ge(IRubyObject arg) {
return cmp(arg,'G');
}
public RubyNumeric abs() {
return new RubyBigDecimal(getRuntime(),value.abs());
}
public IRubyObject ceil(RubyInteger arg) {
// TODO: implement correctly
return this;
}
public IRubyObject coerce(IRubyObject other) {
IRubyObject obj;
if(other instanceof RubyFloat) {
obj = getRuntime().newArray(other,to_f());
} else {
obj = getRuntime().newArray(newCreate(other,new IRubyObject[]{other.callMethod(getRuntime().getCurrentContext(),"to_s")}),this);
}
return obj;
}
public double getDoubleValue() { return value.doubleValue(); }
public long getLongValue() { return value.longValue(); }
public IRubyObject divmod(IRubyObject arg) {
// TODO: implement
return getRuntime().getNil();
}
public IRubyObject exponent() {
BigDecimal abs = value.abs();
String unscaled = abs.unscaledValue().toString();
int exponent = abs.toString().indexOf('.');
return getRuntime().newFixnum(exponent);
}
public IRubyObject finite_p() {
// TODO: implement correctly
return getRuntime().getTrue();
}
public IRubyObject fix() {
// TODO: implement correctly
return this;
}
public IRubyObject floor(RubyInteger arg) {
// TODO: implement correctly
return this;
}
public IRubyObject frac() {
// TODO: implement correctly
return this;
}
public IRubyObject infinite_p() {
// TODO: implement correctly
return getRuntime().getFalse();
}
public IRubyObject inspect() {
StringBuffer val = new StringBuffer("#<BigDecimal:").append(Integer.toHexString(System.identityHashCode(this))).append(",");
val.append("'").append(this.callMethod(getRuntime().getCurrentContext(), "to_s")).append("'").append(",");
int len = value.abs().unscaledValue().toString().length();
int pow = len/4;
val.append(len).append("(").append((pow+1)*4).append(")").append(">");
return getRuntime().newString(val.toString());
}
public IRubyObject nan_p() {
// TODO: implement correctly
return getRuntime().getFalse();
}
public IRubyObject nonzero_p() {
return value.signum() != 0 ? getRuntime().getTrue() : getRuntime().getFalse();
}
public IRubyObject precs() {
// TODO: implement
return getRuntime().getNil();
}
public IRubyObject remainder(IRubyObject arg) {
// TODO: implement
return this;
}
public IRubyObject round(IRubyObject[] args) {
// TODO: implement
return this;
}
public IRubyObject sign() {
// TODO: implement correctly
return getRuntime().newFixnum(value.signum());
}
public IRubyObject split() {
// TODO: implement
return getRuntime().getNil();
}
public IRubyObject sqrt(IRubyObject[] args) {
// TODO: implement correctly
return new RubyBigDecimal(getRuntime(),new BigDecimal(Math.sqrt(value.doubleValue())));
}
public IRubyObject to_f() {
return RubyFloat.newFloat(getRuntime(),value.doubleValue());
}
public IRubyObject to_i() {
return RubyNumeric.int2fix(getRuntime(),value.longValue());
}
public IRubyObject to_int() {
// TODO: implement to handle infinity and stuff
return RubyNumeric.int2fix(getRuntime(),value.longValue());
}
public IRubyObject to_s(IRubyObject[] args) {
boolean engineering = true;
boolean pos_sign = false;
boolean pos_space = false;
int groups = 0;
if(args.length != 0 && !args[0].isNil()) {
String format = args[0].toString();
int start = 0;
int end = format.length();
if(format.length() > 0 && format.charAt(0) == '+') {
pos_sign = true;
start++;
} else if(format.length() > 0 && format.charAt(0) == ' ') {
pos_sign = true;
pos_space = true;
start++;
}
if(format.length() > 0 && format.charAt(format.length()-1) == 'F') {
engineering = false;
end--;
} else if(format.length() > 0 && format.charAt(format.length()-1) == 'E') {
engineering = true;
end--;
}
String nums = format.substring(start,end);
if(nums.length()>0) {
groups = Integer.parseInt(nums);
}
}
String out = null;
if(engineering) {
BigDecimal abs = value.abs();
String unscaled = abs.unscaledValue().toString();
int exponent = abs.toString().indexOf('.');
if(-1 == exponent) {
exponent = abs.toString().length();
}
int signum = value.signum();
StringBuffer build = new StringBuffer();
build.append(signum == -1 ? "-" : (signum == 1 ? (pos_sign ? (pos_space ? " " : "+" ) : "") : ""));
build.append("0.");
if(0 == groups) {
build.append(unscaled);
} else {
int index = 0;
String sep = "";
while(index < unscaled.length()) {
int next = index+groups;
if(next > unscaled.length()) {
next = unscaled.length();
}
build.append(sep).append(unscaled.substring(index,next));
sep = " ";
index += groups;
}
}
build.append("E").append(exponent);
out = build.toString();
} else {
BigDecimal abs = value.abs();
String unscaled = abs.unscaledValue().toString();
int ix = abs.toString().indexOf('.');
String whole = unscaled;
String after = null;
if(ix != -1) {
whole = unscaled.substring(0,ix);
- after = unscaled.substring(ix+1);
+ after = unscaled.substring(ix);
}
int signum = value.signum();
StringBuffer build = new StringBuffer();
build.append(signum == -1 ? "-" : (signum == 1 ? (pos_sign ? (pos_space ? " " : "+" ) : "") : ""));
if(0 == groups) {
build.append(whole);
if(null != after) {
build.append(".").append(after);
}
} else {
int index = 0;
String sep = "";
while(index < whole.length()) {
int next = index+groups;
if(next > whole.length()) {
next = whole.length();
}
build.append(sep).append(whole.substring(index,next));
sep = " ";
index += groups;
}
if(null != after) {
build.append(".");
index = 0;
sep = "";
while(index < after.length()) {
int next = index+groups;
if(next > after.length()) {
next = after.length();
}
build.append(sep).append(after.substring(index,next));
sep = " ";
index += groups;
}
}
}
out = build.toString();
}
return getRuntime().newString(out);
}
public IRubyObject truncate(IRubyObject[] args) {
// TODO: implement
return this;
}
public RubyBoolean zero_p() {
return value.signum() == 0 ? getRuntime().getTrue() : getRuntime().getFalse();
}
}// RubyBigdecimal
| true | true | public IRubyObject to_s(IRubyObject[] args) {
boolean engineering = true;
boolean pos_sign = false;
boolean pos_space = false;
int groups = 0;
if(args.length != 0 && !args[0].isNil()) {
String format = args[0].toString();
int start = 0;
int end = format.length();
if(format.length() > 0 && format.charAt(0) == '+') {
pos_sign = true;
start++;
} else if(format.length() > 0 && format.charAt(0) == ' ') {
pos_sign = true;
pos_space = true;
start++;
}
if(format.length() > 0 && format.charAt(format.length()-1) == 'F') {
engineering = false;
end--;
} else if(format.length() > 0 && format.charAt(format.length()-1) == 'E') {
engineering = true;
end--;
}
String nums = format.substring(start,end);
if(nums.length()>0) {
groups = Integer.parseInt(nums);
}
}
String out = null;
if(engineering) {
BigDecimal abs = value.abs();
String unscaled = abs.unscaledValue().toString();
int exponent = abs.toString().indexOf('.');
if(-1 == exponent) {
exponent = abs.toString().length();
}
int signum = value.signum();
StringBuffer build = new StringBuffer();
build.append(signum == -1 ? "-" : (signum == 1 ? (pos_sign ? (pos_space ? " " : "+" ) : "") : ""));
build.append("0.");
if(0 == groups) {
build.append(unscaled);
} else {
int index = 0;
String sep = "";
while(index < unscaled.length()) {
int next = index+groups;
if(next > unscaled.length()) {
next = unscaled.length();
}
build.append(sep).append(unscaled.substring(index,next));
sep = " ";
index += groups;
}
}
build.append("E").append(exponent);
out = build.toString();
} else {
BigDecimal abs = value.abs();
String unscaled = abs.unscaledValue().toString();
int ix = abs.toString().indexOf('.');
String whole = unscaled;
String after = null;
if(ix != -1) {
whole = unscaled.substring(0,ix);
after = unscaled.substring(ix+1);
}
int signum = value.signum();
StringBuffer build = new StringBuffer();
build.append(signum == -1 ? "-" : (signum == 1 ? (pos_sign ? (pos_space ? " " : "+" ) : "") : ""));
if(0 == groups) {
build.append(whole);
if(null != after) {
build.append(".").append(after);
}
} else {
int index = 0;
String sep = "";
while(index < whole.length()) {
int next = index+groups;
if(next > whole.length()) {
next = whole.length();
}
build.append(sep).append(whole.substring(index,next));
sep = " ";
index += groups;
}
if(null != after) {
build.append(".");
index = 0;
sep = "";
while(index < after.length()) {
int next = index+groups;
if(next > after.length()) {
next = after.length();
}
build.append(sep).append(after.substring(index,next));
sep = " ";
index += groups;
}
}
}
out = build.toString();
}
return getRuntime().newString(out);
}
| public IRubyObject to_s(IRubyObject[] args) {
boolean engineering = true;
boolean pos_sign = false;
boolean pos_space = false;
int groups = 0;
if(args.length != 0 && !args[0].isNil()) {
String format = args[0].toString();
int start = 0;
int end = format.length();
if(format.length() > 0 && format.charAt(0) == '+') {
pos_sign = true;
start++;
} else if(format.length() > 0 && format.charAt(0) == ' ') {
pos_sign = true;
pos_space = true;
start++;
}
if(format.length() > 0 && format.charAt(format.length()-1) == 'F') {
engineering = false;
end--;
} else if(format.length() > 0 && format.charAt(format.length()-1) == 'E') {
engineering = true;
end--;
}
String nums = format.substring(start,end);
if(nums.length()>0) {
groups = Integer.parseInt(nums);
}
}
String out = null;
if(engineering) {
BigDecimal abs = value.abs();
String unscaled = abs.unscaledValue().toString();
int exponent = abs.toString().indexOf('.');
if(-1 == exponent) {
exponent = abs.toString().length();
}
int signum = value.signum();
StringBuffer build = new StringBuffer();
build.append(signum == -1 ? "-" : (signum == 1 ? (pos_sign ? (pos_space ? " " : "+" ) : "") : ""));
build.append("0.");
if(0 == groups) {
build.append(unscaled);
} else {
int index = 0;
String sep = "";
while(index < unscaled.length()) {
int next = index+groups;
if(next > unscaled.length()) {
next = unscaled.length();
}
build.append(sep).append(unscaled.substring(index,next));
sep = " ";
index += groups;
}
}
build.append("E").append(exponent);
out = build.toString();
} else {
BigDecimal abs = value.abs();
String unscaled = abs.unscaledValue().toString();
int ix = abs.toString().indexOf('.');
String whole = unscaled;
String after = null;
if(ix != -1) {
whole = unscaled.substring(0,ix);
after = unscaled.substring(ix);
}
int signum = value.signum();
StringBuffer build = new StringBuffer();
build.append(signum == -1 ? "-" : (signum == 1 ? (pos_sign ? (pos_space ? " " : "+" ) : "") : ""));
if(0 == groups) {
build.append(whole);
if(null != after) {
build.append(".").append(after);
}
} else {
int index = 0;
String sep = "";
while(index < whole.length()) {
int next = index+groups;
if(next > whole.length()) {
next = whole.length();
}
build.append(sep).append(whole.substring(index,next));
sep = " ";
index += groups;
}
if(null != after) {
build.append(".");
index = 0;
sep = "";
while(index < after.length()) {
int next = index+groups;
if(next > after.length()) {
next = after.length();
}
build.append(sep).append(after.substring(index,next));
sep = " ";
index += groups;
}
}
}
out = build.toString();
}
return getRuntime().newString(out);
}
|
diff --git a/gdms/src/test/java/org/gdms/data/schema/MetadataUtilitiesTest.java b/gdms/src/test/java/org/gdms/data/schema/MetadataUtilitiesTest.java
index e130bc747..f97b98453 100644
--- a/gdms/src/test/java/org/gdms/data/schema/MetadataUtilitiesTest.java
+++ b/gdms/src/test/java/org/gdms/data/schema/MetadataUtilitiesTest.java
@@ -1,133 +1,138 @@
/*
* OrbisGIS is a GIS application dedicated to scientific spatial simulation.
* This cross-platform GIS is developed at French IRSTV institute and is able to
* manipulate and create vector and raster spatial information. OrbisGIS is
* distributed under GPL 3 license. It is produced by the "Atelier SIG" team of
* the IRSTV Institute <http://www.irstv.cnrs.fr/> CNRS FR 2488.
*
*
* Team leader Erwan BOCHER, scientific researcher,
*
* User support leader : Gwendall Petit, geomatic engineer.
*
*
* Copyright (C) 2007 Erwan BOCHER, Fernando GONZALEZ CORTES, Thomas LEDUC
*
* Copyright (C) 2010 Erwan BOCHER, Pierre-Yves FADET, Alexis GUEGANNO, Maxence LAURENT
*
* This file is part of OrbisGIS.
*
* OrbisGIS is free software: you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* OrbisGIS is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* OrbisGIS. If not, see <http://www.gnu.org/licenses/>.
*
* For more information, please consult: <http://www.orbisgis.org/>
*
* or contact directly:
* erwan.bocher _at_ ec-nantes.fr
* gwendall.petit _at_ ec-nantes.fr
*/
package org.gdms.data.schema;
import org.gdms.data.types.Type;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author ebocher
*/
public class MetadataUtilitiesTest {
private DefaultMetadata basicMetadata;
private DefaultMetadata geometryMetadata;
private DefaultMetadata rasterMetadata;
@Before
public void setUp() throws Exception {
basicMetadata = new DefaultMetadata();
basicMetadata.addField("name", Type.STRING);
basicMetadata.addField("surname", Type.STRING);
basicMetadata.addField("location", Type.STRING);
geometryMetadata = new DefaultMetadata();
geometryMetadata.addField("the_geom", Type.GEOMETRY);
geometryMetadata.addField("surname", Type.STRING);
geometryMetadata.addField("location", Type.STRING);
rasterMetadata = new DefaultMetadata();
rasterMetadata.addField("raster", Type.RASTER);
rasterMetadata.addField("surname", Type.STRING);
rasterMetadata.addField("location", Type.STRING);
}
@Test
public void testGetSpatialFieldIndex() throws Exception {
assertTrue(MetadataUtilities.getSpatialFieldIndex(basicMetadata) == -1);
assertTrue(MetadataUtilities.getSpatialFieldIndex(geometryMetadata) == 0);
assertTrue(MetadataUtilities.getSpatialFieldIndex(rasterMetadata) == 0);
}
@Test
public void testGetGeometryFieldIndex() throws Exception {
assertTrue(MetadataUtilities.getGeometryFieldIndex(basicMetadata) == -1);
assertTrue(MetadataUtilities.getGeometryFieldIndex(geometryMetadata) == 0);
assertTrue(MetadataUtilities.getGeometryFieldIndex(rasterMetadata) == -1);
}
@Test
public void testGetRasterFieldIndex() throws Exception {
assertTrue(MetadataUtilities.getRasterFieldIndex(basicMetadata) == -1);
assertTrue(MetadataUtilities.getRasterFieldIndex(geometryMetadata) == -1);
assertTrue(MetadataUtilities.getRasterFieldIndex(rasterMetadata) == 0);
}
@Test
public void testisGeometry() throws Exception {
assertTrue(!MetadataUtilities.isGeometry(basicMetadata));
assertTrue(MetadataUtilities.isGeometry(geometryMetadata));
assertTrue(!MetadataUtilities.isGeometry(rasterMetadata));
}
@Test
public void testisRaster() throws Exception {
assertTrue(!MetadataUtilities.isRaster(basicMetadata));
assertTrue(!MetadataUtilities.isRaster(geometryMetadata));
assertTrue(MetadataUtilities.isRaster(rasterMetadata));
}
@Test
public void testGeometryDimension() throws Exception{
DefaultMetadata dm = new DefaultMetadata();
dm.addField("name", Type.STRING);
dm.addField("point", Type.POINT);
dm.addField("MultiPoint", Type.MULTIPOINT);
dm.addField("LineString", Type.LINESTRING);
dm.addField("MultiLineString", Type.MULTILINESTRING);
dm.addField("Polygon", Type.POLYGON);
dm.addField("MultiPolygon", Type.MULTIPOLYGON);
dm.addField("Geometry", Type.GEOMETRY);
dm.addField("GeometryCollection", Type.GEOMETRYCOLLECTION);
- assertEquals(MetadataUtilities.getGeometryDimension(dm, 0),-1);
+ try{
+ int ret = MetadataUtilities.getGeometryDimension(dm, 0);
+ fail();
+ } catch(UnsupportedOperationException e){
+ assertTrue(true);
+ }
assertEquals(MetadataUtilities.getGeometryDimension(dm, 1),0);
assertEquals(MetadataUtilities.getGeometryDimension(dm, 2),0);
assertEquals(MetadataUtilities.getGeometryDimension(dm, 3),1);
assertEquals(MetadataUtilities.getGeometryDimension(dm, 4),1);
assertEquals(MetadataUtilities.getGeometryDimension(dm, 5),2);
assertEquals(MetadataUtilities.getGeometryDimension(dm, 6),2);
assertEquals(MetadataUtilities.getGeometryDimension(dm, 7),-1);
assertEquals(MetadataUtilities.getGeometryDimension(dm, 8),-1);
}
}
| true | true | public void testGeometryDimension() throws Exception{
DefaultMetadata dm = new DefaultMetadata();
dm.addField("name", Type.STRING);
dm.addField("point", Type.POINT);
dm.addField("MultiPoint", Type.MULTIPOINT);
dm.addField("LineString", Type.LINESTRING);
dm.addField("MultiLineString", Type.MULTILINESTRING);
dm.addField("Polygon", Type.POLYGON);
dm.addField("MultiPolygon", Type.MULTIPOLYGON);
dm.addField("Geometry", Type.GEOMETRY);
dm.addField("GeometryCollection", Type.GEOMETRYCOLLECTION);
assertEquals(MetadataUtilities.getGeometryDimension(dm, 0),-1);
assertEquals(MetadataUtilities.getGeometryDimension(dm, 1),0);
assertEquals(MetadataUtilities.getGeometryDimension(dm, 2),0);
assertEquals(MetadataUtilities.getGeometryDimension(dm, 3),1);
assertEquals(MetadataUtilities.getGeometryDimension(dm, 4),1);
assertEquals(MetadataUtilities.getGeometryDimension(dm, 5),2);
assertEquals(MetadataUtilities.getGeometryDimension(dm, 6),2);
assertEquals(MetadataUtilities.getGeometryDimension(dm, 7),-1);
assertEquals(MetadataUtilities.getGeometryDimension(dm, 8),-1);
}
| public void testGeometryDimension() throws Exception{
DefaultMetadata dm = new DefaultMetadata();
dm.addField("name", Type.STRING);
dm.addField("point", Type.POINT);
dm.addField("MultiPoint", Type.MULTIPOINT);
dm.addField("LineString", Type.LINESTRING);
dm.addField("MultiLineString", Type.MULTILINESTRING);
dm.addField("Polygon", Type.POLYGON);
dm.addField("MultiPolygon", Type.MULTIPOLYGON);
dm.addField("Geometry", Type.GEOMETRY);
dm.addField("GeometryCollection", Type.GEOMETRYCOLLECTION);
try{
int ret = MetadataUtilities.getGeometryDimension(dm, 0);
fail();
} catch(UnsupportedOperationException e){
assertTrue(true);
}
assertEquals(MetadataUtilities.getGeometryDimension(dm, 1),0);
assertEquals(MetadataUtilities.getGeometryDimension(dm, 2),0);
assertEquals(MetadataUtilities.getGeometryDimension(dm, 3),1);
assertEquals(MetadataUtilities.getGeometryDimension(dm, 4),1);
assertEquals(MetadataUtilities.getGeometryDimension(dm, 5),2);
assertEquals(MetadataUtilities.getGeometryDimension(dm, 6),2);
assertEquals(MetadataUtilities.getGeometryDimension(dm, 7),-1);
assertEquals(MetadataUtilities.getGeometryDimension(dm, 8),-1);
}
|
diff --git a/src/carnero/cgeo/cgeomap.java b/src/carnero/cgeo/cgeomap.java
index 8f778ef..6057a96 100644
--- a/src/carnero/cgeo/cgeomap.java
+++ b/src/carnero/cgeo/cgeomap.java
@@ -1,1535 +1,1535 @@
package carnero.cgeo;
import android.app.Activity;
import android.app.ProgressDialog;
import java.util.ArrayList;
import android.os.Bundle;
import android.view.Menu;
import android.view.SubMenu;
import android.view.MenuItem;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.widget.TextView;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import java.lang.reflect.Field;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
public class cgeomap extends MapActivity {
private Resources res = null;
private Activity activity = null;
private MapView mapView = null;
private MapController mapController = null;
private cgSettings settings = null;
private cgBase base = null;
private cgWarning warning = null;
private cgeoapplication app = null;
private SharedPreferences.Editor prefsEdit = null;
private cgGeo geo = null;
private cgDirection dir = null;
private cgUpdateLoc geoUpdate = new update();
private cgUpdateDir dirUpdate = new updateDir();
private boolean followLocation = false;
private boolean initLocation = true;
private cgMapOverlay overlay = null;
private cgUsersOverlay overlayUsers = null;
private cgOverlayScale overlayScale = null;
private cgMapMyOverlay overlayMyLoc = null;
private Drawable pin = null;
private boolean fromDetail = false;
private Double oneLatitude = null;
private Double oneLongitude = null;
private Long searchId = null;
private String geocode = null;
private Integer centerLatitude = null;
private Integer centerLongitude = null;
private Integer spanLatitude = null;
private Integer spanLongitude = null;
private Integer centerLatitudeUsers = null;
private Integer centerLongitudeUsers = null;
private Integer spanLatitudeUsers = null;
private Integer spanLongitudeUsers = null;
private ArrayList<cgCache> caches = new ArrayList<cgCache>();
private ArrayList<cgCoord> coordinates = new ArrayList<cgCoord>();
private ArrayList<cgUser> users = new ArrayList<cgUser>();
private loadCaches loadingThread = null;
private loadUsers usersThread = null;
private long closeShowed = 0l;
private int numberType = 0; // 0: altitude, 1: traveled distance
private TextView numberView = null;
private LinearLayout close = null;
private TextView closeGC = null;
private TextView closeDst = null;
private ImageView myLocation = null;
private ProgressDialog waitDialog = null;
private int detailTotal = 0;
private int detailProgress = 0;
private Long detailProgressTime = 0l;
private boolean firstRun = true;
private geocachesLoadDetails threadD = null;
private int closeCounter = 0;
private String usertoken = null;
protected boolean searching = false;
protected boolean searchingUsers = false;
protected boolean searchingForClose = false;
protected boolean live = false;
final private static HashMap<String, Integer> gcIconsClear = new HashMap<String, Integer>();
final private static HashMap<String, Integer> gcIcons = new HashMap<String, Integer>();
final private static HashMap<String, Integer> wpIcons = new HashMap<String, Integer>();
final private Handler startLoading = new Handler() {
@Override
public void handleMessage(Message msg) {
changeTitle(true);
}
};
final private Handler loadCacheFromDbHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
try {
if (app != null && searchId != null && app.getError(searchId) != null && app.getError(searchId).length() > 0) {
warning.showToast(res.getString(R.string.err_no_chaches));
changeTitle(false);
return;
}
addOverlays(true, true);
} catch (Exception e) {
Log.e(cgSettings.tag, "cgeomap.loadCacheFromDbHandler: " + e.toString());
changeTitle(false);
}
}
};
final private Handler loadCachesHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
try {
if (app != null && app.getError(searchId) != null && app.getError(searchId).length() > 0) {
warning.showToast(res.getString(R.string.err_download_fail) + app.getError(searchId) + ".");
searching = false;
changeTitle(false);
return;
}
addOverlays(true, false);
} catch (Exception e) {
Log.e(cgSettings.tag, "cgeomap.loadCachesHandler: " + e.toString());
searching = false;
changeTitle(false);
return;
} finally {
searching = false;
}
}
};
final private Handler loadUsersHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
try {
addOverlays(false, false);
} catch (Exception e) {
Log.e(cgSettings.tag, "cgeomap.loadUsersHandler: " + e.toString());
searchingUsers = false;
return;
} finally {
searchingUsers = false;
}
}
};
final private Handler loadDetailsHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == 0) {
if (waitDialog != null) {
Float diffTime = new Float((System.currentTimeMillis() - detailProgressTime) / 1000); // seconds left
Float oneCache = diffTime / detailProgress; // left time per cache
Float etaTime = (detailTotal - detailProgress) * oneCache; // seconds remaining
waitDialog.setProgress(detailProgress);
if (etaTime < (1 / 60)) {
waitDialog.setMessage(res.getString(R.string.caches_downloading) + res.getString(R.string.caches_eta_ltm));
} else {
waitDialog.setMessage(res.getString(R.string.caches_downloading) + String.format(Locale.getDefault(), "%.0f", (etaTime / 60)) + res.getString(R.string.caches_eta_mins));
}
}
} else {
if (waitDialog != null) {
waitDialog.dismiss();
waitDialog.setOnCancelListener(null);
}
if (geo == null) geo = app.startGeo(activity, geoUpdate, base, settings, warning, 0, 0);
if (settings.useCompass == 1 && dir == null) dir = app.startDir(activity, dirUpdate, warning);
}
}
};
final private Handler setCloseHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
try {
if (close == null) close = (LinearLayout)findViewById(R.id.close);
if (closeGC == null) closeGC = (TextView)findViewById(R.id.close_gc);
if (closeDst == null) closeDst = (TextView)findViewById(R.id.close_dst);
final int index = msg.what;
if (geo == null || caches == null || caches.isEmpty() == true || index == -1 || caches.size() <= index) {
if ((System.currentTimeMillis() - 5000) < closeShowed) {
close.setVisibility(View.GONE);
searchingForClose = false;
return;
}
}
cgCache cache = null;
try { // probably trying to get cache that doesn't exist in list
cache = caches.get(index);
} catch (Exception e) {
if ((System.currentTimeMillis() - 5000) < closeShowed) close.setVisibility(View.GONE);
searchingForClose = false;
return;
}
if (cache == null) {
if ((System.currentTimeMillis() - 5000) < closeShowed) close.setVisibility(View.GONE);
searchingForClose = false;
return;
}
final Double distance = base.getDistance(geo.latitudeNow, geo.longitudeNow, cache.latitude, cache.longitude);
close.setClickable(false);
close.setOnClickListener(null);
if (cache != null && geo != null && followLocation == true && geo.speedNow != null && geo.speedNow > 6) { // more than 6 m/s
if (closeCounter < 5) {
closeCounter ++;
} else {
closeShowed = System.currentTimeMillis();
close.setVisibility(View.VISIBLE);
if (geo != null) {
closeDst.setText(base.getHumanDistance(distance));
} else {
closeDst.setText("---");
}
if (cache.name != null && cache.name.length() > 0) {
closeGC.setText(cache.name);
} else {
closeGC.setText(cache.geocode);
}
if (cache.type != null && gcIcons.containsKey(cache.type) == true) { // cache icon
closeGC.setCompoundDrawablesWithIntrinsicBounds((Drawable)activity.getResources().getDrawable(gcIconsClear.get(cache.type)), null, null, null);
} else { // unknown cache type, "mystery" icon
closeGC.setCompoundDrawablesWithIntrinsicBounds((Drawable)activity.getResources().getDrawable(gcIconsClear.get("mystery")), null, null, null);
}
close.setClickable(true);
close.setOnClickListener(new closeClickListener(cache));
close.bringToFront();
closeCounter = 5;
}
} else {
if (closeCounter > 0) {
closeCounter --;
} else {
if (closeShowed < (System.currentTimeMillis() - (30 * 1000))) close.setVisibility(View.GONE);
closeCounter = 0;
}
}
} catch (Exception e) {
Log.e(cgSettings.tag, "cgeomap.setCloseHandler.handleMessage: " + e.toString());
}
searchingForClose = false;
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// class init
res = this.getResources();
activity = this;
app = (cgeoapplication)activity.getApplication();
app.setAction(null);
settings = new cgSettings(activity, getSharedPreferences(cgSettings.preferences, 0));
base = new cgBase(app, settings, getSharedPreferences(cgSettings.preferences, 0));
warning = new cgWarning(activity);
prefsEdit = getSharedPreferences(cgSettings.preferences, 0).edit();
// set layout
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
// set layout
if (settings.skin == 1) {
setTheme(R.style.light);
} else {
setTheme(R.style.dark);
}
setContentView(R.layout.map);
base.setTitle(activity, res.getString(R.string.map_map));
// google analytics
base.sendAnal(activity, "/map");
if (geo == null) geo = app.startGeo(activity, geoUpdate, base, settings, warning, 0, 0);
if (settings.useCompass == 1 && dir == null) dir = app.startDir(activity, dirUpdate, warning);
mapView = (MapView)findViewById(R.id.map);
mapController = mapView.getController();
mapView.getOverlays().clear();
if (overlayMyLoc == null) {
overlayMyLoc = new cgMapMyOverlay(settings);
mapView.getOverlays().add(overlayMyLoc);
}
// get parameters
Bundle extras = getIntent().getExtras();
if (extras != null) {
fromDetail = extras.getBoolean("detail");
searchId = extras.getLong("searchid");
geocode = extras.getString("geocode");
oneLatitude = extras.getDouble("latitude");
oneLongitude = extras.getDouble("longitude");
}
if (settings.maptype == settings.mapSatellite) {
mapView.setSatellite(true);
} else {
mapView.setSatellite(false);
}
mapView.setBuiltInZoomControls(true);
mapView.displayZoomControls(true);
mapController.setZoom(settings.mapzoom);
if ((searchId == null || searchId <= 0) && (oneLatitude == null || oneLongitude == null)) {
base.setTitle(activity, res.getString(R.string.map_live));
searchId = null;
live = true;
initLocation = false;
followLocation = true;
loadingThread = new loadCaches(loadCachesHandler, mapView);
loadingThread.enable();
loadingThread.start();
myLocationInMiddle();
} else if (searchId != null && searchId > 0) {
base.setTitle(activity, res.getString(R.string.map_map));
live = false;
initLocation = true;
followLocation = false;
(new loadCacheFromDb(loadCacheFromDbHandler)).start();
} else if (geocode != null && geocode.length() > 0) {
base.setTitle(activity, res.getString(R.string.map_map));
live = false;
initLocation = true;
followLocation = false;
(new loadCacheFromDb(loadCacheFromDbHandler)).start();
} else if (oneLatitude != null && oneLongitude != null) {
base.setTitle(activity, res.getString(R.string.map_map));
searchId = null;
live = false;
initLocation = true;
followLocation = false;
addOverlays(true, true);
}
if (myLocation == null) {
myLocation = (ImageView)findViewById(R.id.my_position);
if (followLocation == true) myLocation.setImageResource(R.drawable.my_location_on);
else myLocation.setImageResource(R.drawable.my_location_off);
myLocation.setOnClickListener(new myLocationListener());
}
usersThread = new loadUsers(loadUsersHandler, mapView);
if (settings.publicLoc == 1) {
usersThread.enable();
} else {
usersThread.disable();
}
usersThread.start();
if (geo != null) geoUpdate.updateLoc(geo);
if (dir != null) dirUpdate.updateDir(dir);
if (numberView == null) numberView = (TextView)findViewById(R.id.number);
numberView.setClickable(true);
numberView.setOnClickListener(new changeNumber());
numberView.setOnLongClickListener(new resetNumber());
}
@Override
protected boolean isRouteDisplayed() {
return false;
}
@Override
public void onResume() {
super.onResume();
app.setAction(null);
if (geo == null) geo = app.startGeo(activity, geoUpdate, base, settings, warning, 0, 0);
if (settings.useCompass == 1 && dir == null) dir = app.startDir(activity, dirUpdate, warning);
// restart loading threads
if (loadingThread != null) loadingThread.kill();
if (usersThread != null) usersThread.kill();
if (live == true) {
loadingThread = new loadCaches(loadCachesHandler, mapView);
loadingThread.enable();
loadingThread.start();
}
usersThread = new loadUsers(loadUsersHandler, mapView);
if (settings.publicLoc == 1) {
usersThread.enable();
} else {
usersThread.disable();
}
usersThread.start();
if (geo != null) geoUpdate.updateLoc(geo);
if (dir != null) dirUpdate.updateDir(dir);
}
@Override
public void onStop() {
if (dir != null) dir = app.removeDir();
if (geo != null) geo = app.removeGeo();
savePrefs();
if (mapView != null) mapView.destroyDrawingCache();
if (loadingThread != null) loadingThread.kill();
if (usersThread != null) usersThread.kill();
super.onStop();
}
@Override
public void onPause() {
if (loadingThread != null) loadingThread.kill();
if (usersThread != null) usersThread.kill();
if (dir != null) dir = app.removeDir();
if (geo != null) geo = app.removeGeo();
savePrefs();
if (mapView != null) mapView.destroyDrawingCache();
super.onPause();
}
@Override
public void onDestroy() {
if (loadingThread != null) loadingThread.kill();
if (usersThread != null) usersThread.kill();
if (dir != null) dir = app.removeDir();
if (geo != null) geo = app.removeGeo();
savePrefs();
if (mapView != null) {
mapView.destroyDrawingCache();
mapView = null;
}
try {
// clean up tiles from memory
Class<?> tileClass = Class.forName("com.google.googlenav.map.Tile");
Field fTileCache = tileClass.getDeclaredField("tileObjectCache");
fTileCache.setAccessible(true);
Object[] tileObjectCache = (Object[]) fTileCache.get(null);
for (int i = 0; i < tileObjectCache.length; i++) {
tileObjectCache[i] = null;
}
} catch (Exception e) {
Log.e(cgSettings.tag, "cgeomap.onDestroy: " + e.toString());
}
super.onDestroy();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, 2, 0, res.getString(R.string.map_trail_hide)).setIcon(android.R.drawable.ic_menu_recent_history);
menu.add(0, 3, 0, res.getString(R.string.map_live_disable)).setIcon(android.R.drawable.ic_menu_close_clear_cancel);
menu.add(0, 4, 0, res.getString(R.string.caches_store_offline)).setIcon(android.R.drawable.ic_menu_set_as).setVisible(false);
menu.add(0, 0, 0, res.getString(R.string.caches_on_map)).setIcon(android.R.drawable.ic_menu_mapmode);
SubMenu subMenu = menu.addSubMenu(0, 5, 0, res.getString(R.string.caches_select)).setIcon(android.R.drawable.ic_menu_myplaces);
if (coordinates.size() > 0) {
int cnt = 6;
for (cgCoord coordinate : coordinates) {
subMenu.add(0, cnt, 0, Html.fromHtml(coordinate.name) + " (" + coordinate.type + ")");
cnt ++;
}
}
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
MenuItem item;
try {
item = menu.findItem(0); // view
if (mapView != null && mapView.isSatellite() == false) item.setTitle(res.getString(R.string.map_view_satellite));
else item.setTitle(res.getString(R.string.map_view_map));
item = menu.findItem(2); // show trail
if (settings.maptrail == 1) item.setTitle(res.getString(R.string.map_trail_hide));
else item.setTitle(res.getString(R.string.map_trail_show));
item = menu.findItem(3); // live map
if (live == false) {
item.setVisible(false);
item.setTitle(res.getString(R.string.map_live_enable));
} else {
if (settings.maplive == 1) {
item.setTitle(res.getString(R.string.map_live_disable));
} else {
item.setTitle(res.getString(R.string.map_live_enable));
}
}
item = menu.findItem(4); // store loaded
if (live == true && caches != null && caches.size() > 0 && searching == false) item.setVisible(true);
else item.setVisible(false);
item = menu.findItem(5);
item.setVisible(false);
SubMenu subMenu = item.getSubMenu();
subMenu.clear();
if (coordinates.size() > 0) {
int cnt = 6;
for (cgCoord coordinate : coordinates) {
subMenu.add(0, cnt, 0, Html.fromHtml(coordinate.name) + " (" + coordinate.type + ")");
cnt ++;
}
item.setVisible(true);
}
} catch (Exception e) {
Log.e(cgSettings.tag, "cgeomap.onPrepareOptionsMenu: " + e.toString());
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == 0) {
if (mapView != null && mapView.isSatellite() == false) {
mapView.setSatellite(true);
prefsEdit.putInt("maptype", settings.mapSatellite);
prefsEdit.commit();
} else {
mapView.setSatellite(false);
prefsEdit.putInt("maptype", settings.mapClassic);
prefsEdit.commit();
}
return true;
} else if (id == 2) {
if (settings.maptrail == 1) {
prefsEdit.putInt("maptrail", 0);
prefsEdit.commit();
settings.maptrail = 0;
} else {
prefsEdit.putInt("maptrail", 1);
prefsEdit.commit();
settings.maptrail = 1;
}
} else if (id == 3) {
if (settings.maplive == 1) {
dismissClose();
settings.liveMapDisable();
} else {
dismissClose();
settings.liveMapEnable();
}
// reset last viewport to force load caches imediatelly
centerLatitude = null;
centerLongitude = null;
spanLatitude = null;
spanLongitude = null;
} else if (id == 4) {
ArrayList<String> geocodes = new ArrayList<String>();
try {
if (coordinates != null && coordinates.size() > 0) {
final GeoPoint mapCenter = mapView.getMapCenter();
final int mapCenterLat = mapCenter.getLatitudeE6();
final int mapCenterLon = mapCenter.getLongitudeE6();
final int mapSpanLat = mapView.getLatitudeSpan();
final int mapSpanLon = mapView.getLongitudeSpan();
for (cgCoord coord : coordinates) {
if (coord.geocode != null && coord.geocode.length() > 0) {
if (base.isCacheInViewPort(mapCenterLat, mapCenterLon, mapSpanLat, mapSpanLon, coord.latitude, coord.longitude) && app.isOffline(coord.geocode, null) == false) {
geocodes.add(coord.geocode);
}
}
}
}
} catch (Exception e) {
Log.e(cgSettings.tag, "cgeomap.onOptionsItemSelected.#4: " + e.toString());
}
detailTotal = geocodes.size();
if (detailTotal == 0) {
warning.showToast(res.getString(R.string.warn_save_nothing));
return true;
}
waitDialog = new ProgressDialog(this);
waitDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface arg0) {
try {
if (threadD != null) threadD.kill();
if (geo == null) geo = app.startGeo(activity, geoUpdate, base, settings, warning, 0, 0);
if (settings.useCompass == 1 && dir == null) dir = app.startDir(activity, dirUpdate, warning);
} catch (Exception e) {
Log.e(cgSettings.tag, "cgeocaches.onPrepareOptionsMenu.onCancel: " + e.toString());
}
}
});
waitDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
Float etaTime = new Float((detailTotal * 7) / 60);
if (etaTime < 1) {
waitDialog.setMessage(res.getString(R.string.caches_downloading) + res.getString(R.string.caches_eta_ltm));
} else {
waitDialog.setMessage(res.getString(R.string.caches_downloading) + String.format(Locale.getDefault(), "%.0f", new Float((detailTotal * 7) / 60)) + res.getString(R.string.caches_eta_mins));
}
waitDialog.setCancelable(true);
waitDialog.setMax(detailTotal);
waitDialog.show();
detailProgressTime = System.currentTimeMillis();
threadD = new geocachesLoadDetails(loadDetailsHandler, geocodes);
threadD.start();
return true;
} else if (id > 5 && coordinates.get(id - 6) != null) {
try {
cgCoord coordinate = coordinates.get(id - 6);
followLocation = false;
centerMap(coordinate.latitude, coordinate.longitude);
} catch (Exception e) {
Log.e(cgSettings.tag, "cgeomap.onOptionsItemSelected: " + e.toString());
}
return true;
}
return false;
}
private void savePrefs() {
if (mapView == null) return;
if (prefsEdit == null) prefsEdit = getSharedPreferences(cgSettings.preferences, 0).edit();
if (mapView.isSatellite()) prefsEdit.putInt("maptype", settings.mapSatellite);
else prefsEdit.putInt("maptype", settings.mapClassic);
prefsEdit.putInt("mapzoom", mapView.getZoomLevel());
prefsEdit.commit();
if (mapView.isSatellite()) settings.maptype = settings.mapSatellite;
else settings.maptype = settings.mapClassic;
}
private void addOverlays(boolean canChangeTitle, boolean canInit) {
// scale bar
if (overlayScale == null && mapView != null) {
overlayScale = new cgOverlayScale(activity, base, settings);
mapView.getOverlays().add(overlayScale);
}
if (mapView.getOverlays().contains(overlayScale) == false) {
mapView.getOverlays().add(overlayScale);
}
mapView.invalidate();
// users
if (mapView == null) return;
// init images
if (gcIconsClear.isEmpty()) {
gcIconsClear.put("ape", R.drawable.type_ape);
gcIconsClear.put("cito", R.drawable.type_cito);
gcIconsClear.put("earth", R.drawable.type_earth);
gcIconsClear.put("event", R.drawable.type_event);
gcIconsClear.put("letterbox", R.drawable.type_letterbox);
gcIconsClear.put("locationless", R.drawable.type_locationless);
gcIconsClear.put("mega", R.drawable.type_mega);
gcIconsClear.put("multi", R.drawable.type_multi);
gcIconsClear.put("traditional", R.drawable.type_traditional);
gcIconsClear.put("virtual", R.drawable.type_virtual);
gcIconsClear.put("webcam", R.drawable.type_webcam);
gcIconsClear.put("wherigo", R.drawable.type_wherigo);
gcIconsClear.put("mystery", R.drawable.type_mystery);
}
if (gcIcons.isEmpty()) {
gcIcons.put("ape", R.drawable.marker_cache_ape);
gcIcons.put("cito", R.drawable.marker_cache_cito);
gcIcons.put("earth", R.drawable.marker_cache_earth);
gcIcons.put("event", R.drawable.marker_cache_event);
gcIcons.put("letterbox", R.drawable.marker_cache_letterbox);
gcIcons.put("locationless", R.drawable.marker_cache_locationless);
gcIcons.put("mega", R.drawable.marker_cache_mega);
gcIcons.put("multi", R.drawable.marker_cache_multi);
gcIcons.put("traditional", R.drawable.marker_cache_traditional);
gcIcons.put("virtual", R.drawable.marker_cache_virtual);
gcIcons.put("webcam", R.drawable.marker_cache_webcam);
gcIcons.put("wherigo", R.drawable.marker_cache_wherigo);
gcIcons.put("mystery", R.drawable.marker_cache_mystery);
gcIcons.put("ape-found", R.drawable.marker_cache_ape_found);
gcIcons.put("cito-found", R.drawable.marker_cache_cito_found);
gcIcons.put("earth-found", R.drawable.marker_cache_earth_found);
gcIcons.put("event-found", R.drawable.marker_cache_event_found);
gcIcons.put("letterbox-found", R.drawable.marker_cache_letterbox_found);
gcIcons.put("locationless-found", R.drawable.marker_cache_locationless_found);
gcIcons.put("mega-found", R.drawable.marker_cache_mega_found);
gcIcons.put("multi-found", R.drawable.marker_cache_multi_found);
gcIcons.put("traditional-found", R.drawable.marker_cache_traditional_found);
gcIcons.put("virtual-found", R.drawable.marker_cache_virtual_found);
gcIcons.put("webcam-found", R.drawable.marker_cache_webcam_found);
gcIcons.put("wherigo-found", R.drawable.marker_cache_wherigo_found);
gcIcons.put("mystery-found", R.drawable.marker_cache_mystery_found);
gcIcons.put("ape-disabled", R.drawable.marker_cache_ape_disabled);
gcIcons.put("cito-disabled", R.drawable.marker_cache_cito_disabled);
gcIcons.put("earth-disabled", R.drawable.marker_cache_earth_disabled);
gcIcons.put("event-disabled", R.drawable.marker_cache_event_disabled);
gcIcons.put("letterbox-disabled", R.drawable.marker_cache_letterbox_disabled);
gcIcons.put("locationless-disabled", R.drawable.marker_cache_locationless_disabled);
gcIcons.put("mega-disabled", R.drawable.marker_cache_mega_disabled);
gcIcons.put("multi-disabled", R.drawable.marker_cache_multi_disabled);
gcIcons.put("traditional-disabled", R.drawable.marker_cache_traditional_disabled);
gcIcons.put("virtual-disabled", R.drawable.marker_cache_virtual_disabled);
gcIcons.put("webcam-disabled", R.drawable.marker_cache_webcam_disabled);
gcIcons.put("wherigo-disabled", R.drawable.marker_cache_wherigo_disabled);
gcIcons.put("mystery-disabled", R.drawable.marker_cache_mystery_disabled);
}
if (wpIcons.isEmpty()) {
wpIcons.put("waypoint", R.drawable.marker_waypoint_waypoint);
wpIcons.put("flag", R.drawable.marker_waypoint_flag);
wpIcons.put("pkg", R.drawable.marker_waypoint_pkg);
wpIcons.put("puzzle", R.drawable.marker_waypoint_puzzle);
wpIcons.put("stage", R.drawable.marker_waypoint_stage);
wpIcons.put("trailhead", R.drawable.marker_waypoint_trailhead);
}
if (settings.publicLoc == 1 && users != null && users.isEmpty() == false) {
if (overlayUsers == null) {
overlayUsers = new cgUsersOverlay(app, (Context)this, base, getResources().getDrawable(R.drawable.user_location));
} else {
overlayUsers.disableTap();
overlayUsers.clearItems();
}
for (cgUser user : users) {
if (user.latitude == null && user.longitude == null) continue;
final cgOverlayUser item = new cgOverlayUser(activity, user);
pin = getResources().getDrawable(R.drawable.user_location);
pin.setBounds(0, 0, pin.getIntrinsicWidth(), pin.getIntrinsicHeight());
item.setMarker(pin);
overlayUsers.addItem(item);
}
if (mapView.getOverlays().contains(overlayUsers) == false) {
mapView.getOverlays().add(overlayUsers);
}
mapView.invalidate();
overlayUsers.enableTap();
}
searchingUsers = false;
// geocaches
if (overlay == null) {
overlay = new cgMapOverlay(app, (Context)this, base, getResources().getDrawable(R.drawable.marker), fromDetail);
} else {
overlay.disableTap();
overlay.clearItems();
}
Integer maxLat = Integer.MIN_VALUE;
Integer minLat = Integer.MAX_VALUE;
Integer maxLon = Integer.MIN_VALUE;
Integer minLon = Integer.MAX_VALUE;
GeoPoint geopoint = null;
int cachesWithCoords = 0;
coordinates.clear();
if (caches != null && caches.size() > 0) {
for (cgCache cache : caches) {
if (cache.latitude == null && cache.longitude == null) continue;
else cachesWithCoords ++;
String type = null;
if (cache.found == true) {
type = cache.type + "-found";
} else if (cache.disabled == true) {
type = cache.type + "-disabled";
} else {
type = cache.type;
}
if (type != null && gcIcons.containsKey(type) == true) {
pin = getResources().getDrawable(gcIcons.get(type));
} else {
pin = getResources().getDrawable(gcIcons.get("mystery"));
}
final cgCoord coord = new cgCoord(cache);
coordinates.add(coord);
final cgOverlayItem item = new cgOverlayItem(coord);
pin.setBounds(0, 0, pin.getIntrinsicWidth(), pin.getIntrinsicHeight());
item.setMarker(pin);
overlay.addItem(item);
final int latitudeE6 = (int)(cache.latitude * 1e6);
final int longitudeE6 = (int)(cache.longitude * 1e6);
if (latitudeE6 > maxLat) maxLat = latitudeE6;
if (latitudeE6 < minLat) minLat = latitudeE6;
if (longitudeE6 > maxLon) maxLon = longitudeE6;
if (longitudeE6 < minLon) minLon = longitudeE6;
}
if (cachesWithCoords == 0) {
warning.showToast(res.getString(R.string.warn_no_cache_coord));
myLocationInMiddleForce();
}
if (live == false) {
// there is only one cache
if (caches != null && caches.size() == 1 && cachesWithCoords > 0) {
cgCache oneCache = caches.get(0);
maxLat = (int)(oneCache.latitude * 1e6);
minLat = (int)(oneCache.latitude * 1e6);
maxLon = (int)(oneCache.longitude * 1e6);
minLon = (int)(oneCache.longitude * 1e6);
// waypoints
if (oneCache != null && oneCache.waypoints != null && oneCache.waypoints.size() > 0) {
for (cgWaypoint waypoint : oneCache.waypoints) {
if (waypoint.latitude == null && waypoint.longitude == null) continue;
if (waypoint.type != null && wpIcons.containsKey(waypoint.type) == true) {
pin = getResources().getDrawable(wpIcons.get(waypoint.type));
} else {
pin = getResources().getDrawable(wpIcons.get("waypoint"));
}
cgCoord coord = new cgCoord(waypoint);
coordinates.add(coord);
cgOverlayItem item = new cgOverlayItem(coord);
pin.setBounds(0, 0, pin.getIntrinsicWidth(), pin.getIntrinsicHeight());
item.setMarker(pin);
overlay.addItem(item);
int latitudeE6 = (int)(waypoint.latitude * 1e6);
int longitudeE6 = (int)(waypoint.longitude * 1e6);
if (latitudeE6 > maxLat) maxLat = latitudeE6;
if (latitudeE6 < minLat) minLat = latitudeE6;
if (longitudeE6 > maxLon) maxLon = longitudeE6;
if (longitudeE6 < minLon) minLon = longitudeE6;
coord = null;
}
}
int centerLat = 0;
int centerLon = 0;
if (coordinates.size() > 1) {
if ((Math.abs(maxLat) - Math.abs(minLat)) != 0) centerLat = minLat + ((maxLat - minLat) / 2);
if ((Math.abs(maxLon) - Math.abs(minLon)) != 0) centerLon = minLon + ((maxLon - minLon) / 2);
} else {
centerLat = (int)(oneCache.latitude * 1e6);
centerLon = (int)(oneCache.longitude * 1e6);
}
if (canInit == true && initLocation == true) {
mapController.animateTo(new GeoPoint(centerLat, centerLon));
if (Math.abs(maxLat - minLat) != 0 && Math.abs(maxLon - minLon) != 0) mapController.zoomToSpan(Math.abs(maxLat - minLat), Math.abs(maxLon - minLon));
initLocation = false;
}
} else {
int centerLat = 0;
int centerLon = 0;
if ((Math.abs(maxLat) - Math.abs(minLat)) != 0) centerLat = minLat + ((maxLat - minLat) / 2);
if ((Math.abs(maxLon) - Math.abs(minLon)) != 0) centerLon = minLon + ((maxLon - minLon) / 2);
if ((canInit == true || initLocation == true) && cachesWithCoords > 0) {
mapController.animateTo(new GeoPoint(centerLat, centerLon));
if (Math.abs(maxLat - minLat) != 0 && Math.abs(maxLon - minLon) != 0) mapController.zoomToSpan(Math.abs(maxLat - minLat), Math.abs(maxLon - minLon));
initLocation = false;
}
}
}
} else if (oneLatitude != null && oneLongitude != null) {
pin = getResources().getDrawable(wpIcons.get("waypoint"));
cgCoord coord = new cgCoord();
coord.type = "waypoint";
coord.latitude = oneLatitude;
coord.longitude = oneLongitude;
- coord.name = "some plase";
+ coord.name = "some place";
coordinates.add(coord);
cgOverlayItem item = new cgOverlayItem(coord);
pin.setBounds(0, 0, pin.getIntrinsicWidth(), pin.getIntrinsicHeight());
item.setMarker(pin);
overlay.addItem(item);
geopoint = new GeoPoint((int)(oneLatitude * 1e6), (int)(oneLongitude * 1e6));
if (canInit == true || initLocation == true) {
mapController.animateTo(geopoint);
initLocation = false;
}
}
if (mapView.getOverlays().contains(overlay) == false) {
mapView.getOverlays().add(overlay);
}
mapView.invalidate();
overlay.enableTap();
searching = false;
if (canChangeTitle == true) changeTitle(false);
}
private void myLocationInMiddle() {
if (followLocation == false && initLocation == false) return;
if (geo == null) return;
centerMap(geo.latitudeNow, geo.longitudeNow);
if (initLocation == true) initLocation = false;
}
private void myLocationInMiddleForce() {
if (geo == null) return;
centerMap(geo.latitudeNow, geo.longitudeNow);
}
private void centerMap(Double latitude, Double longitude) {
if (latitude == null || longitude == null) return;
if (mapView == null) return;
mapController.animateTo(new GeoPoint((int)(latitude * 1e6), (int)(longitude * 1e6)));
}
private class update extends cgUpdateLoc {
@Override
public void updateLoc(cgGeo geo) {
if (geo == null) return;
try {
if (overlayMyLoc == null && mapView != null) {
overlayMyLoc = new cgMapMyOverlay(settings);
mapView.getOverlays().add(overlayMyLoc);
}
if (overlayMyLoc != null && geo.location != null) overlayMyLoc.setCoordinates(geo.location);
(new findClose()).start();
if (geo.latitudeNow != null && geo.longitudeNow != null) {
if (followLocation == true) myLocationInMiddle();
}
if (settings.useCompass == 0 || (geo.speedNow != null && geo.speedNow > 5)) { // use GPS when speed is higher than 18 km/h
if (geo.bearingNow != null) overlayMyLoc.setHeading(geo.bearingNow);
else overlayMyLoc.setHeading(0.0f);
}
} catch (Exception e) {
Log.w(cgSettings.tag, "Failed to update location.");
}
setNumber();
}
}
private class updateDir extends cgUpdateDir {
@Override
public void updateDir(cgDirection dir) {
if (dir == null || dir.directionNow == null) return;
if (overlayMyLoc != null && mapView != null && (geo == null || geo.speedNow == null || geo.speedNow <= 5)) { // use compass when speed is lower than 18 km/h
overlayMyLoc.setHeading(dir.directionNow);
mapView.invalidate();
}
}
}
private class loadCacheFromDb extends Thread {
private Handler handler = null;
private loadCacheFromDb(Handler handlerIn) {
handler = handlerIn;
}
@Override
public void run() {
startLoading.sendEmptyMessage(0);
if (searchId != null) {
caches = app.getCaches(searchId, false, true, false, false, false, false);
}
if (geocode != null && geocode.length() > 0) {
caches = new ArrayList<cgCache>();
caches.add(app.getCacheByGeocode(geocode, false, true, false, false, false, false));
}
handler.sendMessage(new Message());
}
}
// thread used just like timer
private class loadCaches extends Thread {
private boolean requestedKill = false;
private boolean enabled = true;
private Handler handler = null;
private String viewstate = null;
private MapView mapView = null;
private loadCaches(Handler handlerIn, MapView mapViewIn) {
handler = handlerIn;
mapView = mapViewIn;
}
protected void kill() {
requestedKill = true;
}
protected void enable() {
enabled = true;
}
protected void disable() {
enabled = false;
}
public boolean state() {
return enabled;
}
protected void setViewstate(String viewstateIn) {
viewstate = viewstateIn;
}
@Override
public void run() {
while (requestedKill == false) {
try {
if (firstRun == false) {
sleep(700);
} else {
firstRun = false;
}
if (enabled == true && mapView != null && searching == false) {
loadCachesReal realThread = new loadCachesReal(handler, mapView, viewstate);
realThread.start();
}
} catch (Exception e) {
Log.e(cgSettings.tag, "cgeomap.loadCaches: " + e.toString());
}
}
}
}
// thread that is downloading caches
private class loadCachesReal extends Thread {
private Handler handler = null;
private String viewstate = null;
private MapView mapView = null;
private Double latitudeT = null;
private Double latitudeB = null;
private Double longitudeL = null;
private Double longitudeR = null;
private loadCachesReal(Handler handlerIn, MapView mapViewIn, String viewstateIn) {
handler = handlerIn;
viewstate = viewstateIn;
mapView = mapViewIn;
}
@Override
public void run() {
GeoPoint center = mapView.getMapCenter();
int latitudeCenter = center.getLatitudeE6();
int longitudeCenter = center.getLongitudeE6();
int latitudeSpan = mapView.getLatitudeSpan();
int longitudeSpan = mapView.getLongitudeSpan();
if (
(centerLatitude == null || centerLongitude == null || spanLatitude == null || spanLongitude == null) || // first run
((
(Math.abs(latitudeSpan - spanLatitude) > 50) || // changed zoom
(Math.abs(longitudeSpan - spanLongitude) > 50) || // changed zoom
(Math.abs(latitudeCenter - centerLatitude) > (latitudeSpan / 6)) || // map moved
(Math.abs(longitudeCenter - centerLongitude) > (longitudeSpan / 6)) // map moved
) && (
base.isInViewPort(centerLatitude, centerLongitude, latitudeCenter, longitudeCenter, spanLatitude, spanLongitude, latitudeSpan, longitudeSpan) == false ||
caches.isEmpty() == true
))
) {
latitudeT = (latitudeCenter + (latitudeSpan / 2)) / 1e6;
latitudeB = (latitudeCenter - (latitudeSpan / 2)) / 1e6;
longitudeL = (longitudeCenter + (longitudeSpan / 2)) / 1e6;
longitudeR = (longitudeCenter - (longitudeSpan / 2)) / 1e6;
centerLatitude = latitudeCenter;
centerLongitude = longitudeCenter;
spanLatitude = latitudeSpan;
spanLongitude = longitudeSpan;
if (searching == false) {
searching = true;
startLoading.sendEmptyMessage(0);
if (settings.maplive == 1) { // live map - downloads caches from gc.com
if (usertoken == null) {
usertoken = base.getMapUserToken();
}
HashMap<String, String> params = new HashMap<String, String>();
params.put("usertoken", usertoken);
params.put("latitude-t", String.format((Locale)null, "%.6f", latitudeT));
params.put("latitude-b", String.format((Locale)null, "%.6f", latitudeB));
params.put("longitude-l", String.format((Locale)null, "%.6f", longitudeL));
params.put("longitude-r", String.format((Locale)null, "%.6f", longitudeR));
Log.i(cgSettings.tag, "Starting download caches for: " + String.format((Locale)null, "%.6f", latitudeT) + "," + String.format((Locale)null, "%.6f", longitudeL) + " | " + String.format((Locale)null, "%.6f", latitudeB) + "," + String.format((Locale)null, "%.6f", longitudeR));
searchId = base.searchByViewport(params, 0);
if (searchId != null && searchId > 0) {
if (loadingThread != null && app.getViewstate(searchId) != null) {
loadingThread.setViewstate(app.getViewstate(searchId));
}
caches.clear();
if (app.getCount(searchId) > 0) {
caches.addAll(app.getCaches(searchId, false, false, false, false, false, false));
}
}
} else { // dead map - uses stored caches
Log.i(cgSettings.tag, "Starting load offline caches for: " + String.format((Locale)null, "%.6f", latitudeT) + "," + String.format((Locale)null, "%.6f", longitudeL) + " | " + String.format((Locale)null, "%.6f", latitudeB) + "," + String.format((Locale)null, "%.6f", longitudeR));
searchId = app.getOfflineInViewport(latitudeT, longitudeL, latitudeB, longitudeR, settings.cacheType);
if (searchId != null && searchId > 0) {
if (loadingThread != null && app.getViewstate(searchId) != null) {
loadingThread.setViewstate(app.getViewstate(searchId));
}
caches.clear();
if (app.getCount(searchId) > 0) {
caches.addAll(app.getCaches(searchId, false, false, false, false, false, false));
}
}
}
Log.i(cgSettings.tag, "Caches found: " + caches.size());
handler.sendEmptyMessage(0);
}
}
}
}
private class loadUsers extends Thread {
private boolean requestedKill = false;
private boolean enabled = true;
private Handler handler = null;
private MapView mapView = null;
private Double latitudeT = null;
private Double latitudeB = null;
private Double longitudeL = null;
private Double longitudeR = null;
protected void kill() {
requestedKill = true;
}
protected void enable() {
enabled = true;
}
protected void disable() {
enabled = false;
}
public boolean state() {
return enabled;
}
private loadUsers(Handler handlerIn, MapView mapViewIn) {
setPriority(Thread.MIN_PRIORITY);
handler = handlerIn;
mapView = mapViewIn;
}
@Override
public void run() {
while (requestedKill == false) {
try {
sleep(500);
} catch (Exception e) {
// nothing
}
if (enabled == true && mapView != null) {
GeoPoint center = mapView.getMapCenter();
int latitudeCenter = center.getLatitudeE6();
int longitudeCenter = center.getLongitudeE6();
int latitudeSpan = mapView.getLatitudeSpan();
int longitudeSpan = mapView.getLongitudeSpan();
if (
(centerLatitudeUsers == null || centerLongitudeUsers == null || spanLatitudeUsers == null || spanLongitudeUsers == null) || // first run
((
(Math.abs(latitudeSpan - spanLatitudeUsers) > 50) || // changed zoom
(Math.abs(longitudeSpan - spanLongitudeUsers) > 50) || // changed zoom
(Math.abs(latitudeCenter - centerLatitudeUsers) > (latitudeSpan / 6)) || // map moved
(Math.abs(longitudeCenter - centerLongitudeUsers) > (longitudeSpan / 6)) // map moved
) && (
base.isInViewPort(centerLatitudeUsers, centerLongitudeUsers, latitudeCenter, longitudeCenter, spanLatitudeUsers, spanLongitudeUsers, latitudeSpan, longitudeSpan) == false ||
users == null || users.isEmpty() == true
))
) {
latitudeT = (latitudeCenter + (latitudeSpan / 2)) / 1e6;
latitudeB = (latitudeCenter - (latitudeSpan / 2)) / 1e6;
longitudeL = (longitudeCenter + (longitudeSpan / 2)) / 1e6;
longitudeR = (longitudeCenter - (longitudeSpan / 2)) / 1e6;
centerLatitudeUsers = latitudeCenter;
centerLongitudeUsers = longitudeCenter;
spanLatitudeUsers = latitudeSpan;
spanLongitudeUsers = longitudeSpan;
if (searchingUsers == false) {
Log.i(cgSettings.tag, "Starting download other users for: " + String.format((Locale)null, "%.6f", latitudeT) + "," + String.format((Locale)null, "%.6f", longitudeL) + " | " + String.format((Locale)null, "%.6f", latitudeB) + "," + String.format((Locale)null, "%.6f", longitudeR));
searchingUsers = true;
users = base.usersInViewport(settings.getUsername(), latitudeB, latitudeT, longitudeR, longitudeL);
}
handler.sendEmptyMessage(0);
}
}
}
}
}
private class findClose extends Thread {
public findClose() {
setPriority(Thread.MIN_PRIORITY);
}
@Override
public void run() {
if (searchingForClose == true) return;
searchingForClose = true;
try {
double distance = 0d;
double closestDistance = Double.POSITIVE_INFINITY;
int closestCache = -1;
if (geo != null && caches != null && caches.isEmpty() == false) {
for (cgCache oneCache : caches) {
distance = base.getDistance(geo.latitudeNow, geo.longitudeNow, oneCache.latitude, oneCache.longitude);
if (live == true && geo != null && distance < closestDistance) {
closestDistance = distance;
closestCache = caches.indexOf(oneCache);
}
}
}
setCloseHandler.sendEmptyMessage(closestCache);
} catch (Exception e) {
Log.e(cgSettings.tag, "cgeocaches.findClose.run: " + e.toString());
}
}
}
private class closeClickListener implements View.OnClickListener {
private cgCache cache = null;
public closeClickListener(cgCache cacheIn) {
cache = cacheIn;
}
public void onClick(View arg0) {
if (cache == null) return;
Intent cacheIntent = new Intent(activity, cgeodetail.class);
cacheIntent.putExtra("geocode", cache.geocode.toUpperCase());
activity.startActivity(cacheIntent);
}
}
public void dismissClose() {
if (close == null) close = (LinearLayout)findViewById(R.id.close);
close.setVisibility(View.GONE);
}
private class geocachesLoadDetails extends Thread {
private Handler handler = null;
private ArrayList<String> geocodes = null;
private volatile Boolean needToStop = false;
public geocachesLoadDetails(Handler handlerIn, ArrayList<String> geocodesIn) {
handler = handlerIn;
geocodes = geocodesIn;
}
public void kill() {
this.needToStop = true;
}
@Override
public void run() {
if (geocodes == null || geocodes.isEmpty()) return;
if (dir != null) dir = app.removeDir();
if (geo != null) geo = app.removeGeo();
Message msg = null;
for (String geocode : geocodes) {
try {
if (needToStop == true) {
Log.i(cgSettings.tag, "Stopped storing process.");
break;
}
try {
sleep(3000 + ((Double)(Math.random() * 3000)).intValue());
} catch (Exception e) {
Log.e(cgSettings.tag, "cgeomap.geocachesLoadDetails.sleep: " + e.toString());
}
if (needToStop == true) {
Log.i(cgSettings.tag, "Stopped storing process.");
break;
}
detailProgress ++;
base.storeCache(app, activity, null, geocode, handler);
msg = new Message();
msg.what = 0;
handler.sendMessage(msg);
} catch (Exception e) {
Log.e(cgSettings.tag, "cgeocaches.geocachesLoadDetails: " + e.toString());
}
yield();
}
msg = new Message();
msg.what = 1;
handler.sendMessage(msg);
}
}
protected void changeTitle(boolean loading) {
String title = null;
if (live == true) title = res.getString(R.string.map_live);
else title = res.getString(R.string.map_map);
if (loading == true) {
base.showProgress(activity, true);
base.setTitle(activity, title);
} else if (caches != null) {
base.showProgress(activity, false);
base.setTitle(activity, title + " (" + caches.size() + ")");
} else {
base.showProgress(activity, false);
base.setTitle(activity, title + res.getString(R.string.caches_no_caches));
}
}
private class myLocationListener implements View.OnClickListener {
public void onClick(View view) {
if (myLocation == null) myLocation = (ImageView)findViewById(R.id.my_position);
if (followLocation == true) {
followLocation = false;
myLocation.setImageResource(R.drawable.my_location_off);
} else {
followLocation = true;
myLocationInMiddle();
myLocation.setImageResource(R.drawable.my_location_on);
}
}
}
public void setNumber() {
try {
if (numberView == null) numberView = (TextView)findViewById(R.id.number);
if (numberType >= 0 && numberView.getVisibility() != View.VISIBLE) numberView.setVisibility(View.VISIBLE);
else if (numberType < 0 && numberView.getVisibility() != View.GONE) numberView.setVisibility(View.GONE);
if (numberType == 0 && geo != null) { // altitude
String humanAlt;
if (geo.altitudeNow != null) {
if (settings.units == settings.unitsImperial) {
humanAlt = String.format("%.0f", (geo.altitudeNow * 3.2808399)) + " ft";
} else {
humanAlt = String.format("%.0f", geo.altitudeNow) + " m";
}
} else {
humanAlt = "N/A";
}
numberView.setText(humanAlt);
numberView.bringToFront();
} else if (numberType == 1 && geo != null) { // travaled distance
numberView.setText(base.getHumanDistance(geo.distanceNow));
numberView.bringToFront();
}
} catch (Exception e) {
Log.w(cgSettings.tag, "Failed to update traveled distance.");
}
}
private class changeNumber implements View.OnClickListener {
public void onClick(View view) {
if (numberType < 1) numberType ++;
else numberType = 0;
setNumber();
if (numberType == 0) {
warning.showShortToast(res.getString(R.string.info_altitude));
} else if (numberType == 1) {
long dstSince = 0l;
String dstString = null;
dstSince = activity.getSharedPreferences(cgSettings.preferences, 0).getLong("dst-since", 0l);
if (dstSince > 0) {
Date dstDate = new Date(dstSince);
dstString = res.getString(R.string.info_since) + " " + base.dateOut.format(dstDate) + ", " + base.timeOut.format(dstDate) + ")";
} else {
dstString = "";
}
warning.showShortToast(res.getString(R.string.info_distance) + dstString);
}
}
}
private class resetNumber implements View.OnLongClickListener {
public boolean onLongClick(View view) {
if (numberType == 1) {
geo.distanceNow = 0f;
final SharedPreferences.Editor prefsEdit = activity.getSharedPreferences(cgSettings.preferences, 0).edit();
if (prefsEdit != null) {
prefsEdit.putFloat("dst", 0f);
prefsEdit.putLong("dst-since", System.currentTimeMillis());
prefsEdit.commit();
}
setNumber();
warning.showToast(res.getString(R.string.info_distance_cleared));
return true;
}
return false;
}
}
public void goHome(View view) {
base.goHome(activity);
}
}
| true | true | private void addOverlays(boolean canChangeTitle, boolean canInit) {
// scale bar
if (overlayScale == null && mapView != null) {
overlayScale = new cgOverlayScale(activity, base, settings);
mapView.getOverlays().add(overlayScale);
}
if (mapView.getOverlays().contains(overlayScale) == false) {
mapView.getOverlays().add(overlayScale);
}
mapView.invalidate();
// users
if (mapView == null) return;
// init images
if (gcIconsClear.isEmpty()) {
gcIconsClear.put("ape", R.drawable.type_ape);
gcIconsClear.put("cito", R.drawable.type_cito);
gcIconsClear.put("earth", R.drawable.type_earth);
gcIconsClear.put("event", R.drawable.type_event);
gcIconsClear.put("letterbox", R.drawable.type_letterbox);
gcIconsClear.put("locationless", R.drawable.type_locationless);
gcIconsClear.put("mega", R.drawable.type_mega);
gcIconsClear.put("multi", R.drawable.type_multi);
gcIconsClear.put("traditional", R.drawable.type_traditional);
gcIconsClear.put("virtual", R.drawable.type_virtual);
gcIconsClear.put("webcam", R.drawable.type_webcam);
gcIconsClear.put("wherigo", R.drawable.type_wherigo);
gcIconsClear.put("mystery", R.drawable.type_mystery);
}
if (gcIcons.isEmpty()) {
gcIcons.put("ape", R.drawable.marker_cache_ape);
gcIcons.put("cito", R.drawable.marker_cache_cito);
gcIcons.put("earth", R.drawable.marker_cache_earth);
gcIcons.put("event", R.drawable.marker_cache_event);
gcIcons.put("letterbox", R.drawable.marker_cache_letterbox);
gcIcons.put("locationless", R.drawable.marker_cache_locationless);
gcIcons.put("mega", R.drawable.marker_cache_mega);
gcIcons.put("multi", R.drawable.marker_cache_multi);
gcIcons.put("traditional", R.drawable.marker_cache_traditional);
gcIcons.put("virtual", R.drawable.marker_cache_virtual);
gcIcons.put("webcam", R.drawable.marker_cache_webcam);
gcIcons.put("wherigo", R.drawable.marker_cache_wherigo);
gcIcons.put("mystery", R.drawable.marker_cache_mystery);
gcIcons.put("ape-found", R.drawable.marker_cache_ape_found);
gcIcons.put("cito-found", R.drawable.marker_cache_cito_found);
gcIcons.put("earth-found", R.drawable.marker_cache_earth_found);
gcIcons.put("event-found", R.drawable.marker_cache_event_found);
gcIcons.put("letterbox-found", R.drawable.marker_cache_letterbox_found);
gcIcons.put("locationless-found", R.drawable.marker_cache_locationless_found);
gcIcons.put("mega-found", R.drawable.marker_cache_mega_found);
gcIcons.put("multi-found", R.drawable.marker_cache_multi_found);
gcIcons.put("traditional-found", R.drawable.marker_cache_traditional_found);
gcIcons.put("virtual-found", R.drawable.marker_cache_virtual_found);
gcIcons.put("webcam-found", R.drawable.marker_cache_webcam_found);
gcIcons.put("wherigo-found", R.drawable.marker_cache_wherigo_found);
gcIcons.put("mystery-found", R.drawable.marker_cache_mystery_found);
gcIcons.put("ape-disabled", R.drawable.marker_cache_ape_disabled);
gcIcons.put("cito-disabled", R.drawable.marker_cache_cito_disabled);
gcIcons.put("earth-disabled", R.drawable.marker_cache_earth_disabled);
gcIcons.put("event-disabled", R.drawable.marker_cache_event_disabled);
gcIcons.put("letterbox-disabled", R.drawable.marker_cache_letterbox_disabled);
gcIcons.put("locationless-disabled", R.drawable.marker_cache_locationless_disabled);
gcIcons.put("mega-disabled", R.drawable.marker_cache_mega_disabled);
gcIcons.put("multi-disabled", R.drawable.marker_cache_multi_disabled);
gcIcons.put("traditional-disabled", R.drawable.marker_cache_traditional_disabled);
gcIcons.put("virtual-disabled", R.drawable.marker_cache_virtual_disabled);
gcIcons.put("webcam-disabled", R.drawable.marker_cache_webcam_disabled);
gcIcons.put("wherigo-disabled", R.drawable.marker_cache_wherigo_disabled);
gcIcons.put("mystery-disabled", R.drawable.marker_cache_mystery_disabled);
}
if (wpIcons.isEmpty()) {
wpIcons.put("waypoint", R.drawable.marker_waypoint_waypoint);
wpIcons.put("flag", R.drawable.marker_waypoint_flag);
wpIcons.put("pkg", R.drawable.marker_waypoint_pkg);
wpIcons.put("puzzle", R.drawable.marker_waypoint_puzzle);
wpIcons.put("stage", R.drawable.marker_waypoint_stage);
wpIcons.put("trailhead", R.drawable.marker_waypoint_trailhead);
}
if (settings.publicLoc == 1 && users != null && users.isEmpty() == false) {
if (overlayUsers == null) {
overlayUsers = new cgUsersOverlay(app, (Context)this, base, getResources().getDrawable(R.drawable.user_location));
} else {
overlayUsers.disableTap();
overlayUsers.clearItems();
}
for (cgUser user : users) {
if (user.latitude == null && user.longitude == null) continue;
final cgOverlayUser item = new cgOverlayUser(activity, user);
pin = getResources().getDrawable(R.drawable.user_location);
pin.setBounds(0, 0, pin.getIntrinsicWidth(), pin.getIntrinsicHeight());
item.setMarker(pin);
overlayUsers.addItem(item);
}
if (mapView.getOverlays().contains(overlayUsers) == false) {
mapView.getOverlays().add(overlayUsers);
}
mapView.invalidate();
overlayUsers.enableTap();
}
searchingUsers = false;
// geocaches
if (overlay == null) {
overlay = new cgMapOverlay(app, (Context)this, base, getResources().getDrawable(R.drawable.marker), fromDetail);
} else {
overlay.disableTap();
overlay.clearItems();
}
Integer maxLat = Integer.MIN_VALUE;
Integer minLat = Integer.MAX_VALUE;
Integer maxLon = Integer.MIN_VALUE;
Integer minLon = Integer.MAX_VALUE;
GeoPoint geopoint = null;
int cachesWithCoords = 0;
coordinates.clear();
if (caches != null && caches.size() > 0) {
for (cgCache cache : caches) {
if (cache.latitude == null && cache.longitude == null) continue;
else cachesWithCoords ++;
String type = null;
if (cache.found == true) {
type = cache.type + "-found";
} else if (cache.disabled == true) {
type = cache.type + "-disabled";
} else {
type = cache.type;
}
if (type != null && gcIcons.containsKey(type) == true) {
pin = getResources().getDrawable(gcIcons.get(type));
} else {
pin = getResources().getDrawable(gcIcons.get("mystery"));
}
final cgCoord coord = new cgCoord(cache);
coordinates.add(coord);
final cgOverlayItem item = new cgOverlayItem(coord);
pin.setBounds(0, 0, pin.getIntrinsicWidth(), pin.getIntrinsicHeight());
item.setMarker(pin);
overlay.addItem(item);
final int latitudeE6 = (int)(cache.latitude * 1e6);
final int longitudeE6 = (int)(cache.longitude * 1e6);
if (latitudeE6 > maxLat) maxLat = latitudeE6;
if (latitudeE6 < minLat) minLat = latitudeE6;
if (longitudeE6 > maxLon) maxLon = longitudeE6;
if (longitudeE6 < minLon) minLon = longitudeE6;
}
if (cachesWithCoords == 0) {
warning.showToast(res.getString(R.string.warn_no_cache_coord));
myLocationInMiddleForce();
}
if (live == false) {
// there is only one cache
if (caches != null && caches.size() == 1 && cachesWithCoords > 0) {
cgCache oneCache = caches.get(0);
maxLat = (int)(oneCache.latitude * 1e6);
minLat = (int)(oneCache.latitude * 1e6);
maxLon = (int)(oneCache.longitude * 1e6);
minLon = (int)(oneCache.longitude * 1e6);
// waypoints
if (oneCache != null && oneCache.waypoints != null && oneCache.waypoints.size() > 0) {
for (cgWaypoint waypoint : oneCache.waypoints) {
if (waypoint.latitude == null && waypoint.longitude == null) continue;
if (waypoint.type != null && wpIcons.containsKey(waypoint.type) == true) {
pin = getResources().getDrawable(wpIcons.get(waypoint.type));
} else {
pin = getResources().getDrawable(wpIcons.get("waypoint"));
}
cgCoord coord = new cgCoord(waypoint);
coordinates.add(coord);
cgOverlayItem item = new cgOverlayItem(coord);
pin.setBounds(0, 0, pin.getIntrinsicWidth(), pin.getIntrinsicHeight());
item.setMarker(pin);
overlay.addItem(item);
int latitudeE6 = (int)(waypoint.latitude * 1e6);
int longitudeE6 = (int)(waypoint.longitude * 1e6);
if (latitudeE6 > maxLat) maxLat = latitudeE6;
if (latitudeE6 < minLat) minLat = latitudeE6;
if (longitudeE6 > maxLon) maxLon = longitudeE6;
if (longitudeE6 < minLon) minLon = longitudeE6;
coord = null;
}
}
int centerLat = 0;
int centerLon = 0;
if (coordinates.size() > 1) {
if ((Math.abs(maxLat) - Math.abs(minLat)) != 0) centerLat = minLat + ((maxLat - minLat) / 2);
if ((Math.abs(maxLon) - Math.abs(minLon)) != 0) centerLon = minLon + ((maxLon - minLon) / 2);
} else {
centerLat = (int)(oneCache.latitude * 1e6);
centerLon = (int)(oneCache.longitude * 1e6);
}
if (canInit == true && initLocation == true) {
mapController.animateTo(new GeoPoint(centerLat, centerLon));
if (Math.abs(maxLat - minLat) != 0 && Math.abs(maxLon - minLon) != 0) mapController.zoomToSpan(Math.abs(maxLat - minLat), Math.abs(maxLon - minLon));
initLocation = false;
}
} else {
int centerLat = 0;
int centerLon = 0;
if ((Math.abs(maxLat) - Math.abs(minLat)) != 0) centerLat = minLat + ((maxLat - minLat) / 2);
if ((Math.abs(maxLon) - Math.abs(minLon)) != 0) centerLon = minLon + ((maxLon - minLon) / 2);
if ((canInit == true || initLocation == true) && cachesWithCoords > 0) {
mapController.animateTo(new GeoPoint(centerLat, centerLon));
if (Math.abs(maxLat - minLat) != 0 && Math.abs(maxLon - minLon) != 0) mapController.zoomToSpan(Math.abs(maxLat - minLat), Math.abs(maxLon - minLon));
initLocation = false;
}
}
}
} else if (oneLatitude != null && oneLongitude != null) {
pin = getResources().getDrawable(wpIcons.get("waypoint"));
cgCoord coord = new cgCoord();
coord.type = "waypoint";
coord.latitude = oneLatitude;
coord.longitude = oneLongitude;
coord.name = "some plase";
coordinates.add(coord);
cgOverlayItem item = new cgOverlayItem(coord);
pin.setBounds(0, 0, pin.getIntrinsicWidth(), pin.getIntrinsicHeight());
item.setMarker(pin);
overlay.addItem(item);
geopoint = new GeoPoint((int)(oneLatitude * 1e6), (int)(oneLongitude * 1e6));
if (canInit == true || initLocation == true) {
mapController.animateTo(geopoint);
initLocation = false;
}
}
if (mapView.getOverlays().contains(overlay) == false) {
mapView.getOverlays().add(overlay);
}
mapView.invalidate();
overlay.enableTap();
searching = false;
if (canChangeTitle == true) changeTitle(false);
}
| private void addOverlays(boolean canChangeTitle, boolean canInit) {
// scale bar
if (overlayScale == null && mapView != null) {
overlayScale = new cgOverlayScale(activity, base, settings);
mapView.getOverlays().add(overlayScale);
}
if (mapView.getOverlays().contains(overlayScale) == false) {
mapView.getOverlays().add(overlayScale);
}
mapView.invalidate();
// users
if (mapView == null) return;
// init images
if (gcIconsClear.isEmpty()) {
gcIconsClear.put("ape", R.drawable.type_ape);
gcIconsClear.put("cito", R.drawable.type_cito);
gcIconsClear.put("earth", R.drawable.type_earth);
gcIconsClear.put("event", R.drawable.type_event);
gcIconsClear.put("letterbox", R.drawable.type_letterbox);
gcIconsClear.put("locationless", R.drawable.type_locationless);
gcIconsClear.put("mega", R.drawable.type_mega);
gcIconsClear.put("multi", R.drawable.type_multi);
gcIconsClear.put("traditional", R.drawable.type_traditional);
gcIconsClear.put("virtual", R.drawable.type_virtual);
gcIconsClear.put("webcam", R.drawable.type_webcam);
gcIconsClear.put("wherigo", R.drawable.type_wherigo);
gcIconsClear.put("mystery", R.drawable.type_mystery);
}
if (gcIcons.isEmpty()) {
gcIcons.put("ape", R.drawable.marker_cache_ape);
gcIcons.put("cito", R.drawable.marker_cache_cito);
gcIcons.put("earth", R.drawable.marker_cache_earth);
gcIcons.put("event", R.drawable.marker_cache_event);
gcIcons.put("letterbox", R.drawable.marker_cache_letterbox);
gcIcons.put("locationless", R.drawable.marker_cache_locationless);
gcIcons.put("mega", R.drawable.marker_cache_mega);
gcIcons.put("multi", R.drawable.marker_cache_multi);
gcIcons.put("traditional", R.drawable.marker_cache_traditional);
gcIcons.put("virtual", R.drawable.marker_cache_virtual);
gcIcons.put("webcam", R.drawable.marker_cache_webcam);
gcIcons.put("wherigo", R.drawable.marker_cache_wherigo);
gcIcons.put("mystery", R.drawable.marker_cache_mystery);
gcIcons.put("ape-found", R.drawable.marker_cache_ape_found);
gcIcons.put("cito-found", R.drawable.marker_cache_cito_found);
gcIcons.put("earth-found", R.drawable.marker_cache_earth_found);
gcIcons.put("event-found", R.drawable.marker_cache_event_found);
gcIcons.put("letterbox-found", R.drawable.marker_cache_letterbox_found);
gcIcons.put("locationless-found", R.drawable.marker_cache_locationless_found);
gcIcons.put("mega-found", R.drawable.marker_cache_mega_found);
gcIcons.put("multi-found", R.drawable.marker_cache_multi_found);
gcIcons.put("traditional-found", R.drawable.marker_cache_traditional_found);
gcIcons.put("virtual-found", R.drawable.marker_cache_virtual_found);
gcIcons.put("webcam-found", R.drawable.marker_cache_webcam_found);
gcIcons.put("wherigo-found", R.drawable.marker_cache_wherigo_found);
gcIcons.put("mystery-found", R.drawable.marker_cache_mystery_found);
gcIcons.put("ape-disabled", R.drawable.marker_cache_ape_disabled);
gcIcons.put("cito-disabled", R.drawable.marker_cache_cito_disabled);
gcIcons.put("earth-disabled", R.drawable.marker_cache_earth_disabled);
gcIcons.put("event-disabled", R.drawable.marker_cache_event_disabled);
gcIcons.put("letterbox-disabled", R.drawable.marker_cache_letterbox_disabled);
gcIcons.put("locationless-disabled", R.drawable.marker_cache_locationless_disabled);
gcIcons.put("mega-disabled", R.drawable.marker_cache_mega_disabled);
gcIcons.put("multi-disabled", R.drawable.marker_cache_multi_disabled);
gcIcons.put("traditional-disabled", R.drawable.marker_cache_traditional_disabled);
gcIcons.put("virtual-disabled", R.drawable.marker_cache_virtual_disabled);
gcIcons.put("webcam-disabled", R.drawable.marker_cache_webcam_disabled);
gcIcons.put("wherigo-disabled", R.drawable.marker_cache_wherigo_disabled);
gcIcons.put("mystery-disabled", R.drawable.marker_cache_mystery_disabled);
}
if (wpIcons.isEmpty()) {
wpIcons.put("waypoint", R.drawable.marker_waypoint_waypoint);
wpIcons.put("flag", R.drawable.marker_waypoint_flag);
wpIcons.put("pkg", R.drawable.marker_waypoint_pkg);
wpIcons.put("puzzle", R.drawable.marker_waypoint_puzzle);
wpIcons.put("stage", R.drawable.marker_waypoint_stage);
wpIcons.put("trailhead", R.drawable.marker_waypoint_trailhead);
}
if (settings.publicLoc == 1 && users != null && users.isEmpty() == false) {
if (overlayUsers == null) {
overlayUsers = new cgUsersOverlay(app, (Context)this, base, getResources().getDrawable(R.drawable.user_location));
} else {
overlayUsers.disableTap();
overlayUsers.clearItems();
}
for (cgUser user : users) {
if (user.latitude == null && user.longitude == null) continue;
final cgOverlayUser item = new cgOverlayUser(activity, user);
pin = getResources().getDrawable(R.drawable.user_location);
pin.setBounds(0, 0, pin.getIntrinsicWidth(), pin.getIntrinsicHeight());
item.setMarker(pin);
overlayUsers.addItem(item);
}
if (mapView.getOverlays().contains(overlayUsers) == false) {
mapView.getOverlays().add(overlayUsers);
}
mapView.invalidate();
overlayUsers.enableTap();
}
searchingUsers = false;
// geocaches
if (overlay == null) {
overlay = new cgMapOverlay(app, (Context)this, base, getResources().getDrawable(R.drawable.marker), fromDetail);
} else {
overlay.disableTap();
overlay.clearItems();
}
Integer maxLat = Integer.MIN_VALUE;
Integer minLat = Integer.MAX_VALUE;
Integer maxLon = Integer.MIN_VALUE;
Integer minLon = Integer.MAX_VALUE;
GeoPoint geopoint = null;
int cachesWithCoords = 0;
coordinates.clear();
if (caches != null && caches.size() > 0) {
for (cgCache cache : caches) {
if (cache.latitude == null && cache.longitude == null) continue;
else cachesWithCoords ++;
String type = null;
if (cache.found == true) {
type = cache.type + "-found";
} else if (cache.disabled == true) {
type = cache.type + "-disabled";
} else {
type = cache.type;
}
if (type != null && gcIcons.containsKey(type) == true) {
pin = getResources().getDrawable(gcIcons.get(type));
} else {
pin = getResources().getDrawable(gcIcons.get("mystery"));
}
final cgCoord coord = new cgCoord(cache);
coordinates.add(coord);
final cgOverlayItem item = new cgOverlayItem(coord);
pin.setBounds(0, 0, pin.getIntrinsicWidth(), pin.getIntrinsicHeight());
item.setMarker(pin);
overlay.addItem(item);
final int latitudeE6 = (int)(cache.latitude * 1e6);
final int longitudeE6 = (int)(cache.longitude * 1e6);
if (latitudeE6 > maxLat) maxLat = latitudeE6;
if (latitudeE6 < minLat) minLat = latitudeE6;
if (longitudeE6 > maxLon) maxLon = longitudeE6;
if (longitudeE6 < minLon) minLon = longitudeE6;
}
if (cachesWithCoords == 0) {
warning.showToast(res.getString(R.string.warn_no_cache_coord));
myLocationInMiddleForce();
}
if (live == false) {
// there is only one cache
if (caches != null && caches.size() == 1 && cachesWithCoords > 0) {
cgCache oneCache = caches.get(0);
maxLat = (int)(oneCache.latitude * 1e6);
minLat = (int)(oneCache.latitude * 1e6);
maxLon = (int)(oneCache.longitude * 1e6);
minLon = (int)(oneCache.longitude * 1e6);
// waypoints
if (oneCache != null && oneCache.waypoints != null && oneCache.waypoints.size() > 0) {
for (cgWaypoint waypoint : oneCache.waypoints) {
if (waypoint.latitude == null && waypoint.longitude == null) continue;
if (waypoint.type != null && wpIcons.containsKey(waypoint.type) == true) {
pin = getResources().getDrawable(wpIcons.get(waypoint.type));
} else {
pin = getResources().getDrawable(wpIcons.get("waypoint"));
}
cgCoord coord = new cgCoord(waypoint);
coordinates.add(coord);
cgOverlayItem item = new cgOverlayItem(coord);
pin.setBounds(0, 0, pin.getIntrinsicWidth(), pin.getIntrinsicHeight());
item.setMarker(pin);
overlay.addItem(item);
int latitudeE6 = (int)(waypoint.latitude * 1e6);
int longitudeE6 = (int)(waypoint.longitude * 1e6);
if (latitudeE6 > maxLat) maxLat = latitudeE6;
if (latitudeE6 < minLat) minLat = latitudeE6;
if (longitudeE6 > maxLon) maxLon = longitudeE6;
if (longitudeE6 < minLon) minLon = longitudeE6;
coord = null;
}
}
int centerLat = 0;
int centerLon = 0;
if (coordinates.size() > 1) {
if ((Math.abs(maxLat) - Math.abs(minLat)) != 0) centerLat = minLat + ((maxLat - minLat) / 2);
if ((Math.abs(maxLon) - Math.abs(minLon)) != 0) centerLon = minLon + ((maxLon - minLon) / 2);
} else {
centerLat = (int)(oneCache.latitude * 1e6);
centerLon = (int)(oneCache.longitude * 1e6);
}
if (canInit == true && initLocation == true) {
mapController.animateTo(new GeoPoint(centerLat, centerLon));
if (Math.abs(maxLat - minLat) != 0 && Math.abs(maxLon - minLon) != 0) mapController.zoomToSpan(Math.abs(maxLat - minLat), Math.abs(maxLon - minLon));
initLocation = false;
}
} else {
int centerLat = 0;
int centerLon = 0;
if ((Math.abs(maxLat) - Math.abs(minLat)) != 0) centerLat = minLat + ((maxLat - minLat) / 2);
if ((Math.abs(maxLon) - Math.abs(minLon)) != 0) centerLon = minLon + ((maxLon - minLon) / 2);
if ((canInit == true || initLocation == true) && cachesWithCoords > 0) {
mapController.animateTo(new GeoPoint(centerLat, centerLon));
if (Math.abs(maxLat - minLat) != 0 && Math.abs(maxLon - minLon) != 0) mapController.zoomToSpan(Math.abs(maxLat - minLat), Math.abs(maxLon - minLon));
initLocation = false;
}
}
}
} else if (oneLatitude != null && oneLongitude != null) {
pin = getResources().getDrawable(wpIcons.get("waypoint"));
cgCoord coord = new cgCoord();
coord.type = "waypoint";
coord.latitude = oneLatitude;
coord.longitude = oneLongitude;
coord.name = "some place";
coordinates.add(coord);
cgOverlayItem item = new cgOverlayItem(coord);
pin.setBounds(0, 0, pin.getIntrinsicWidth(), pin.getIntrinsicHeight());
item.setMarker(pin);
overlay.addItem(item);
geopoint = new GeoPoint((int)(oneLatitude * 1e6), (int)(oneLongitude * 1e6));
if (canInit == true || initLocation == true) {
mapController.animateTo(geopoint);
initLocation = false;
}
}
if (mapView.getOverlays().contains(overlay) == false) {
mapView.getOverlays().add(overlay);
}
mapView.invalidate();
overlay.enableTap();
searching = false;
if (canChangeTitle == true) changeTitle(false);
}
|
diff --git a/java/src/com/android/inputmethod/latin/LatinIME.java b/java/src/com/android/inputmethod/latin/LatinIME.java
index cf7eea70b..9dd5351f9 100644
--- a/java/src/com/android/inputmethod/latin/LatinIME.java
+++ b/java/src/com/android/inputmethod/latin/LatinIME.java
@@ -1,2439 +1,2435 @@
/*
* 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.inputmethod.latin;
import static com.android.inputmethod.latin.Constants.ImeOption.FORCE_ASCII;
import static com.android.inputmethod.latin.Constants.ImeOption.NO_MICROPHONE;
import static com.android.inputmethod.latin.Constants.ImeOption.NO_MICROPHONE_COMPAT;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Rect;
import android.inputmethodservice.InputMethodService;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.os.Debug;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Message;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.util.PrintWriterPrinter;
import android.util.Printer;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.CompletionInfo;
import android.view.inputmethod.CorrectionInfo;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodSubtype;
import com.android.inputmethod.accessibility.AccessibilityUtils;
import com.android.inputmethod.accessibility.AccessibleKeyboardViewProxy;
import com.android.inputmethod.compat.CompatUtils;
import com.android.inputmethod.compat.InputMethodManagerCompatWrapper;
import com.android.inputmethod.compat.InputMethodServiceCompatUtils;
import com.android.inputmethod.compat.SuggestionSpanUtils;
import com.android.inputmethod.keyboard.KeyDetector;
import com.android.inputmethod.keyboard.Keyboard;
import com.android.inputmethod.keyboard.KeyboardActionListener;
import com.android.inputmethod.keyboard.KeyboardId;
import com.android.inputmethod.keyboard.KeyboardSwitcher;
import com.android.inputmethod.keyboard.KeyboardView;
import com.android.inputmethod.keyboard.MainKeyboardView;
import com.android.inputmethod.latin.LocaleUtils.RunInLocale;
import com.android.inputmethod.latin.Utils.Stats;
import com.android.inputmethod.latin.define.ProductionFlag;
import com.android.inputmethod.latin.suggestions.SuggestionStripView;
import com.android.inputmethod.research.ResearchLogger;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Locale;
/**
* Input method implementation for Qwerty'ish keyboard.
*/
public final class LatinIME extends InputMethodService implements KeyboardActionListener,
SuggestionStripView.Listener, TargetApplicationGetter.OnTargetApplicationKnownListener,
Suggest.SuggestInitializationListener {
private static final String TAG = LatinIME.class.getSimpleName();
private static final boolean TRACE = false;
private static boolean DEBUG;
private static final int EXTENDED_TOUCHABLE_REGION_HEIGHT = 100;
// How many continuous deletes at which to start deleting at a higher speed.
private static final int DELETE_ACCELERATE_AT = 20;
// Key events coming any faster than this are long-presses.
private static final int QUICK_PRESS = 200;
private static final int PENDING_IMS_CALLBACK_DURATION = 800;
/**
* The name of the scheme used by the Package Manager to warn of a new package installation,
* replacement or removal.
*/
private static final String SCHEME_PACKAGE = "package";
private static final int SPACE_STATE_NONE = 0;
// Double space: the state where the user pressed space twice quickly, which LatinIME
// resolved as period-space. Undoing this converts the period to a space.
private static final int SPACE_STATE_DOUBLE = 1;
// Swap punctuation: the state where a weak space and a punctuation from the suggestion strip
// have just been swapped. Undoing this swaps them back; the space is still considered weak.
private static final int SPACE_STATE_SWAP_PUNCTUATION = 2;
// Weak space: a space that should be swapped only by suggestion strip punctuation. Weak
// spaces happen when the user presses space, accepting the current suggestion (whether
// it's an auto-correction or not).
private static final int SPACE_STATE_WEAK = 3;
// Phantom space: a not-yet-inserted space that should get inserted on the next input,
// character provided it's not a separator. If it's a separator, the phantom space is dropped.
// Phantom spaces happen when a user chooses a word from the suggestion strip.
private static final int SPACE_STATE_PHANTOM = 4;
// Current space state of the input method. This can be any of the above constants.
private int mSpaceState;
private SettingsValues mCurrentSettings;
private View mExtractArea;
private View mKeyPreviewBackingView;
private View mSuggestionsContainer;
private SuggestionStripView mSuggestionStripView;
/* package for tests */ Suggest mSuggest;
private CompletionInfo[] mApplicationSpecifiedCompletions;
private ApplicationInfo mTargetApplicationInfo;
private InputMethodManagerCompatWrapper mImm;
private Resources mResources;
private SharedPreferences mPrefs;
/* package for tests */ final KeyboardSwitcher mKeyboardSwitcher;
private final SubtypeSwitcher mSubtypeSwitcher;
private boolean mShouldSwitchToLastSubtype = true;
private boolean mIsMainDictionaryAvailable;
private UserBinaryDictionary mUserDictionary;
private UserHistoryDictionary mUserHistoryDictionary;
private boolean mIsUserDictionaryAvailable;
private LastComposedWord mLastComposedWord = LastComposedWord.NOT_A_COMPOSED_WORD;
private final WordComposer mWordComposer = new WordComposer();
private RichInputConnection mConnection = new RichInputConnection(this);
// Keep track of the last selection range to decide if we need to show word alternatives
private static final int NOT_A_CURSOR_POSITION = -1;
private int mLastSelectionStart = NOT_A_CURSOR_POSITION;
private int mLastSelectionEnd = NOT_A_CURSOR_POSITION;
// Whether we are expecting an onUpdateSelection event to fire. If it does when we don't
// "expect" it, it means the user actually moved the cursor.
private boolean mExpectingUpdateSelection;
private int mDeleteCount;
private long mLastKeyTime;
private AudioAndHapticFeedbackManager mFeedbackManager;
// Member variables for remembering the current device orientation.
private int mDisplayOrientation;
// Object for reacting to adding/removing a dictionary pack.
private BroadcastReceiver mDictionaryPackInstallReceiver =
new DictionaryPackInstallBroadcastReceiver(this);
// Keeps track of most recently inserted text (multi-character key) for reverting
private CharSequence mEnteredText;
private boolean mIsAutoCorrectionIndicatorOn;
private AlertDialog mOptionsDialog;
private final boolean mIsHardwareAcceleratedDrawingEnabled;
public final UIHandler mHandler = new UIHandler(this);
public static final class UIHandler extends StaticInnerHandlerWrapper<LatinIME> {
private static final int MSG_UPDATE_SHIFT_STATE = 0;
private static final int MSG_PENDING_IMS_CALLBACK = 1;
private static final int MSG_UPDATE_SUGGESTION_STRIP = 2;
private static final int MSG_SHOW_GESTURE_PREVIEW_AND_SUGGESTION_STRIP = 3;
private static final int ARG1_DISMISS_GESTURE_FLOATING_PREVIEW_TEXT = 1;
private int mDelayUpdateSuggestions;
private int mDelayUpdateShiftState;
private long mDoubleSpacesTurnIntoPeriodTimeout;
private long mDoubleSpaceTimerStart;
public UIHandler(final LatinIME outerInstance) {
super(outerInstance);
}
public void onCreate() {
final Resources res = getOuterInstance().getResources();
mDelayUpdateSuggestions =
res.getInteger(R.integer.config_delay_update_suggestions);
mDelayUpdateShiftState =
res.getInteger(R.integer.config_delay_update_shift_state);
mDoubleSpacesTurnIntoPeriodTimeout = res.getInteger(
R.integer.config_double_spaces_turn_into_period_timeout);
}
@Override
public void handleMessage(final Message msg) {
final LatinIME latinIme = getOuterInstance();
final KeyboardSwitcher switcher = latinIme.mKeyboardSwitcher;
switch (msg.what) {
case MSG_UPDATE_SUGGESTION_STRIP:
latinIme.updateSuggestionStrip();
break;
case MSG_UPDATE_SHIFT_STATE:
switcher.updateShiftState();
break;
case MSG_SHOW_GESTURE_PREVIEW_AND_SUGGESTION_STRIP:
latinIme.showGesturePreviewAndSuggestionStrip((SuggestedWords)msg.obj,
msg.arg1 == ARG1_DISMISS_GESTURE_FLOATING_PREVIEW_TEXT);
break;
}
}
public void postUpdateSuggestionStrip() {
sendMessageDelayed(obtainMessage(MSG_UPDATE_SUGGESTION_STRIP), mDelayUpdateSuggestions);
}
public void cancelUpdateSuggestionStrip() {
removeMessages(MSG_UPDATE_SUGGESTION_STRIP);
}
public boolean hasPendingUpdateSuggestions() {
return hasMessages(MSG_UPDATE_SUGGESTION_STRIP);
}
public void postUpdateShiftState() {
removeMessages(MSG_UPDATE_SHIFT_STATE);
sendMessageDelayed(obtainMessage(MSG_UPDATE_SHIFT_STATE), mDelayUpdateShiftState);
}
public void cancelUpdateShiftState() {
removeMessages(MSG_UPDATE_SHIFT_STATE);
}
public void showGesturePreviewAndSuggestionStrip(final SuggestedWords suggestedWords,
final boolean dismissGestureFloatingPreviewText) {
removeMessages(MSG_SHOW_GESTURE_PREVIEW_AND_SUGGESTION_STRIP);
final int arg1 = dismissGestureFloatingPreviewText
? ARG1_DISMISS_GESTURE_FLOATING_PREVIEW_TEXT : 0;
obtainMessage(MSG_SHOW_GESTURE_PREVIEW_AND_SUGGESTION_STRIP, arg1, 0, suggestedWords)
.sendToTarget();
}
public void startDoubleSpacesTimer() {
mDoubleSpaceTimerStart = SystemClock.uptimeMillis();
}
public void cancelDoubleSpacesTimer() {
mDoubleSpaceTimerStart = 0;
}
public boolean isAcceptingDoubleSpaces() {
return SystemClock.uptimeMillis() - mDoubleSpaceTimerStart
< mDoubleSpacesTurnIntoPeriodTimeout;
}
// Working variables for the following methods.
private boolean mIsOrientationChanging;
private boolean mPendingSuccessiveImsCallback;
private boolean mHasPendingStartInput;
private boolean mHasPendingFinishInputView;
private boolean mHasPendingFinishInput;
private EditorInfo mAppliedEditorInfo;
public void startOrientationChanging() {
removeMessages(MSG_PENDING_IMS_CALLBACK);
resetPendingImsCallback();
mIsOrientationChanging = true;
final LatinIME latinIme = getOuterInstance();
if (latinIme.isInputViewShown()) {
latinIme.mKeyboardSwitcher.saveKeyboardState();
}
}
private void resetPendingImsCallback() {
mHasPendingFinishInputView = false;
mHasPendingFinishInput = false;
mHasPendingStartInput = false;
}
private void executePendingImsCallback(final LatinIME latinIme, final EditorInfo editorInfo,
boolean restarting) {
if (mHasPendingFinishInputView)
latinIme.onFinishInputViewInternal(mHasPendingFinishInput);
if (mHasPendingFinishInput)
latinIme.onFinishInputInternal();
if (mHasPendingStartInput)
latinIme.onStartInputInternal(editorInfo, restarting);
resetPendingImsCallback();
}
public void onStartInput(final EditorInfo editorInfo, final boolean restarting) {
if (hasMessages(MSG_PENDING_IMS_CALLBACK)) {
// Typically this is the second onStartInput after orientation changed.
mHasPendingStartInput = true;
} else {
if (mIsOrientationChanging && restarting) {
// This is the first onStartInput after orientation changed.
mIsOrientationChanging = false;
mPendingSuccessiveImsCallback = true;
}
final LatinIME latinIme = getOuterInstance();
executePendingImsCallback(latinIme, editorInfo, restarting);
latinIme.onStartInputInternal(editorInfo, restarting);
}
}
public void onStartInputView(final EditorInfo editorInfo, final boolean restarting) {
if (hasMessages(MSG_PENDING_IMS_CALLBACK)
&& KeyboardId.equivalentEditorInfoForKeyboard(editorInfo, mAppliedEditorInfo)) {
// Typically this is the second onStartInputView after orientation changed.
resetPendingImsCallback();
} else {
if (mPendingSuccessiveImsCallback) {
// This is the first onStartInputView after orientation changed.
mPendingSuccessiveImsCallback = false;
resetPendingImsCallback();
sendMessageDelayed(obtainMessage(MSG_PENDING_IMS_CALLBACK),
PENDING_IMS_CALLBACK_DURATION);
}
final LatinIME latinIme = getOuterInstance();
executePendingImsCallback(latinIme, editorInfo, restarting);
latinIme.onStartInputViewInternal(editorInfo, restarting);
mAppliedEditorInfo = editorInfo;
}
}
public void onFinishInputView(final boolean finishingInput) {
if (hasMessages(MSG_PENDING_IMS_CALLBACK)) {
// Typically this is the first onFinishInputView after orientation changed.
mHasPendingFinishInputView = true;
} else {
final LatinIME latinIme = getOuterInstance();
latinIme.onFinishInputViewInternal(finishingInput);
mAppliedEditorInfo = null;
}
}
public void onFinishInput() {
if (hasMessages(MSG_PENDING_IMS_CALLBACK)) {
// Typically this is the first onFinishInput after orientation changed.
mHasPendingFinishInput = true;
} else {
final LatinIME latinIme = getOuterInstance();
executePendingImsCallback(latinIme, null, false);
latinIme.onFinishInputInternal();
}
}
}
public LatinIME() {
super();
mSubtypeSwitcher = SubtypeSwitcher.getInstance();
mKeyboardSwitcher = KeyboardSwitcher.getInstance();
mIsHardwareAcceleratedDrawingEnabled =
InputMethodServiceCompatUtils.enableHardwareAcceleration(this);
Log.i(TAG, "Hardware accelerated drawing: " + mIsHardwareAcceleratedDrawingEnabled);
}
@Override
public void onCreate() {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
mPrefs = prefs;
LatinImeLogger.init(this, prefs);
if (ProductionFlag.IS_EXPERIMENTAL) {
ResearchLogger.getInstance().init(this, prefs);
}
InputMethodManagerCompatWrapper.init(this);
SubtypeSwitcher.init(this);
KeyboardSwitcher.init(this, prefs);
AccessibilityUtils.init(this);
super.onCreate();
mImm = InputMethodManagerCompatWrapper.getInstance();
mHandler.onCreate();
DEBUG = LatinImeLogger.sDBG;
final Resources res = getResources();
mResources = res;
loadSettings();
ImfUtils.setAdditionalInputMethodSubtypes(this, mCurrentSettings.getAdditionalSubtypes());
initSuggest();
mDisplayOrientation = res.getConfiguration().orientation;
// Register to receive ringer mode change and network state change.
// Also receive installation and removal of a dictionary pack.
final IntentFilter filter = new IntentFilter();
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
filter.addAction(AudioManager.RINGER_MODE_CHANGED_ACTION);
registerReceiver(mReceiver, filter);
final IntentFilter packageFilter = new IntentFilter();
packageFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
packageFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
packageFilter.addDataScheme(SCHEME_PACKAGE);
registerReceiver(mDictionaryPackInstallReceiver, packageFilter);
final IntentFilter newDictFilter = new IntentFilter();
newDictFilter.addAction(
DictionaryPackInstallBroadcastReceiver.NEW_DICTIONARY_INTENT_ACTION);
registerReceiver(mDictionaryPackInstallReceiver, newDictFilter);
}
// Has to be package-visible for unit tests
/* package for test */
void loadSettings() {
// Note that the calling sequence of onCreate() and onCurrentInputMethodSubtypeChanged()
// is not guaranteed. It may even be called at the same time on a different thread.
if (null == mPrefs) mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
final InputAttributes inputAttributes =
new InputAttributes(getCurrentInputEditorInfo(), isFullscreenMode());
final RunInLocale<SettingsValues> job = new RunInLocale<SettingsValues>() {
@Override
protected SettingsValues job(Resources res) {
return new SettingsValues(mPrefs, inputAttributes, LatinIME.this);
}
};
mCurrentSettings = job.runInLocale(mResources, mSubtypeSwitcher.getCurrentSubtypeLocale());
mFeedbackManager = new AudioAndHapticFeedbackManager(this, mCurrentSettings);
resetContactsDictionary(null == mSuggest ? null : mSuggest.getContactsDictionary());
}
// Note that this method is called from a non-UI thread.
@Override
public void onUpdateMainDictionaryAvailability(final boolean isMainDictionaryAvailable) {
mIsMainDictionaryAvailable = isMainDictionaryAvailable;
final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView();
if (mainKeyboardView != null) {
mainKeyboardView.setMainDictionaryAvailability(isMainDictionaryAvailable);
}
}
private void initSuggest() {
final Locale subtypeLocale = mSubtypeSwitcher.getCurrentSubtypeLocale();
final String localeStr = subtypeLocale.toString();
final ContactsBinaryDictionary oldContactsDictionary;
if (mSuggest != null) {
oldContactsDictionary = mSuggest.getContactsDictionary();
mSuggest.close();
} else {
oldContactsDictionary = null;
}
mSuggest = new Suggest(this /* Context */, subtypeLocale,
this /* SuggestInitializationListener */);
if (mCurrentSettings.mCorrectionEnabled) {
mSuggest.setAutoCorrectionThreshold(mCurrentSettings.mAutoCorrectionThreshold);
}
mIsMainDictionaryAvailable = DictionaryFactory.isDictionaryAvailable(this, subtypeLocale);
if (ProductionFlag.IS_EXPERIMENTAL) {
ResearchLogger.getInstance().initSuggest(mSuggest);
}
mUserDictionary = new UserBinaryDictionary(this, localeStr);
mIsUserDictionaryAvailable = mUserDictionary.isEnabled();
mSuggest.setUserDictionary(mUserDictionary);
resetContactsDictionary(oldContactsDictionary);
// Note that the calling sequence of onCreate() and onCurrentInputMethodSubtypeChanged()
// is not guaranteed. It may even be called at the same time on a different thread.
if (null == mPrefs) mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
mUserHistoryDictionary = UserHistoryDictionary.getInstance(this, localeStr, mPrefs);
mSuggest.setUserHistoryDictionary(mUserHistoryDictionary);
}
/**
* Resets the contacts dictionary in mSuggest according to the user settings.
*
* This method takes an optional contacts dictionary to use when the locale hasn't changed
* since the contacts dictionary can be opened or closed as necessary depending on the settings.
*
* @param oldContactsDictionary an optional dictionary to use, or null
*/
private void resetContactsDictionary(final ContactsBinaryDictionary oldContactsDictionary) {
final boolean shouldSetDictionary = (null != mSuggest && mCurrentSettings.mUseContactsDict);
final ContactsBinaryDictionary dictionaryToUse;
if (!shouldSetDictionary) {
// Make sure the dictionary is closed. If it is already closed, this is a no-op,
// so it's safe to call it anyways.
if (null != oldContactsDictionary) oldContactsDictionary.close();
dictionaryToUse = null;
} else {
final Locale locale = mSubtypeSwitcher.getCurrentSubtypeLocale();
if (null != oldContactsDictionary) {
if (!oldContactsDictionary.mLocale.equals(locale)) {
// If the locale has changed then recreate the contacts dictionary. This
// allows locale dependent rules for handling bigram name predictions.
oldContactsDictionary.close();
dictionaryToUse = new ContactsBinaryDictionary(this, locale);
} else {
// Make sure the old contacts dictionary is opened. If it is already open,
// this is a no-op, so it's safe to call it anyways.
oldContactsDictionary.reopen(this);
dictionaryToUse = oldContactsDictionary;
}
} else {
dictionaryToUse = new ContactsBinaryDictionary(this, locale);
}
}
if (null != mSuggest) {
mSuggest.setContactsDictionary(dictionaryToUse);
}
}
/* package private */ void resetSuggestMainDict() {
final Locale subtypeLocale = mSubtypeSwitcher.getCurrentSubtypeLocale();
mSuggest.resetMainDict(this, subtypeLocale, this /* SuggestInitializationListener */);
mIsMainDictionaryAvailable = DictionaryFactory.isDictionaryAvailable(this, subtypeLocale);
}
@Override
public void onDestroy() {
if (mSuggest != null) {
mSuggest.close();
mSuggest = null;
}
unregisterReceiver(mReceiver);
unregisterReceiver(mDictionaryPackInstallReceiver);
LatinImeLogger.commit();
LatinImeLogger.onDestroy();
super.onDestroy();
}
@Override
public void onConfigurationChanged(final Configuration conf) {
// System locale has been changed. Needs to reload keyboard.
if (mSubtypeSwitcher.onConfigurationChanged(conf, this)) {
loadKeyboard();
}
// If orientation changed while predicting, commit the change
if (mDisplayOrientation != conf.orientation) {
mDisplayOrientation = conf.orientation;
mHandler.startOrientationChanging();
mConnection.beginBatchEdit();
commitTyped(LastComposedWord.NOT_A_SEPARATOR);
mConnection.finishComposingText();
mConnection.endBatchEdit();
if (isShowingOptionDialog()) {
mOptionsDialog.dismiss();
}
}
super.onConfigurationChanged(conf);
}
@Override
public View onCreateInputView() {
return mKeyboardSwitcher.onCreateInputView(mIsHardwareAcceleratedDrawingEnabled);
}
@Override
public void setInputView(final View view) {
super.setInputView(view);
mExtractArea = getWindow().getWindow().getDecorView()
.findViewById(android.R.id.extractArea);
mKeyPreviewBackingView = view.findViewById(R.id.key_preview_backing);
mSuggestionsContainer = view.findViewById(R.id.suggestions_container);
mSuggestionStripView = (SuggestionStripView)view.findViewById(R.id.suggestion_strip_view);
if (mSuggestionStripView != null)
mSuggestionStripView.setListener(this, view);
if (LatinImeLogger.sVISUALDEBUG) {
mKeyPreviewBackingView.setBackgroundColor(0x10FF0000);
}
}
@Override
public void setCandidatesView(final View view) {
// To ensure that CandidatesView will never be set.
return;
}
@Override
public void onStartInput(final EditorInfo editorInfo, final boolean restarting) {
mHandler.onStartInput(editorInfo, restarting);
}
@Override
public void onStartInputView(final EditorInfo editorInfo, final boolean restarting) {
mHandler.onStartInputView(editorInfo, restarting);
}
@Override
public void onFinishInputView(final boolean finishingInput) {
mHandler.onFinishInputView(finishingInput);
}
@Override
public void onFinishInput() {
mHandler.onFinishInput();
}
@Override
public void onCurrentInputMethodSubtypeChanged(final InputMethodSubtype subtype) {
// Note that the calling sequence of onCreate() and onCurrentInputMethodSubtypeChanged()
// is not guaranteed. It may even be called at the same time on a different thread.
mSubtypeSwitcher.updateSubtype(subtype);
loadKeyboard();
}
private void onStartInputInternal(final EditorInfo editorInfo, final boolean restarting) {
super.onStartInput(editorInfo, restarting);
}
@SuppressWarnings("deprecation")
private void onStartInputViewInternal(final EditorInfo editorInfo, final boolean restarting) {
super.onStartInputView(editorInfo, restarting);
final KeyboardSwitcher switcher = mKeyboardSwitcher;
final MainKeyboardView mainKeyboardView = switcher.getMainKeyboardView();
if (editorInfo == null) {
Log.e(TAG, "Null EditorInfo in onStartInputView()");
if (LatinImeLogger.sDBG) {
throw new NullPointerException("Null EditorInfo in onStartInputView()");
}
return;
}
if (DEBUG) {
Log.d(TAG, "onStartInputView: editorInfo:"
+ String.format("inputType=0x%08x imeOptions=0x%08x",
editorInfo.inputType, editorInfo.imeOptions));
Log.d(TAG, "All caps = "
+ ((editorInfo.inputType & InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS) != 0)
+ ", sentence caps = "
+ ((editorInfo.inputType & InputType.TYPE_TEXT_FLAG_CAP_SENTENCES) != 0)
+ ", word caps = "
+ ((editorInfo.inputType & InputType.TYPE_TEXT_FLAG_CAP_WORDS) != 0));
}
if (ProductionFlag.IS_EXPERIMENTAL) {
ResearchLogger.latinIME_onStartInputViewInternal(editorInfo, mPrefs);
}
if (InputAttributes.inPrivateImeOptions(null, NO_MICROPHONE_COMPAT, editorInfo)) {
Log.w(TAG, "Deprecated private IME option specified: "
+ editorInfo.privateImeOptions);
Log.w(TAG, "Use " + getPackageName() + "." + NO_MICROPHONE + " instead");
}
if (InputAttributes.inPrivateImeOptions(getPackageName(), FORCE_ASCII, editorInfo)) {
Log.w(TAG, "Deprecated private IME option specified: "
+ editorInfo.privateImeOptions);
Log.w(TAG, "Use EditorInfo.IME_FLAG_FORCE_ASCII flag instead");
}
mTargetApplicationInfo =
TargetApplicationGetter.getCachedApplicationInfo(editorInfo.packageName);
if (null == mTargetApplicationInfo) {
new TargetApplicationGetter(this /* context */, this /* listener */)
.execute(editorInfo.packageName);
}
LatinImeLogger.onStartInputView(editorInfo);
// In landscape mode, this method gets called without the input view being created.
if (mainKeyboardView == null) {
return;
}
// Forward this event to the accessibility utilities, if enabled.
final AccessibilityUtils accessUtils = AccessibilityUtils.getInstance();
if (accessUtils.isTouchExplorationEnabled()) {
accessUtils.onStartInputViewInternal(mainKeyboardView, editorInfo, restarting);
}
final boolean selectionChanged = mLastSelectionStart != editorInfo.initialSelStart
|| mLastSelectionEnd != editorInfo.initialSelEnd;
final boolean inputTypeChanged = !mCurrentSettings.isSameInputType(editorInfo);
final boolean isDifferentTextField = !restarting || inputTypeChanged;
if (isDifferentTextField) {
final boolean currentSubtypeEnabled = mSubtypeSwitcher
.updateParametersOnStartInputViewAndReturnIfCurrentSubtypeEnabled();
if (!currentSubtypeEnabled) {
// Current subtype is disabled. Needs to update subtype and keyboard.
final InputMethodSubtype newSubtype = ImfUtils.getCurrentInputMethodSubtype(
this, mSubtypeSwitcher.getNoLanguageSubtype());
mSubtypeSwitcher.updateSubtype(newSubtype);
loadKeyboard();
}
}
// The EditorInfo might have a flag that affects fullscreen mode.
// Note: This call should be done by InputMethodService?
updateFullscreenMode();
mApplicationSpecifiedCompletions = null;
- if (isDifferentTextField || selectionChanged) {
- // If the selection changed, we reset the input state. Essentially, we come here with
- // restarting == true when the app called setText() or similar. We should reset the
- // state if the app set the text to something else, but keep it if it set a suggestion
- // or something.
- mEnteredText = null;
- resetComposingState(true /* alsoResetLastComposedWord */);
- mDeleteCount = 0;
- mSpaceState = SPACE_STATE_NONE;
+ // The app calling setText() has the effect of clearing the composing
+ // span, so we should reset our state unconditionally, even if restarting is true.
+ mEnteredText = null;
+ resetComposingState(true /* alsoResetLastComposedWord */);
+ mDeleteCount = 0;
+ mSpaceState = SPACE_STATE_NONE;
- if (mSuggestionStripView != null) {
- // This will set the punctuation suggestions if next word suggestion is off;
- // otherwise it will clear the suggestion strip.
- setPunctuationSuggestions();
- }
+ if (mSuggestionStripView != null) {
+ // This will set the punctuation suggestions if next word suggestion is off;
+ // otherwise it will clear the suggestion strip.
+ setPunctuationSuggestions();
}
mConnection.resetCachesUponCursorMove(editorInfo.initialSelStart);
if (isDifferentTextField) {
mainKeyboardView.closing();
loadSettings();
if (mSuggest != null && mCurrentSettings.mCorrectionEnabled) {
mSuggest.setAutoCorrectionThreshold(mCurrentSettings.mAutoCorrectionThreshold);
}
switcher.loadKeyboard(editorInfo, mCurrentSettings);
} else if (restarting) {
// TODO: Come up with a more comprehensive way to reset the keyboard layout when
// a keyboard layout set doesn't get reloaded in this method.
switcher.resetKeyboardStateToAlphabet();
}
setSuggestionStripShownInternal(
isSuggestionsStripVisible(), /* needsInputViewShown */ false);
mLastSelectionStart = editorInfo.initialSelStart;
mLastSelectionEnd = editorInfo.initialSelEnd;
// If we come here something in the text state is very likely to have changed.
// We should update the shift state regardless of whether we are restarting or not, because
// this is not perceived as a layout change that may be disruptive like we may have with
// switcher.loadKeyboard; in apps like Talk, we come here when the text is sent and the
// field gets emptied and we need to re-evaluate the shift state, but not the whole layout
// which would be disruptive.
// Space state must be updated before calling updateShiftState
mKeyboardSwitcher.updateShiftState();
mHandler.cancelUpdateSuggestionStrip();
mHandler.cancelDoubleSpacesTimer();
mainKeyboardView.setMainDictionaryAvailability(mIsMainDictionaryAvailable);
mainKeyboardView.setKeyPreviewPopupEnabled(mCurrentSettings.mKeyPreviewPopupOn,
mCurrentSettings.mKeyPreviewPopupDismissDelay);
mainKeyboardView.setGestureHandlingEnabledByUser(mCurrentSettings.mGestureInputEnabled);
mainKeyboardView.setGesturePreviewMode(mCurrentSettings.mGesturePreviewTrailEnabled,
mCurrentSettings.mGestureFloatingPreviewTextEnabled);
if (TRACE) Debug.startMethodTracing("/data/trace/latinime");
}
// Callback for the TargetApplicationGetter
@Override
public void onTargetApplicationKnown(final ApplicationInfo info) {
mTargetApplicationInfo = info;
}
@Override
public void onWindowHidden() {
if (ProductionFlag.IS_EXPERIMENTAL) {
ResearchLogger.latinIME_onWindowHidden(mLastSelectionStart, mLastSelectionEnd,
getCurrentInputConnection());
}
super.onWindowHidden();
final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView();
if (mainKeyboardView != null) {
mainKeyboardView.closing();
}
}
private void onFinishInputInternal() {
super.onFinishInput();
LatinImeLogger.commit();
if (ProductionFlag.IS_EXPERIMENTAL) {
ResearchLogger.getInstance().latinIME_onFinishInputInternal();
}
final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView();
if (mainKeyboardView != null) {
mainKeyboardView.closing();
}
}
private void onFinishInputViewInternal(final boolean finishingInput) {
super.onFinishInputView(finishingInput);
mKeyboardSwitcher.onFinishInputView();
final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView();
if (mainKeyboardView != null) {
mainKeyboardView.cancelAllMessages();
}
// Remove pending messages related to update suggestions
mHandler.cancelUpdateSuggestionStrip();
}
@Override
public void onUpdateSelection(final int oldSelStart, final int oldSelEnd,
final int newSelStart, final int newSelEnd,
final int composingSpanStart, final int composingSpanEnd) {
super.onUpdateSelection(oldSelStart, oldSelEnd, newSelStart, newSelEnd,
composingSpanStart, composingSpanEnd);
if (DEBUG) {
Log.i(TAG, "onUpdateSelection: oss=" + oldSelStart
+ ", ose=" + oldSelEnd
+ ", lss=" + mLastSelectionStart
+ ", lse=" + mLastSelectionEnd
+ ", nss=" + newSelStart
+ ", nse=" + newSelEnd
+ ", cs=" + composingSpanStart
+ ", ce=" + composingSpanEnd);
}
if (ProductionFlag.IS_EXPERIMENTAL) {
final boolean expectingUpdateSelectionFromLogger =
ResearchLogger.getAndClearLatinIMEExpectingUpdateSelection();
ResearchLogger.latinIME_onUpdateSelection(mLastSelectionStart, mLastSelectionEnd,
oldSelStart, oldSelEnd, newSelStart, newSelEnd, composingSpanStart,
composingSpanEnd, mExpectingUpdateSelection,
expectingUpdateSelectionFromLogger, mConnection);
if (expectingUpdateSelectionFromLogger) {
// TODO: Investigate. Quitting now sounds wrong - we won't do the resetting work
return;
}
}
// TODO: refactor the following code to be less contrived.
// "newSelStart != composingSpanEnd" || "newSelEnd != composingSpanEnd" means
// that the cursor is not at the end of the composing span, or there is a selection.
// "mLastSelectionStart != newSelStart" means that the cursor is not in the same place
// as last time we were called (if there is a selection, it means the start hasn't
// changed, so it's the end that did).
final boolean selectionChanged = (newSelStart != composingSpanEnd
|| newSelEnd != composingSpanEnd) && mLastSelectionStart != newSelStart;
// if composingSpanStart and composingSpanEnd are -1, it means there is no composing
// span in the view - we can use that to narrow down whether the cursor was moved
// by us or not. If we are composing a word but there is no composing span, then
// we know for sure the cursor moved while we were composing and we should reset
// the state.
final boolean noComposingSpan = composingSpanStart == -1 && composingSpanEnd == -1;
if (!mExpectingUpdateSelection
&& !mConnection.isBelatedExpectedUpdate(oldSelStart, newSelStart)) {
// TAKE CARE: there is a race condition when we enter this test even when the user
// did not explicitly move the cursor. This happens when typing fast, where two keys
// turn this flag on in succession and both onUpdateSelection() calls arrive after
// the second one - the first call successfully avoids this test, but the second one
// enters. For the moment we rely on noComposingSpan to further reduce the impact.
// TODO: the following is probably better done in resetEntireInputState().
// it should only happen when the cursor moved, and the very purpose of the
// test below is to narrow down whether this happened or not. Likewise with
// the call to updateShiftState.
// We set this to NONE because after a cursor move, we don't want the space
// state-related special processing to kick in.
mSpaceState = SPACE_STATE_NONE;
if ((!mWordComposer.isComposingWord()) || selectionChanged || noComposingSpan) {
// If we are composing a word and moving the cursor, we would want to set a
// suggestion span for recorrection to work correctly. Unfortunately, that
// would involve the keyboard committing some new text, which would move the
// cursor back to where it was. Latin IME could then fix the position of the cursor
// again, but the asynchronous nature of the calls results in this wreaking havoc
// with selection on double tap and the like.
// Another option would be to send suggestions each time we set the composing
// text, but that is probably too expensive to do, so we decided to leave things
// as is.
resetEntireInputState(newSelStart);
}
mKeyboardSwitcher.updateShiftState();
}
mExpectingUpdateSelection = false;
// TODO: Decide to call restartSuggestionsOnWordBeforeCursorIfAtEndOfWord() or not
// here. It would probably be too expensive to call directly here but we may want to post a
// message to delay it. The point would be to unify behavior between backspace to the
// end of a word and manually put the pointer at the end of the word.
// Make a note of the cursor position
mLastSelectionStart = newSelStart;
mLastSelectionEnd = newSelEnd;
}
/**
* This is called when the user has clicked on the extracted text view,
* when running in fullscreen mode. The default implementation hides
* the suggestions view when this happens, but only if the extracted text
* editor has a vertical scroll bar because its text doesn't fit.
* Here we override the behavior due to the possibility that a re-correction could
* cause the suggestions strip to disappear and re-appear.
*/
@Override
public void onExtractedTextClicked() {
if (mCurrentSettings.isSuggestionsRequested(mDisplayOrientation)) return;
super.onExtractedTextClicked();
}
/**
* This is called when the user has performed a cursor movement in the
* extracted text view, when it is running in fullscreen mode. The default
* implementation hides the suggestions view when a vertical movement
* happens, but only if the extracted text editor has a vertical scroll bar
* because its text doesn't fit.
* Here we override the behavior due to the possibility that a re-correction could
* cause the suggestions strip to disappear and re-appear.
*/
@Override
public void onExtractedCursorMovement(final int dx, final int dy) {
if (mCurrentSettings.isSuggestionsRequested(mDisplayOrientation)) return;
super.onExtractedCursorMovement(dx, dy);
}
@Override
public void hideWindow() {
LatinImeLogger.commit();
mKeyboardSwitcher.onHideWindow();
if (TRACE) Debug.stopMethodTracing();
if (mOptionsDialog != null && mOptionsDialog.isShowing()) {
mOptionsDialog.dismiss();
mOptionsDialog = null;
}
super.hideWindow();
}
@Override
public void onDisplayCompletions(final CompletionInfo[] applicationSpecifiedCompletions) {
if (DEBUG) {
Log.i(TAG, "Received completions:");
if (applicationSpecifiedCompletions != null) {
for (int i = 0; i < applicationSpecifiedCompletions.length; i++) {
Log.i(TAG, " #" + i + ": " + applicationSpecifiedCompletions[i]);
}
}
}
if (!mCurrentSettings.isApplicationSpecifiedCompletionsOn()) return;
mApplicationSpecifiedCompletions = applicationSpecifiedCompletions;
if (applicationSpecifiedCompletions == null) {
clearSuggestionStrip();
if (ProductionFlag.IS_EXPERIMENTAL) {
ResearchLogger.latinIME_onDisplayCompletions(null);
}
return;
}
final ArrayList<SuggestedWords.SuggestedWordInfo> applicationSuggestedWords =
SuggestedWords.getFromApplicationSpecifiedCompletions(
applicationSpecifiedCompletions);
final SuggestedWords suggestedWords = new SuggestedWords(
applicationSuggestedWords,
false /* typedWordValid */,
false /* hasAutoCorrectionCandidate */,
false /* isPunctuationSuggestions */,
false /* isObsoleteSuggestions */,
false /* isPrediction */);
// When in fullscreen mode, show completions generated by the application
final boolean isAutoCorrection = false;
setSuggestionStrip(suggestedWords, isAutoCorrection);
setAutoCorrectionIndicator(isAutoCorrection);
// TODO: is this the right thing to do? What should we auto-correct to in
// this case? This says to keep whatever the user typed.
mWordComposer.setAutoCorrection(mWordComposer.getTypedWord());
setSuggestionStripShown(true);
if (ProductionFlag.IS_EXPERIMENTAL) {
ResearchLogger.latinIME_onDisplayCompletions(applicationSpecifiedCompletions);
}
}
private void setSuggestionStripShownInternal(final boolean shown,
final boolean needsInputViewShown) {
// TODO: Modify this if we support suggestions with hard keyboard
if (onEvaluateInputViewShown() && mSuggestionsContainer != null) {
final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView();
final boolean inputViewShown = (mainKeyboardView != null)
? mainKeyboardView.isShown() : false;
final boolean shouldShowSuggestions = shown
&& (needsInputViewShown ? inputViewShown : true);
if (isFullscreenMode()) {
mSuggestionsContainer.setVisibility(
shouldShowSuggestions ? View.VISIBLE : View.GONE);
} else {
mSuggestionsContainer.setVisibility(
shouldShowSuggestions ? View.VISIBLE : View.INVISIBLE);
}
}
}
private void setSuggestionStripShown(final boolean shown) {
setSuggestionStripShownInternal(shown, /* needsInputViewShown */true);
}
private int getAdjustedBackingViewHeight() {
final int currentHeight = mKeyPreviewBackingView.getHeight();
if (currentHeight > 0) {
return currentHeight;
}
final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView();
if (mainKeyboardView == null) {
return 0;
}
final int keyboardHeight = mainKeyboardView.getHeight();
final int suggestionsHeight = mSuggestionsContainer.getHeight();
final int displayHeight = mResources.getDisplayMetrics().heightPixels;
final Rect rect = new Rect();
mKeyPreviewBackingView.getWindowVisibleDisplayFrame(rect);
final int notificationBarHeight = rect.top;
final int remainingHeight = displayHeight - notificationBarHeight - suggestionsHeight
- keyboardHeight;
final LayoutParams params = mKeyPreviewBackingView.getLayoutParams();
params.height = mSuggestionStripView.setMoreSuggestionsHeight(remainingHeight);
mKeyPreviewBackingView.setLayoutParams(params);
return params.height;
}
@Override
public void onComputeInsets(final InputMethodService.Insets outInsets) {
super.onComputeInsets(outInsets);
final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView();
if (mainKeyboardView == null || mSuggestionsContainer == null) {
return;
}
final int adjustedBackingHeight = getAdjustedBackingViewHeight();
final boolean backingGone = (mKeyPreviewBackingView.getVisibility() == View.GONE);
final int backingHeight = backingGone ? 0 : adjustedBackingHeight;
// In fullscreen mode, the height of the extract area managed by InputMethodService should
// be considered.
// See {@link android.inputmethodservice.InputMethodService#onComputeInsets}.
final int extractHeight = isFullscreenMode() ? mExtractArea.getHeight() : 0;
final int suggestionsHeight = (mSuggestionsContainer.getVisibility() == View.GONE) ? 0
: mSuggestionsContainer.getHeight();
final int extraHeight = extractHeight + backingHeight + suggestionsHeight;
int touchY = extraHeight;
// Need to set touchable region only if input view is being shown
if (mainKeyboardView.isShown()) {
if (mSuggestionsContainer.getVisibility() == View.VISIBLE) {
touchY -= suggestionsHeight;
}
final int touchWidth = mainKeyboardView.getWidth();
final int touchHeight = mainKeyboardView.getHeight() + extraHeight
// Extend touchable region below the keyboard.
+ EXTENDED_TOUCHABLE_REGION_HEIGHT;
outInsets.touchableInsets = InputMethodService.Insets.TOUCHABLE_INSETS_REGION;
outInsets.touchableRegion.set(0, touchY, touchWidth, touchHeight);
}
outInsets.contentTopInsets = touchY;
outInsets.visibleTopInsets = touchY;
}
@Override
public boolean onEvaluateFullscreenMode() {
// Reread resource value here, because this method is called by framework anytime as needed.
final boolean isFullscreenModeAllowed =
mCurrentSettings.isFullscreenModeAllowed(getResources());
if (super.onEvaluateFullscreenMode() && isFullscreenModeAllowed) {
// TODO: Remove this hack. Actually we should not really assume NO_EXTRACT_UI
// implies NO_FULLSCREEN. However, the framework mistakenly does. i.e. NO_EXTRACT_UI
// without NO_FULLSCREEN doesn't work as expected. Because of this we need this
// hack for now. Let's get rid of this once the framework gets fixed.
final EditorInfo ei = getCurrentInputEditorInfo();
return !(ei != null && ((ei.imeOptions & EditorInfo.IME_FLAG_NO_EXTRACT_UI) != 0));
} else {
return false;
}
}
@Override
public void updateFullscreenMode() {
super.updateFullscreenMode();
if (mKeyPreviewBackingView == null) return;
// In fullscreen mode, no need to have extra space to show the key preview.
// If not, we should have extra space above the keyboard to show the key preview.
mKeyPreviewBackingView.setVisibility(isFullscreenMode() ? View.GONE : View.VISIBLE);
}
// This will reset the whole input state to the starting state. It will clear
// the composing word, reset the last composed word, tell the inputconnection about it.
private void resetEntireInputState(final int newCursorPosition) {
resetComposingState(true /* alsoResetLastComposedWord */);
if (mCurrentSettings.mBigramPredictionEnabled) {
clearSuggestionStrip();
} else {
setSuggestionStrip(mCurrentSettings.mSuggestPuncList, false);
}
mConnection.resetCachesUponCursorMove(newCursorPosition);
}
private void resetComposingState(final boolean alsoResetLastComposedWord) {
mWordComposer.reset();
if (alsoResetLastComposedWord)
mLastComposedWord = LastComposedWord.NOT_A_COMPOSED_WORD;
}
private void commitTyped(final String separatorString) {
if (!mWordComposer.isComposingWord()) return;
final CharSequence typedWord = mWordComposer.getTypedWord();
if (typedWord.length() > 0) {
commitChosenWord(typedWord, LastComposedWord.COMMIT_TYPE_USER_TYPED_WORD,
separatorString);
}
}
// Called from the KeyboardSwitcher which needs to know auto caps state to display
// the right layout.
public int getCurrentAutoCapsState() {
if (!mCurrentSettings.mAutoCap) return Constants.TextUtils.CAP_MODE_OFF;
final EditorInfo ei = getCurrentInputEditorInfo();
if (ei == null) return Constants.TextUtils.CAP_MODE_OFF;
final int inputType = ei.inputType;
// Warning: this depends on mSpaceState, which may not be the most current value. If
// mSpaceState gets updated later, whoever called this may need to be told about it.
return mConnection.getCursorCapsMode(inputType, mSubtypeSwitcher.getCurrentSubtypeLocale(),
SPACE_STATE_PHANTOM == mSpaceState);
}
// Factor in auto-caps and manual caps and compute the current caps mode.
private int getActualCapsMode() {
final int keyboardShiftMode = mKeyboardSwitcher.getKeyboardShiftMode();
if (keyboardShiftMode != WordComposer.CAPS_MODE_AUTO_SHIFTED) return keyboardShiftMode;
final int auto = getCurrentAutoCapsState();
if (0 != (auto & TextUtils.CAP_MODE_CHARACTERS)) {
return WordComposer.CAPS_MODE_AUTO_SHIFT_LOCKED;
}
if (0 != auto) return WordComposer.CAPS_MODE_AUTO_SHIFTED;
return WordComposer.CAPS_MODE_OFF;
}
private void swapSwapperAndSpace() {
CharSequence lastTwo = mConnection.getTextBeforeCursor(2, 0);
// It is guaranteed lastTwo.charAt(1) is a swapper - else this method is not called.
if (lastTwo != null && lastTwo.length() == 2
&& lastTwo.charAt(0) == Keyboard.CODE_SPACE) {
mConnection.deleteSurroundingText(2, 0);
mConnection.commitText(lastTwo.charAt(1) + " ", 1);
if (ProductionFlag.IS_EXPERIMENTAL) {
ResearchLogger.latinIME_swapSwapperAndSpace();
}
mKeyboardSwitcher.updateShiftState();
}
}
private boolean maybeDoubleSpace() {
if (!mCurrentSettings.mCorrectionEnabled) return false;
if (!mHandler.isAcceptingDoubleSpaces()) return false;
final CharSequence lastThree = mConnection.getTextBeforeCursor(3, 0);
if (lastThree != null && lastThree.length() == 3
&& canBeFollowedByPeriod(lastThree.charAt(0))
&& lastThree.charAt(1) == Keyboard.CODE_SPACE
&& lastThree.charAt(2) == Keyboard.CODE_SPACE) {
mHandler.cancelDoubleSpacesTimer();
mConnection.deleteSurroundingText(2, 0);
mConnection.commitText(". ", 1);
mKeyboardSwitcher.updateShiftState();
return true;
}
return false;
}
private static boolean canBeFollowedByPeriod(final int codePoint) {
// TODO: Check again whether there really ain't a better way to check this.
// TODO: This should probably be language-dependant...
return Character.isLetterOrDigit(codePoint)
|| codePoint == Keyboard.CODE_SINGLE_QUOTE
|| codePoint == Keyboard.CODE_DOUBLE_QUOTE
|| codePoint == Keyboard.CODE_CLOSING_PARENTHESIS
|| codePoint == Keyboard.CODE_CLOSING_SQUARE_BRACKET
|| codePoint == Keyboard.CODE_CLOSING_CURLY_BRACKET
|| codePoint == Keyboard.CODE_CLOSING_ANGLE_BRACKET;
}
// Callback for the {@link SuggestionStripView}, to call when the "add to dictionary" hint is
// pressed.
@Override
public boolean addWordToUserDictionary(final String word) {
mUserDictionary.addWordToUserDictionary(word, 128);
return true;
}
private static boolean isAlphabet(final int code) {
return Character.isLetter(code);
}
private void onSettingsKeyPressed() {
if (isShowingOptionDialog()) return;
showSubtypeSelectorAndSettings();
}
// Virtual codes representing custom requests. These are used in onCustomRequest() below.
public static final int CODE_SHOW_INPUT_METHOD_PICKER = 1;
@Override
public boolean onCustomRequest(final int requestCode) {
if (isShowingOptionDialog()) return false;
switch (requestCode) {
case CODE_SHOW_INPUT_METHOD_PICKER:
if (ImfUtils.hasMultipleEnabledIMEsOrSubtypes(
this, true /* include aux subtypes */)) {
mImm.showInputMethodPicker();
return true;
}
return false;
}
return false;
}
private boolean isShowingOptionDialog() {
return mOptionsDialog != null && mOptionsDialog.isShowing();
}
private static int getActionId(final Keyboard keyboard) {
return keyboard != null ? keyboard.mId.imeActionId() : EditorInfo.IME_ACTION_NONE;
}
private void performEditorAction(final int actionId) {
mConnection.performEditorAction(actionId);
}
// TODO: Revise the language switch key behavior to make it much smarter and more reasonable.
private void handleLanguageSwitchKey() {
final IBinder token = getWindow().getWindow().getAttributes().token;
if (mCurrentSettings.mIncludesOtherImesInLanguageSwitchList) {
mImm.switchToNextInputMethod(token, false /* onlyCurrentIme */);
return;
}
if (mShouldSwitchToLastSubtype) {
final InputMethodSubtype lastSubtype = mImm.getLastInputMethodSubtype();
final boolean lastSubtypeBelongsToThisIme =
ImfUtils.checkIfSubtypeBelongsToThisImeAndEnabled(this, lastSubtype);
if (lastSubtypeBelongsToThisIme && mImm.switchToLastInputMethod(token)) {
mShouldSwitchToLastSubtype = false;
} else {
mImm.switchToNextInputMethod(token, true /* onlyCurrentIme */);
mShouldSwitchToLastSubtype = true;
}
} else {
mImm.switchToNextInputMethod(token, true /* onlyCurrentIme */);
}
}
private void sendDownUpKeyEventForBackwardCompatibility(final int code) {
final long eventTime = SystemClock.uptimeMillis();
mConnection.sendKeyEvent(new KeyEvent(eventTime, eventTime,
KeyEvent.ACTION_DOWN, code, 0, 0, KeyCharacterMap.VIRTUAL_KEYBOARD, 0,
KeyEvent.FLAG_SOFT_KEYBOARD | KeyEvent.FLAG_KEEP_TOUCH_MODE));
mConnection.sendKeyEvent(new KeyEvent(SystemClock.uptimeMillis(), eventTime,
KeyEvent.ACTION_UP, code, 0, 0, KeyCharacterMap.VIRTUAL_KEYBOARD, 0,
KeyEvent.FLAG_SOFT_KEYBOARD | KeyEvent.FLAG_KEEP_TOUCH_MODE));
}
private void sendKeyCodePoint(final int code) {
// TODO: Remove this special handling of digit letters.
// For backward compatibility. See {@link InputMethodService#sendKeyChar(char)}.
if (code >= '0' && code <= '9') {
sendDownUpKeyEventForBackwardCompatibility(code - '0' + KeyEvent.KEYCODE_0);
if (ProductionFlag.IS_EXPERIMENTAL) {
ResearchLogger.latinIME_sendKeyCodePoint(code);
}
return;
}
// 16 is android.os.Build.VERSION_CODES.JELLY_BEAN but we can't write it because
// we want to be able to compile against the Ice Cream Sandwich SDK.
if (Keyboard.CODE_ENTER == code && mTargetApplicationInfo != null
&& mTargetApplicationInfo.targetSdkVersion < 16) {
// Backward compatibility mode. Before Jelly bean, the keyboard would simulate
// a hardware keyboard event on pressing enter or delete. This is bad for many
// reasons (there are race conditions with commits) but some applications are
// relying on this behavior so we continue to support it for older apps.
sendDownUpKeyEventForBackwardCompatibility(KeyEvent.KEYCODE_ENTER);
} else {
final String text = new String(new int[] { code }, 0, 1);
mConnection.commitText(text, text.length());
}
}
// Implementation of {@link KeyboardActionListener}.
@Override
public void onCodeInput(final int primaryCode, final int x, final int y) {
final long when = SystemClock.uptimeMillis();
if (primaryCode != Keyboard.CODE_DELETE || when > mLastKeyTime + QUICK_PRESS) {
mDeleteCount = 0;
}
mLastKeyTime = when;
mConnection.beginBatchEdit();
final KeyboardSwitcher switcher = mKeyboardSwitcher;
// The space state depends only on the last character pressed and its own previous
// state. Here, we revert the space state to neutral if the key is actually modifying
// the input contents (any non-shift key), which is what we should do for
// all inputs that do not result in a special state. Each character handling is then
// free to override the state as they see fit.
final int spaceState = mSpaceState;
if (!mWordComposer.isComposingWord()) mIsAutoCorrectionIndicatorOn = false;
// TODO: Consolidate the double space timer, mLastKeyTime, and the space state.
if (primaryCode != Keyboard.CODE_SPACE) {
mHandler.cancelDoubleSpacesTimer();
}
boolean didAutoCorrect = false;
switch (primaryCode) {
case Keyboard.CODE_DELETE:
mSpaceState = SPACE_STATE_NONE;
handleBackspace(spaceState);
mDeleteCount++;
mExpectingUpdateSelection = true;
mShouldSwitchToLastSubtype = true;
LatinImeLogger.logOnDelete(x, y);
break;
case Keyboard.CODE_SHIFT:
case Keyboard.CODE_SWITCH_ALPHA_SYMBOL:
// Shift and symbol key is handled in onPressKey() and onReleaseKey().
break;
case Keyboard.CODE_SETTINGS:
onSettingsKeyPressed();
break;
case Keyboard.CODE_SHORTCUT:
mSubtypeSwitcher.switchToShortcutIME(this);
break;
case Keyboard.CODE_ACTION_ENTER:
performEditorAction(getActionId(switcher.getKeyboard()));
break;
case Keyboard.CODE_ACTION_NEXT:
performEditorAction(EditorInfo.IME_ACTION_NEXT);
break;
case Keyboard.CODE_ACTION_PREVIOUS:
performEditorAction(EditorInfo.IME_ACTION_PREVIOUS);
break;
case Keyboard.CODE_LANGUAGE_SWITCH:
handleLanguageSwitchKey();
break;
case Keyboard.CODE_RESEARCH:
if (ProductionFlag.IS_EXPERIMENTAL) {
ResearchLogger.getInstance().onResearchKeySelected(this);
}
break;
default:
mSpaceState = SPACE_STATE_NONE;
if (mCurrentSettings.isWordSeparator(primaryCode)) {
didAutoCorrect = handleSeparator(primaryCode, x, y, spaceState);
} else {
if (SPACE_STATE_PHANTOM == spaceState) {
if (ProductionFlag.IS_INTERNAL) {
if (mWordComposer.isComposingWord() && mWordComposer.isBatchMode()) {
Stats.onAutoCorrection(
"", mWordComposer.getTypedWord(), " ", mWordComposer);
}
}
commitTyped(LastComposedWord.NOT_A_SEPARATOR);
}
final int keyX, keyY;
final Keyboard keyboard = mKeyboardSwitcher.getKeyboard();
if (keyboard != null && keyboard.hasProximityCharsCorrection(primaryCode)) {
keyX = x;
keyY = y;
} else {
keyX = Constants.NOT_A_COORDINATE;
keyY = Constants.NOT_A_COORDINATE;
}
handleCharacter(primaryCode, keyX, keyY, spaceState);
}
mExpectingUpdateSelection = true;
mShouldSwitchToLastSubtype = true;
break;
}
switcher.onCodeInput(primaryCode);
// Reset after any single keystroke, except shift and symbol-shift
if (!didAutoCorrect && primaryCode != Keyboard.CODE_SHIFT
&& primaryCode != Keyboard.CODE_SWITCH_ALPHA_SYMBOL)
mLastComposedWord.deactivate();
if (Keyboard.CODE_DELETE != primaryCode) {
mEnteredText = null;
}
mConnection.endBatchEdit();
if (ProductionFlag.IS_EXPERIMENTAL) {
ResearchLogger.latinIME_onCodeInput(primaryCode, x, y);
}
}
// Called from PointerTracker through the KeyboardActionListener interface
@Override
public void onTextInput(final CharSequence rawText) {
mConnection.beginBatchEdit();
if (mWordComposer.isComposingWord()) {
commitCurrentAutoCorrection(rawText.toString());
} else {
resetComposingState(true /* alsoResetLastComposedWord */);
}
mHandler.postUpdateSuggestionStrip();
final CharSequence text = specificTldProcessingOnTextInput(rawText);
if (SPACE_STATE_PHANTOM == mSpaceState) {
sendKeyCodePoint(Keyboard.CODE_SPACE);
}
mConnection.commitText(text, 1);
mConnection.endBatchEdit();
// Space state must be updated before calling updateShiftState
mSpaceState = SPACE_STATE_NONE;
mKeyboardSwitcher.updateShiftState();
mKeyboardSwitcher.onCodeInput(Keyboard.CODE_OUTPUT_TEXT);
mEnteredText = text;
}
@Override
public void onStartBatchInput() {
BatchInputUpdater.getInstance().onStartBatchInput();
mConnection.beginBatchEdit();
if (mWordComposer.isComposingWord()) {
if (ProductionFlag.IS_INTERNAL) {
if (mWordComposer.isBatchMode()) {
Stats.onAutoCorrection("", mWordComposer.getTypedWord(), " ", mWordComposer);
}
}
if (mWordComposer.size() <= 1) {
// We auto-correct the previous (typed, not gestured) string iff it's one character
// long. The reason for this is, even in the middle of gesture typing, you'll still
// tap one-letter words and you want them auto-corrected (typically, "i" in English
// should become "I"). However for any longer word, we assume that the reason for
// tapping probably is that the word you intend to type is not in the dictionary,
// so we do not attempt to correct, on the assumption that if that was a dictionary
// word, the user would probably have gestured instead.
commitCurrentAutoCorrection(LastComposedWord.NOT_A_SEPARATOR);
} else {
commitTyped(LastComposedWord.NOT_A_SEPARATOR);
}
mExpectingUpdateSelection = true;
// The following is necessary for the case where the user typed something but didn't
// manual pick it and didn't input any separator.
mSpaceState = SPACE_STATE_PHANTOM;
} else {
final int codePointBeforeCursor = mConnection.getCodePointBeforeCursor();
// TODO: reverse this logic. We should have the means to determine whether a character
// should usually be followed by a space, and it should be more readable.
if (Constants.NOT_A_CODE != codePointBeforeCursor
&& !Character.isWhitespace(codePointBeforeCursor)
&& !mCurrentSettings.isPhantomSpacePromotingSymbol(codePointBeforeCursor)
&& !mCurrentSettings.isWeakSpaceStripper(codePointBeforeCursor)) {
mSpaceState = SPACE_STATE_PHANTOM;
}
}
mConnection.endBatchEdit();
mWordComposer.setCapitalizedModeAtStartComposingTime(getActualCapsMode());
}
private static final class BatchInputUpdater implements Handler.Callback {
private final Handler mHandler;
private LatinIME mLatinIme;
private boolean mInBatchInput; // synchornized using "this".
private BatchInputUpdater() {
final HandlerThread handlerThread = new HandlerThread(
BatchInputUpdater.class.getSimpleName());
handlerThread.start();
mHandler = new Handler(handlerThread.getLooper(), this);
}
// Initialization-on-demand holder
private static final class OnDemandInitializationHolder {
public static final BatchInputUpdater sInstance = new BatchInputUpdater();
}
public static BatchInputUpdater getInstance() {
return OnDemandInitializationHolder.sInstance;
}
private static final int MSG_UPDATE_GESTURE_PREVIEW_AND_SUGGESTION_STRIP = 1;
@Override
public boolean handleMessage(final Message msg) {
switch (msg.what) {
case MSG_UPDATE_GESTURE_PREVIEW_AND_SUGGESTION_STRIP:
updateBatchInput((InputPointers)msg.obj, mLatinIme);
break;
}
return true;
}
// Run in the UI thread.
public synchronized void onStartBatchInput() {
mInBatchInput = true;
}
// Run in the Handler thread.
private synchronized void updateBatchInput(final InputPointers batchPointers,
final LatinIME latinIme) {
if (!mInBatchInput) {
// Batch input has ended while the message was being delivered.
return;
}
final SuggestedWords suggestedWords = getSuggestedWordsGestureLocked(
batchPointers, latinIme);
latinIme.mHandler.showGesturePreviewAndSuggestionStrip(
suggestedWords, false /* dismissGestureFloatingPreviewText */);
}
// Run in the UI thread.
public void onUpdateBatchInput(final InputPointers batchPointers, final LatinIME latinIme) {
mLatinIme = latinIme;
if (mHandler.hasMessages(MSG_UPDATE_GESTURE_PREVIEW_AND_SUGGESTION_STRIP)) {
return;
}
mHandler.obtainMessage(
MSG_UPDATE_GESTURE_PREVIEW_AND_SUGGESTION_STRIP, batchPointers)
.sendToTarget();
}
// Run in the UI thread.
public synchronized SuggestedWords onEndBatchInput(final InputPointers batchPointers,
final LatinIME latinIme) {
mInBatchInput = false;
final SuggestedWords suggestedWords = getSuggestedWordsGestureLocked(
batchPointers, latinIme);
latinIme.mHandler.showGesturePreviewAndSuggestionStrip(
suggestedWords, true /* dismissGestureFloatingPreviewText */);
return suggestedWords;
}
// {@link LatinIME#getSuggestedWords(int)} method calls with same session id have to
// be synchronized.
private static SuggestedWords getSuggestedWordsGestureLocked(
final InputPointers batchPointers, final LatinIME latinIme) {
latinIme.mWordComposer.setBatchInputPointers(batchPointers);
return latinIme.getSuggestedWords(Suggest.SESSION_GESTURE);
}
}
private void showGesturePreviewAndSuggestionStrip(final SuggestedWords suggestedWords,
final boolean dismissGestureFloatingPreviewText) {
final String batchInputText = (suggestedWords.size() > 0)
? suggestedWords.getWord(0) : null;
final KeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView();
mainKeyboardView.showGestureFloatingPreviewText(batchInputText);
showSuggestionStrip(suggestedWords, null);
if (dismissGestureFloatingPreviewText) {
mainKeyboardView.dismissGestureFloatingPreviewText();
}
}
@Override
public void onUpdateBatchInput(final InputPointers batchPointers) {
BatchInputUpdater.getInstance().onUpdateBatchInput(batchPointers, this);
}
@Override
public void onEndBatchInput(final InputPointers batchPointers) {
final SuggestedWords suggestedWords = BatchInputUpdater.getInstance().onEndBatchInput(
batchPointers, this);
final String batchInputText = (suggestedWords.size() > 0)
? suggestedWords.getWord(0) : null;
if (TextUtils.isEmpty(batchInputText)) {
return;
}
mWordComposer.setBatchInputWord(batchInputText);
mConnection.beginBatchEdit();
if (SPACE_STATE_PHANTOM == mSpaceState) {
sendKeyCodePoint(Keyboard.CODE_SPACE);
}
mConnection.setComposingText(batchInputText, 1);
mExpectingUpdateSelection = true;
mConnection.endBatchEdit();
// Space state must be updated before calling updateShiftState
mSpaceState = SPACE_STATE_PHANTOM;
mKeyboardSwitcher.updateShiftState();
}
private CharSequence specificTldProcessingOnTextInput(final CharSequence text) {
if (text.length() <= 1 || text.charAt(0) != Keyboard.CODE_PERIOD
|| !Character.isLetter(text.charAt(1))) {
// Not a tld: do nothing.
return text;
}
// We have a TLD (or something that looks like this): make sure we don't add
// a space even if currently in phantom mode.
mSpaceState = SPACE_STATE_NONE;
// TODO: use getCodePointBeforeCursor instead to improve performance and simplify the code
final CharSequence lastOne = mConnection.getTextBeforeCursor(1, 0);
if (lastOne != null && lastOne.length() == 1
&& lastOne.charAt(0) == Keyboard.CODE_PERIOD) {
return text.subSequence(1, text.length());
} else {
return text;
}
}
// Called from PointerTracker through the KeyboardActionListener interface
@Override
public void onCancelInput() {
// User released a finger outside any key
mKeyboardSwitcher.onCancelInput();
}
private void handleBackspace(final int spaceState) {
// In many cases, we may have to put the keyboard in auto-shift state again. However
// we want to wait a few milliseconds before doing it to avoid the keyboard flashing
// during key repeat.
mHandler.postUpdateShiftState();
if (mWordComposer.isComposingWord()) {
final int length = mWordComposer.size();
if (length > 0) {
// Immediately after a batch input.
if (SPACE_STATE_PHANTOM == spaceState) {
mWordComposer.reset();
} else {
mWordComposer.deleteLast();
}
mConnection.setComposingText(getTextWithUnderline(mWordComposer.getTypedWord()), 1);
mHandler.postUpdateSuggestionStrip();
} else {
mConnection.deleteSurroundingText(1, 0);
}
} else {
if (mLastComposedWord.canRevertCommit()) {
if (ProductionFlag.IS_INTERNAL) {
Stats.onAutoCorrectionCancellation();
}
revertCommit();
return;
}
if (mEnteredText != null && mConnection.sameAsTextBeforeCursor(mEnteredText)) {
// Cancel multi-character input: remove the text we just entered.
// This is triggered on backspace after a key that inputs multiple characters,
// like the smiley key or the .com key.
final int length = mEnteredText.length();
mConnection.deleteSurroundingText(length, 0);
mEnteredText = null;
// If we have mEnteredText, then we know that mHasUncommittedTypedChars == false.
// In addition we know that spaceState is false, and that we should not be
// reverting any autocorrect at this point. So we can safely return.
return;
}
if (SPACE_STATE_DOUBLE == spaceState) {
mHandler.cancelDoubleSpacesTimer();
if (mConnection.revertDoubleSpace()) {
// No need to reset mSpaceState, it has already be done (that's why we
// receive it as a parameter)
return;
}
} else if (SPACE_STATE_SWAP_PUNCTUATION == spaceState) {
if (mConnection.revertSwapPunctuation()) {
// Likewise
return;
}
}
// No cancelling of commit/double space/swap: we have a regular backspace.
// We should backspace one char and restart suggestion if at the end of a word.
if (mLastSelectionStart != mLastSelectionEnd) {
// If there is a selection, remove it.
final int lengthToDelete = mLastSelectionEnd - mLastSelectionStart;
mConnection.setSelection(mLastSelectionEnd, mLastSelectionEnd);
mConnection.deleteSurroundingText(lengthToDelete, 0);
} else {
// There is no selection, just delete one character.
if (NOT_A_CURSOR_POSITION == mLastSelectionEnd) {
// This should never happen.
Log.e(TAG, "Backspace when we don't know the selection position");
}
// 16 is android.os.Build.VERSION_CODES.JELLY_BEAN but we can't write it because
// we want to be able to compile against the Ice Cream Sandwich SDK.
if (mTargetApplicationInfo != null
&& mTargetApplicationInfo.targetSdkVersion < 16) {
// Backward compatibility mode. Before Jelly bean, the keyboard would simulate
// a hardware keyboard event on pressing enter or delete. This is bad for many
// reasons (there are race conditions with commits) but some applications are
// relying on this behavior so we continue to support it for older apps.
sendDownUpKeyEventForBackwardCompatibility(KeyEvent.KEYCODE_DEL);
} else {
mConnection.deleteSurroundingText(1, 0);
}
if (mDeleteCount > DELETE_ACCELERATE_AT) {
mConnection.deleteSurroundingText(1, 0);
}
}
if (mCurrentSettings.isSuggestionsRequested(mDisplayOrientation)) {
restartSuggestionsOnWordBeforeCursorIfAtEndOfWord();
}
}
}
private boolean maybeStripSpace(final int code,
final int spaceState, final boolean isFromSuggestionStrip) {
if (Keyboard.CODE_ENTER == code && SPACE_STATE_SWAP_PUNCTUATION == spaceState) {
mConnection.removeTrailingSpace();
return false;
} else if ((SPACE_STATE_WEAK == spaceState
|| SPACE_STATE_SWAP_PUNCTUATION == spaceState)
&& isFromSuggestionStrip) {
if (mCurrentSettings.isWeakSpaceSwapper(code)) {
return true;
} else {
if (mCurrentSettings.isWeakSpaceStripper(code)) {
mConnection.removeTrailingSpace();
}
return false;
}
} else {
return false;
}
}
private void handleCharacter(final int primaryCode, final int x,
final int y, final int spaceState) {
boolean isComposingWord = mWordComposer.isComposingWord();
if (SPACE_STATE_PHANTOM == spaceState &&
!mCurrentSettings.isSymbolExcludedFromWordSeparators(primaryCode)) {
if (isComposingWord) {
// Sanity check
throw new RuntimeException("Should not be composing here");
}
sendKeyCodePoint(Keyboard.CODE_SPACE);
}
// NOTE: isCursorTouchingWord() is a blocking IPC call, so it often takes several
// dozen milliseconds. Avoid calling it as much as possible, since we are on the UI
// thread here.
if (!isComposingWord && (isAlphabet(primaryCode)
|| mCurrentSettings.isSymbolExcludedFromWordSeparators(primaryCode))
&& mCurrentSettings.isSuggestionsRequested(mDisplayOrientation) &&
!mConnection.isCursorTouchingWord(mCurrentSettings)) {
// Reset entirely the composing state anyway, then start composing a new word unless
// the character is a single quote. The idea here is, single quote is not a
// separator and it should be treated as a normal character, except in the first
// position where it should not start composing a word.
isComposingWord = (Keyboard.CODE_SINGLE_QUOTE != primaryCode);
// Here we don't need to reset the last composed word. It will be reset
// when we commit this one, if we ever do; if on the other hand we backspace
// it entirely and resume suggestions on the previous word, we'd like to still
// have touch coordinates for it.
resetComposingState(false /* alsoResetLastComposedWord */);
}
if (isComposingWord) {
final int keyX, keyY;
if (KeyboardActionListener.Adapter.isInvalidCoordinate(x)
|| KeyboardActionListener.Adapter.isInvalidCoordinate(y)) {
keyX = x;
keyY = y;
} else {
final KeyDetector keyDetector =
mKeyboardSwitcher.getMainKeyboardView().getKeyDetector();
keyX = keyDetector.getTouchX(x);
keyY = keyDetector.getTouchY(y);
}
mWordComposer.add(primaryCode, keyX, keyY);
// If it's the first letter, make note of auto-caps state
if (mWordComposer.size() == 1) {
mWordComposer.setCapitalizedModeAtStartComposingTime(getActualCapsMode());
}
mConnection.setComposingText(getTextWithUnderline(mWordComposer.getTypedWord()), 1);
} else {
final boolean swapWeakSpace = maybeStripSpace(primaryCode,
spaceState, Constants.SUGGESTION_STRIP_COORDINATE == x);
sendKeyCodePoint(primaryCode);
if (swapWeakSpace) {
swapSwapperAndSpace();
mSpaceState = SPACE_STATE_WEAK;
}
// In case the "add to dictionary" hint was still displayed.
if (null != mSuggestionStripView) mSuggestionStripView.dismissAddToDictionaryHint();
}
mHandler.postUpdateSuggestionStrip();
if (ProductionFlag.IS_INTERNAL) {
Utils.Stats.onNonSeparator((char)primaryCode, x, y);
}
}
// Returns true if we did an autocorrection, false otherwise.
private boolean handleSeparator(final int primaryCode, final int x, final int y,
final int spaceState) {
boolean didAutoCorrect = false;
// Handle separator
if (mWordComposer.isComposingWord()) {
if (mCurrentSettings.mCorrectionEnabled) {
// TODO: maybe cache Strings in an <String> sparse array or something
commitCurrentAutoCorrection(new String(new int[]{primaryCode}, 0, 1));
didAutoCorrect = true;
} else {
commitTyped(new String(new int[]{primaryCode}, 0, 1));
}
}
final boolean swapWeakSpace = maybeStripSpace(primaryCode, spaceState,
Constants.SUGGESTION_STRIP_COORDINATE == x);
if (SPACE_STATE_PHANTOM == spaceState &&
mCurrentSettings.isPhantomSpacePromotingSymbol(primaryCode)) {
sendKeyCodePoint(Keyboard.CODE_SPACE);
}
sendKeyCodePoint(primaryCode);
if (Keyboard.CODE_SPACE == primaryCode) {
if (mCurrentSettings.isSuggestionsRequested(mDisplayOrientation)) {
if (maybeDoubleSpace()) {
mSpaceState = SPACE_STATE_DOUBLE;
} else if (!isShowingPunctuationList()) {
mSpaceState = SPACE_STATE_WEAK;
}
}
mHandler.startDoubleSpacesTimer();
if (!mConnection.isCursorTouchingWord(mCurrentSettings)) {
mHandler.postUpdateSuggestionStrip();
}
} else {
if (swapWeakSpace) {
swapSwapperAndSpace();
mSpaceState = SPACE_STATE_SWAP_PUNCTUATION;
} else if (SPACE_STATE_PHANTOM == spaceState
&& !mCurrentSettings.isWeakSpaceStripper(primaryCode)
&& !mCurrentSettings.isPhantomSpacePromotingSymbol(primaryCode)) {
// If we are in phantom space state, and the user presses a separator, we want to
// stay in phantom space state so that the next keypress has a chance to add the
// space. For example, if I type "Good dat", pick "day" from the suggestion strip
// then insert a comma and go on to typing the next word, I want the space to be
// inserted automatically before the next word, the same way it is when I don't
// input the comma.
// The case is a little different if the separator is a space stripper. Such a
// separator does not normally need a space on the right (that's the difference
// between swappers and strippers), so we should not stay in phantom space state if
// the separator is a stripper. Hence the additional test above.
mSpaceState = SPACE_STATE_PHANTOM;
}
// Set punctuation right away. onUpdateSelection will fire but tests whether it is
// already displayed or not, so it's okay.
setPunctuationSuggestions();
}
if (ProductionFlag.IS_INTERNAL) {
Utils.Stats.onSeparator((char)primaryCode, x, y);
}
mKeyboardSwitcher.updateShiftState();
return didAutoCorrect;
}
private CharSequence getTextWithUnderline(final CharSequence text) {
return mIsAutoCorrectionIndicatorOn
? SuggestionSpanUtils.getTextWithAutoCorrectionIndicatorUnderline(this, text)
: text;
}
private void handleClose() {
commitTyped(LastComposedWord.NOT_A_SEPARATOR);
requestHideSelf(0);
final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView();
if (mainKeyboardView != null) {
mainKeyboardView.closing();
}
}
// TODO: make this private
// Outside LatinIME, only used by the test suite.
/* package for tests */
boolean isShowingPunctuationList() {
if (mSuggestionStripView == null) return false;
return mCurrentSettings.mSuggestPuncList == mSuggestionStripView.getSuggestions();
}
private boolean isSuggestionsStripVisible() {
if (mSuggestionStripView == null)
return false;
if (mSuggestionStripView.isShowingAddToDictionaryHint())
return true;
if (!mCurrentSettings.isSuggestionStripVisibleInOrientation(mDisplayOrientation))
return false;
if (mCurrentSettings.isApplicationSpecifiedCompletionsOn())
return true;
return mCurrentSettings.isSuggestionsRequested(mDisplayOrientation);
}
private void clearSuggestionStrip() {
setSuggestionStrip(SuggestedWords.EMPTY, false);
setAutoCorrectionIndicator(false);
}
private void setSuggestionStrip(final SuggestedWords words, final boolean isAutoCorrection) {
if (mSuggestionStripView != null) {
mSuggestionStripView.setSuggestions(words);
mKeyboardSwitcher.onAutoCorrectionStateChanged(isAutoCorrection);
}
}
private void setAutoCorrectionIndicator(final boolean newAutoCorrectionIndicator) {
// Put a blue underline to a word in TextView which will be auto-corrected.
if (mIsAutoCorrectionIndicatorOn != newAutoCorrectionIndicator
&& mWordComposer.isComposingWord()) {
mIsAutoCorrectionIndicatorOn = newAutoCorrectionIndicator;
final CharSequence textWithUnderline =
getTextWithUnderline(mWordComposer.getTypedWord());
// TODO: when called from an updateSuggestionStrip() call that results from a posted
// message, this is called outside any batch edit. Potentially, this may result in some
// janky flickering of the screen, although the display speed makes it unlikely in
// the practice.
mConnection.setComposingText(textWithUnderline, 1);
}
}
private void updateSuggestionStrip() {
mHandler.cancelUpdateSuggestionStrip();
// Check if we have a suggestion engine attached.
if (mSuggest == null || !mCurrentSettings.isSuggestionsRequested(mDisplayOrientation)) {
if (mWordComposer.isComposingWord()) {
Log.w(TAG, "Called updateSuggestionsOrPredictions but suggestions were not "
+ "requested!");
mWordComposer.setAutoCorrection(mWordComposer.getTypedWord());
}
return;
}
if (!mWordComposer.isComposingWord() && !mCurrentSettings.mBigramPredictionEnabled) {
setPunctuationSuggestions();
return;
}
final SuggestedWords suggestedWords = getSuggestedWords(Suggest.SESSION_TYPING);
final String typedWord = mWordComposer.getTypedWord();
showSuggestionStrip(suggestedWords, typedWord);
}
private SuggestedWords getSuggestedWords(final int sessionId) {
final Keyboard keyboard = mKeyboardSwitcher.getKeyboard();
if (keyboard == null) {
return SuggestedWords.EMPTY;
}
final String typedWord = mWordComposer.getTypedWord();
// Get the word on which we should search the bigrams. If we are composing a word, it's
// whatever is *before* the half-committed word in the buffer, hence 2; if we aren't, we
// should just skip whitespace if any, so 1.
// TODO: this is slow (2-way IPC) - we should probably cache this instead.
final CharSequence prevWord =
mConnection.getNthPreviousWord(mCurrentSettings.mWordSeparators,
mWordComposer.isComposingWord() ? 2 : 1);
final SuggestedWords suggestedWords = mSuggest.getSuggestedWords(mWordComposer,
prevWord, keyboard.getProximityInfo(), mCurrentSettings.mCorrectionEnabled,
sessionId);
return maybeRetrieveOlderSuggestions(typedWord, suggestedWords);
}
private SuggestedWords maybeRetrieveOlderSuggestions(final CharSequence typedWord,
final SuggestedWords suggestedWords) {
// TODO: consolidate this into getSuggestedWords
// We update the suggestion strip only when we have some suggestions to show, i.e. when
// the suggestion count is > 1; else, we leave the old suggestions, with the typed word
// replaced with the new one. However, when the word is a dictionary word, or when the
// length of the typed word is 1 or 0 (after a deletion typically), we do want to remove the
// old suggestions. Also, if we are showing the "add to dictionary" hint, we need to
// revert to suggestions - although it is unclear how we can come here if it's displayed.
if (suggestedWords.size() > 1 || typedWord.length() <= 1
|| !suggestedWords.mTypedWordValid
|| mSuggestionStripView.isShowingAddToDictionaryHint()) {
return suggestedWords;
} else {
SuggestedWords previousSuggestions = mSuggestionStripView.getSuggestions();
if (previousSuggestions == mCurrentSettings.mSuggestPuncList) {
previousSuggestions = SuggestedWords.EMPTY;
}
final ArrayList<SuggestedWords.SuggestedWordInfo> typedWordAndPreviousSuggestions =
SuggestedWords.getTypedWordAndPreviousSuggestions(
typedWord, previousSuggestions);
return new SuggestedWords(typedWordAndPreviousSuggestions,
false /* typedWordValid */,
false /* hasAutoCorrectionCandidate */,
false /* isPunctuationSuggestions */,
true /* isObsoleteSuggestions */,
false /* isPrediction */);
}
}
private void showSuggestionStrip(final SuggestedWords suggestedWords,
final CharSequence typedWord) {
if (null == suggestedWords || suggestedWords.size() <= 0) {
clearSuggestionStrip();
return;
}
final CharSequence autoCorrection;
if (suggestedWords.size() > 0) {
if (suggestedWords.mWillAutoCorrect) {
autoCorrection = suggestedWords.getWord(1);
} else {
autoCorrection = typedWord;
}
} else {
autoCorrection = null;
}
mWordComposer.setAutoCorrection(autoCorrection);
final boolean isAutoCorrection = suggestedWords.willAutoCorrect();
setSuggestionStrip(suggestedWords, isAutoCorrection);
setAutoCorrectionIndicator(isAutoCorrection);
setSuggestionStripShown(isSuggestionsStripVisible());
}
private void commitCurrentAutoCorrection(final String separatorString) {
// Complete any pending suggestions query first
if (mHandler.hasPendingUpdateSuggestions()) {
updateSuggestionStrip();
}
final CharSequence typedAutoCorrection = mWordComposer.getAutoCorrectionOrNull();
final String typedWord = mWordComposer.getTypedWord();
final CharSequence autoCorrection = (typedAutoCorrection != null)
? typedAutoCorrection : typedWord;
if (autoCorrection != null) {
if (TextUtils.isEmpty(typedWord)) {
throw new RuntimeException("We have an auto-correction but the typed word "
+ "is empty? Impossible! I must commit suicide.");
}
if (ProductionFlag.IS_INTERNAL) {
Stats.onAutoCorrection(
typedWord, autoCorrection.toString(), separatorString, mWordComposer);
}
mExpectingUpdateSelection = true;
commitChosenWord(autoCorrection, LastComposedWord.COMMIT_TYPE_DECIDED_WORD,
separatorString);
if (!typedWord.equals(autoCorrection)) {
// This will make the correction flash for a short while as a visual clue
// to the user that auto-correction happened. It has no other effect; in particular
// note that this won't affect the text inside the text field AT ALL: it only makes
// the segment of text starting at the supplied index and running for the length
// of the auto-correction flash. At this moment, the "typedWord" argument is
// ignored by TextView.
mConnection.commitCorrection(
new CorrectionInfo(mLastSelectionEnd - typedWord.length(),
typedWord, autoCorrection));
}
}
}
// Called from {@link SuggestionStripView} through the {@link SuggestionStripView#Listener}
// interface
@Override
public void pickSuggestionManually(final int index, final CharSequence suggestion) {
final SuggestedWords suggestedWords = mSuggestionStripView.getSuggestions();
// If this is a punctuation picked from the suggestion strip, pass it to onCodeInput
if (suggestion.length() == 1 && isShowingPunctuationList()) {
// Word separators are suggested before the user inputs something.
// So, LatinImeLogger logs "" as a user's input.
LatinImeLogger.logOnManualSuggestion("", suggestion.toString(), index, suggestedWords);
// Rely on onCodeInput to do the complicated swapping/stripping logic consistently.
final int primaryCode = suggestion.charAt(0);
onCodeInput(primaryCode,
Constants.SUGGESTION_STRIP_COORDINATE, Constants.SUGGESTION_STRIP_COORDINATE);
if (ProductionFlag.IS_EXPERIMENTAL) {
ResearchLogger.latinIME_punctuationSuggestion(index, suggestion);
}
return;
}
mConnection.beginBatchEdit();
if (SPACE_STATE_PHANTOM == mSpaceState && suggestion.length() > 0
// In the batch input mode, a manually picked suggested word should just replace
// the current batch input text and there is no need for a phantom space.
&& !mWordComposer.isBatchMode()) {
int firstChar = Character.codePointAt(suggestion, 0);
if ((!mCurrentSettings.isWeakSpaceStripper(firstChar))
&& (!mCurrentSettings.isWeakSpaceSwapper(firstChar))) {
sendKeyCodePoint(Keyboard.CODE_SPACE);
}
}
if (mCurrentSettings.isApplicationSpecifiedCompletionsOn()
&& mApplicationSpecifiedCompletions != null
&& index >= 0 && index < mApplicationSpecifiedCompletions.length) {
if (mSuggestionStripView != null) {
mSuggestionStripView.clear();
}
mKeyboardSwitcher.updateShiftState();
resetComposingState(true /* alsoResetLastComposedWord */);
final CompletionInfo completionInfo = mApplicationSpecifiedCompletions[index];
mConnection.commitCompletion(completionInfo);
mConnection.endBatchEdit();
return;
}
// We need to log before we commit, because the word composer will store away the user
// typed word.
final String replacedWord = mWordComposer.getTypedWord().toString();
LatinImeLogger.logOnManualSuggestion(replacedWord,
suggestion.toString(), index, suggestedWords);
mExpectingUpdateSelection = true;
commitChosenWord(suggestion, LastComposedWord.COMMIT_TYPE_MANUAL_PICK,
LastComposedWord.NOT_A_SEPARATOR);
if (ProductionFlag.IS_EXPERIMENTAL) {
ResearchLogger.latinIME_pickSuggestionManually(replacedWord, index, suggestion);
}
mConnection.endBatchEdit();
// Don't allow cancellation of manual pick
mLastComposedWord.deactivate();
// Space state must be updated before calling updateShiftState
mSpaceState = SPACE_STATE_PHANTOM;
mKeyboardSwitcher.updateShiftState();
// We should show the "Touch again to save" hint if the user pressed the first entry
// AND it's in none of our current dictionaries (main, user or otherwise).
// Please note that if mSuggest is null, it means that everything is off: suggestion
// and correction, so we shouldn't try to show the hint
final boolean showingAddToDictionaryHint = index == 0 && mSuggest != null
// If the suggestion is not in the dictionary, the hint should be shown.
&& !AutoCorrection.isValidWord(mSuggest.getUnigramDictionaries(), suggestion, true);
if (ProductionFlag.IS_INTERNAL) {
Stats.onSeparator((char)Keyboard.CODE_SPACE,
Constants.NOT_A_COORDINATE, Constants.NOT_A_COORDINATE);
}
if (showingAddToDictionaryHint && mIsUserDictionaryAvailable) {
mSuggestionStripView.showAddToDictionaryHint(
suggestion, mCurrentSettings.mHintToSaveText);
} else {
// If we're not showing the "Touch again to save", then update the suggestion strip.
mHandler.postUpdateSuggestionStrip();
}
}
/**
* Commits the chosen word to the text field and saves it for later retrieval.
*/
private void commitChosenWord(final CharSequence chosenWord, final int commitType,
final String separatorString) {
final SuggestedWords suggestedWords = mSuggestionStripView.getSuggestions();
mConnection.commitText(SuggestionSpanUtils.getTextWithSuggestionSpan(
this, chosenWord, suggestedWords, mIsMainDictionaryAvailable), 1);
// Add the word to the user history dictionary
final CharSequence prevWord = addToUserHistoryDictionary(chosenWord);
// TODO: figure out here if this is an auto-correct or if the best word is actually
// what user typed. Note: currently this is done much later in
// LastComposedWord#didCommitTypedWord by string equality of the remembered
// strings.
mLastComposedWord = mWordComposer.commitWord(commitType, chosenWord.toString(),
separatorString, prevWord);
}
private void setPunctuationSuggestions() {
if (mCurrentSettings.mBigramPredictionEnabled) {
clearSuggestionStrip();
} else {
setSuggestionStrip(mCurrentSettings.mSuggestPuncList, false);
}
setAutoCorrectionIndicator(false);
setSuggestionStripShown(isSuggestionsStripVisible());
}
private CharSequence addToUserHistoryDictionary(final CharSequence suggestion) {
if (TextUtils.isEmpty(suggestion)) return null;
if (mSuggest == null) return null;
// If correction is not enabled, we don't add words to the user history dictionary.
// That's to avoid unintended additions in some sensitive fields, or fields that
// expect to receive non-words.
if (!mCurrentSettings.mCorrectionEnabled) return null;
final UserHistoryDictionary userHistoryDictionary = mUserHistoryDictionary;
if (userHistoryDictionary != null) {
final CharSequence prevWord
= mConnection.getNthPreviousWord(mCurrentSettings.mWordSeparators, 2);
final String secondWord;
if (mWordComposer.wasAutoCapitalized() && !mWordComposer.isMostlyCaps()) {
secondWord = suggestion.toString().toLowerCase(
mSubtypeSwitcher.getCurrentSubtypeLocale());
} else {
secondWord = suggestion.toString();
}
// We demote unrecognized words (frequency < 0, below) by specifying them as "invalid".
// We don't add words with 0-frequency (assuming they would be profanity etc.).
final int maxFreq = AutoCorrection.getMaxFrequency(
mSuggest.getUnigramDictionaries(), suggestion);
if (maxFreq == 0) return null;
userHistoryDictionary.addToUserHistory(null == prevWord ? null : prevWord.toString(),
secondWord, maxFreq > 0);
return prevWord;
}
return null;
}
/**
* Check if the cursor is actually at the end of a word. If so, restart suggestions on this
* word, else do nothing.
*/
private void restartSuggestionsOnWordBeforeCursorIfAtEndOfWord() {
final CharSequence word = mConnection.getWordBeforeCursorIfAtEndOfWord(mCurrentSettings);
if (null != word) {
restartSuggestionsOnWordBeforeCursor(word);
}
}
private void restartSuggestionsOnWordBeforeCursor(final CharSequence word) {
mWordComposer.setComposingWord(word, mKeyboardSwitcher.getKeyboard());
final int length = word.length();
mConnection.deleteSurroundingText(length, 0);
mConnection.setComposingText(word, 1);
mHandler.postUpdateSuggestionStrip();
}
private void revertCommit() {
final CharSequence previousWord = mLastComposedWord.mPrevWord;
final String originallyTypedWord = mLastComposedWord.mTypedWord;
final CharSequence committedWord = mLastComposedWord.mCommittedWord;
final int cancelLength = committedWord.length();
final int separatorLength = LastComposedWord.getSeparatorLength(
mLastComposedWord.mSeparatorString);
// TODO: should we check our saved separator against the actual contents of the text view?
final int deleteLength = cancelLength + separatorLength;
if (DEBUG) {
if (mWordComposer.isComposingWord()) {
throw new RuntimeException("revertCommit, but we are composing a word");
}
final String wordBeforeCursor =
mConnection.getTextBeforeCursor(deleteLength, 0)
.subSequence(0, cancelLength).toString();
if (!TextUtils.equals(committedWord, wordBeforeCursor)) {
throw new RuntimeException("revertCommit check failed: we thought we were "
+ "reverting \"" + committedWord
+ "\", but before the cursor we found \"" + wordBeforeCursor + "\"");
}
}
mConnection.deleteSurroundingText(deleteLength, 0);
if (!TextUtils.isEmpty(previousWord) && !TextUtils.isEmpty(committedWord)) {
mUserHistoryDictionary.cancelAddingUserHistory(
previousWord.toString(), committedWord.toString());
}
mConnection.commitText(originallyTypedWord + mLastComposedWord.mSeparatorString, 1);
if (ProductionFlag.IS_INTERNAL) {
Stats.onSeparator(mLastComposedWord.mSeparatorString,
Constants.NOT_A_COORDINATE, Constants.NOT_A_COORDINATE);
}
if (ProductionFlag.IS_EXPERIMENTAL) {
ResearchLogger.latinIME_revertCommit(originallyTypedWord);
}
// Don't restart suggestion yet. We'll restart if the user deletes the
// separator.
mLastComposedWord = LastComposedWord.NOT_A_COMPOSED_WORD;
// We have a separator between the word and the cursor: we should show predictions.
mHandler.postUpdateSuggestionStrip();
}
// Used by the RingCharBuffer
public boolean isWordSeparator(final int code) {
return mCurrentSettings.isWordSeparator(code);
}
// TODO: Make this private
// Outside LatinIME, only used by the {@link InputTestsBase} test suite.
/* package for test */
void loadKeyboard() {
// When the device locale is changed in SetupWizard etc., this method may get called via
// onConfigurationChanged before SoftInputWindow is shown.
initSuggest();
loadSettings();
if (mKeyboardSwitcher.getMainKeyboardView() != null) {
// Reload keyboard because the current language has been changed.
mKeyboardSwitcher.loadKeyboard(getCurrentInputEditorInfo(), mCurrentSettings);
}
// Since we just changed languages, we should re-evaluate suggestions with whatever word
// we are currently composing. If we are not composing anything, we may want to display
// predictions or punctuation signs (which is done by the updateSuggestionStrip anyway).
mHandler.postUpdateSuggestionStrip();
}
// TODO: Remove this method from {@link LatinIME} and move {@link FeedbackManager} to
// {@link KeyboardSwitcher}. Called from KeyboardSwitcher
public void hapticAndAudioFeedback(final int primaryCode) {
mFeedbackManager.hapticAndAudioFeedback(
primaryCode, mKeyboardSwitcher.getMainKeyboardView());
}
// Callback called by PointerTracker through the KeyboardActionListener. This is called when a
// key is depressed; release matching call is onReleaseKey below.
@Override
public void onPressKey(final int primaryCode) {
mKeyboardSwitcher.onPressKey(primaryCode);
}
// Callback by PointerTracker through the KeyboardActionListener. This is called when a key
// is released; press matching call is onPressKey above.
@Override
public void onReleaseKey(final int primaryCode, final boolean withSliding) {
mKeyboardSwitcher.onReleaseKey(primaryCode, withSliding);
// If accessibility is on, ensure the user receives keyboard state updates.
if (AccessibilityUtils.getInstance().isTouchExplorationEnabled()) {
switch (primaryCode) {
case Keyboard.CODE_SHIFT:
AccessibleKeyboardViewProxy.getInstance().notifyShiftState();
break;
case Keyboard.CODE_SWITCH_ALPHA_SYMBOL:
AccessibleKeyboardViewProxy.getInstance().notifySymbolsState();
break;
}
}
if (Keyboard.CODE_DELETE == primaryCode) {
// This is a stopgap solution to avoid leaving a high surrogate alone in a text view.
// In the future, we need to deprecate deteleSurroundingText() and have a surrogate
// pair-friendly way of deleting characters in InputConnection.
// TODO: use getCodePointBeforeCursor instead to improve performance
final CharSequence lastChar = mConnection.getTextBeforeCursor(1, 0);
if (!TextUtils.isEmpty(lastChar) && Character.isHighSurrogate(lastChar.charAt(0))) {
mConnection.deleteSurroundingText(1, 0);
}
}
}
// receive ringer mode change and network state change.
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(final Context context, final Intent intent) {
final String action = intent.getAction();
if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
mSubtypeSwitcher.onNetworkStateChanged(intent);
} else if (action.equals(AudioManager.RINGER_MODE_CHANGED_ACTION)) {
mFeedbackManager.onRingerModeChanged();
}
}
};
private void launchSettings() {
handleClose();
launchSubActivity(SettingsActivity.class);
}
// Called from debug code only
public void launchDebugSettings() {
handleClose();
launchSubActivity(DebugSettingsActivity.class);
}
public void launchKeyboardedDialogActivity(final Class<? extends Activity> activityClass) {
// Put the text in the attached EditText into a safe, saved state before switching to a
// new activity that will also use the soft keyboard.
commitTyped(LastComposedWord.NOT_A_SEPARATOR);
launchSubActivity(activityClass);
}
private void launchSubActivity(final Class<? extends Activity> activityClass) {
Intent intent = new Intent();
intent.setClass(LatinIME.this, activityClass);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
private void showSubtypeSelectorAndSettings() {
final CharSequence title = getString(R.string.english_ime_input_options);
final CharSequence[] items = new CharSequence[] {
// TODO: Should use new string "Select active input modes".
getString(R.string.language_selection_title),
getString(R.string.english_ime_settings),
};
final Context context = this;
final DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface di, int position) {
di.dismiss();
switch (position) {
case 0:
Intent intent = CompatUtils.getInputLanguageSelectionIntent(
ImfUtils.getInputMethodIdOfThisIme(context),
Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
| Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
break;
case 1:
launchSettings();
break;
}
}
};
final AlertDialog.Builder builder = new AlertDialog.Builder(this)
.setItems(items, listener)
.setTitle(title);
showOptionDialog(builder.create());
}
public void showOptionDialog(final AlertDialog dialog) {
final IBinder windowToken = mKeyboardSwitcher.getMainKeyboardView().getWindowToken();
if (windowToken == null) {
return;
}
dialog.setCancelable(true);
dialog.setCanceledOnTouchOutside(true);
final Window window = dialog.getWindow();
final WindowManager.LayoutParams lp = window.getAttributes();
lp.token = windowToken;
lp.type = WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG;
window.setAttributes(lp);
window.addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
mOptionsDialog = dialog;
dialog.show();
}
public void debugDumpStateAndCrashWithException(final String context) {
final StringBuilder s = new StringBuilder();
s.append("Target application : ").append(mTargetApplicationInfo.name)
.append("\nPackage : ").append(mTargetApplicationInfo.packageName)
.append("\nTarget app sdk version : ")
.append(mTargetApplicationInfo.targetSdkVersion)
.append("\nAttributes : ").append(mCurrentSettings.getInputAttributesDebugString())
.append("\nContext : ").append(context);
throw new RuntimeException(s.toString());
}
@Override
protected void dump(final FileDescriptor fd, final PrintWriter fout, final String[] args) {
super.dump(fd, fout, args);
final Printer p = new PrintWriterPrinter(fout);
p.println("LatinIME state :");
final Keyboard keyboard = mKeyboardSwitcher.getKeyboard();
final int keyboardMode = keyboard != null ? keyboard.mId.mMode : -1;
p.println(" Keyboard mode = " + keyboardMode);
p.println(" mIsSuggestionsSuggestionsRequested = "
+ mCurrentSettings.isSuggestionsRequested(mDisplayOrientation));
p.println(" mCorrectionEnabled=" + mCurrentSettings.mCorrectionEnabled);
p.println(" isComposingWord=" + mWordComposer.isComposingWord());
p.println(" mSoundOn=" + mCurrentSettings.mSoundOn);
p.println(" mVibrateOn=" + mCurrentSettings.mVibrateOn);
p.println(" mKeyPreviewPopupOn=" + mCurrentSettings.mKeyPreviewPopupOn);
p.println(" inputAttributes=" + mCurrentSettings.getInputAttributesDebugString());
}
}
| false | true | private void onStartInputViewInternal(final EditorInfo editorInfo, final boolean restarting) {
super.onStartInputView(editorInfo, restarting);
final KeyboardSwitcher switcher = mKeyboardSwitcher;
final MainKeyboardView mainKeyboardView = switcher.getMainKeyboardView();
if (editorInfo == null) {
Log.e(TAG, "Null EditorInfo in onStartInputView()");
if (LatinImeLogger.sDBG) {
throw new NullPointerException("Null EditorInfo in onStartInputView()");
}
return;
}
if (DEBUG) {
Log.d(TAG, "onStartInputView: editorInfo:"
+ String.format("inputType=0x%08x imeOptions=0x%08x",
editorInfo.inputType, editorInfo.imeOptions));
Log.d(TAG, "All caps = "
+ ((editorInfo.inputType & InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS) != 0)
+ ", sentence caps = "
+ ((editorInfo.inputType & InputType.TYPE_TEXT_FLAG_CAP_SENTENCES) != 0)
+ ", word caps = "
+ ((editorInfo.inputType & InputType.TYPE_TEXT_FLAG_CAP_WORDS) != 0));
}
if (ProductionFlag.IS_EXPERIMENTAL) {
ResearchLogger.latinIME_onStartInputViewInternal(editorInfo, mPrefs);
}
if (InputAttributes.inPrivateImeOptions(null, NO_MICROPHONE_COMPAT, editorInfo)) {
Log.w(TAG, "Deprecated private IME option specified: "
+ editorInfo.privateImeOptions);
Log.w(TAG, "Use " + getPackageName() + "." + NO_MICROPHONE + " instead");
}
if (InputAttributes.inPrivateImeOptions(getPackageName(), FORCE_ASCII, editorInfo)) {
Log.w(TAG, "Deprecated private IME option specified: "
+ editorInfo.privateImeOptions);
Log.w(TAG, "Use EditorInfo.IME_FLAG_FORCE_ASCII flag instead");
}
mTargetApplicationInfo =
TargetApplicationGetter.getCachedApplicationInfo(editorInfo.packageName);
if (null == mTargetApplicationInfo) {
new TargetApplicationGetter(this /* context */, this /* listener */)
.execute(editorInfo.packageName);
}
LatinImeLogger.onStartInputView(editorInfo);
// In landscape mode, this method gets called without the input view being created.
if (mainKeyboardView == null) {
return;
}
// Forward this event to the accessibility utilities, if enabled.
final AccessibilityUtils accessUtils = AccessibilityUtils.getInstance();
if (accessUtils.isTouchExplorationEnabled()) {
accessUtils.onStartInputViewInternal(mainKeyboardView, editorInfo, restarting);
}
final boolean selectionChanged = mLastSelectionStart != editorInfo.initialSelStart
|| mLastSelectionEnd != editorInfo.initialSelEnd;
final boolean inputTypeChanged = !mCurrentSettings.isSameInputType(editorInfo);
final boolean isDifferentTextField = !restarting || inputTypeChanged;
if (isDifferentTextField) {
final boolean currentSubtypeEnabled = mSubtypeSwitcher
.updateParametersOnStartInputViewAndReturnIfCurrentSubtypeEnabled();
if (!currentSubtypeEnabled) {
// Current subtype is disabled. Needs to update subtype and keyboard.
final InputMethodSubtype newSubtype = ImfUtils.getCurrentInputMethodSubtype(
this, mSubtypeSwitcher.getNoLanguageSubtype());
mSubtypeSwitcher.updateSubtype(newSubtype);
loadKeyboard();
}
}
// The EditorInfo might have a flag that affects fullscreen mode.
// Note: This call should be done by InputMethodService?
updateFullscreenMode();
mApplicationSpecifiedCompletions = null;
if (isDifferentTextField || selectionChanged) {
// If the selection changed, we reset the input state. Essentially, we come here with
// restarting == true when the app called setText() or similar. We should reset the
// state if the app set the text to something else, but keep it if it set a suggestion
// or something.
mEnteredText = null;
resetComposingState(true /* alsoResetLastComposedWord */);
mDeleteCount = 0;
mSpaceState = SPACE_STATE_NONE;
if (mSuggestionStripView != null) {
// This will set the punctuation suggestions if next word suggestion is off;
// otherwise it will clear the suggestion strip.
setPunctuationSuggestions();
}
}
mConnection.resetCachesUponCursorMove(editorInfo.initialSelStart);
if (isDifferentTextField) {
mainKeyboardView.closing();
loadSettings();
if (mSuggest != null && mCurrentSettings.mCorrectionEnabled) {
mSuggest.setAutoCorrectionThreshold(mCurrentSettings.mAutoCorrectionThreshold);
}
switcher.loadKeyboard(editorInfo, mCurrentSettings);
} else if (restarting) {
// TODO: Come up with a more comprehensive way to reset the keyboard layout when
// a keyboard layout set doesn't get reloaded in this method.
switcher.resetKeyboardStateToAlphabet();
}
setSuggestionStripShownInternal(
isSuggestionsStripVisible(), /* needsInputViewShown */ false);
mLastSelectionStart = editorInfo.initialSelStart;
mLastSelectionEnd = editorInfo.initialSelEnd;
// If we come here something in the text state is very likely to have changed.
// We should update the shift state regardless of whether we are restarting or not, because
// this is not perceived as a layout change that may be disruptive like we may have with
// switcher.loadKeyboard; in apps like Talk, we come here when the text is sent and the
// field gets emptied and we need to re-evaluate the shift state, but not the whole layout
// which would be disruptive.
// Space state must be updated before calling updateShiftState
mKeyboardSwitcher.updateShiftState();
mHandler.cancelUpdateSuggestionStrip();
mHandler.cancelDoubleSpacesTimer();
mainKeyboardView.setMainDictionaryAvailability(mIsMainDictionaryAvailable);
mainKeyboardView.setKeyPreviewPopupEnabled(mCurrentSettings.mKeyPreviewPopupOn,
mCurrentSettings.mKeyPreviewPopupDismissDelay);
mainKeyboardView.setGestureHandlingEnabledByUser(mCurrentSettings.mGestureInputEnabled);
mainKeyboardView.setGesturePreviewMode(mCurrentSettings.mGesturePreviewTrailEnabled,
mCurrentSettings.mGestureFloatingPreviewTextEnabled);
if (TRACE) Debug.startMethodTracing("/data/trace/latinime");
}
| private void onStartInputViewInternal(final EditorInfo editorInfo, final boolean restarting) {
super.onStartInputView(editorInfo, restarting);
final KeyboardSwitcher switcher = mKeyboardSwitcher;
final MainKeyboardView mainKeyboardView = switcher.getMainKeyboardView();
if (editorInfo == null) {
Log.e(TAG, "Null EditorInfo in onStartInputView()");
if (LatinImeLogger.sDBG) {
throw new NullPointerException("Null EditorInfo in onStartInputView()");
}
return;
}
if (DEBUG) {
Log.d(TAG, "onStartInputView: editorInfo:"
+ String.format("inputType=0x%08x imeOptions=0x%08x",
editorInfo.inputType, editorInfo.imeOptions));
Log.d(TAG, "All caps = "
+ ((editorInfo.inputType & InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS) != 0)
+ ", sentence caps = "
+ ((editorInfo.inputType & InputType.TYPE_TEXT_FLAG_CAP_SENTENCES) != 0)
+ ", word caps = "
+ ((editorInfo.inputType & InputType.TYPE_TEXT_FLAG_CAP_WORDS) != 0));
}
if (ProductionFlag.IS_EXPERIMENTAL) {
ResearchLogger.latinIME_onStartInputViewInternal(editorInfo, mPrefs);
}
if (InputAttributes.inPrivateImeOptions(null, NO_MICROPHONE_COMPAT, editorInfo)) {
Log.w(TAG, "Deprecated private IME option specified: "
+ editorInfo.privateImeOptions);
Log.w(TAG, "Use " + getPackageName() + "." + NO_MICROPHONE + " instead");
}
if (InputAttributes.inPrivateImeOptions(getPackageName(), FORCE_ASCII, editorInfo)) {
Log.w(TAG, "Deprecated private IME option specified: "
+ editorInfo.privateImeOptions);
Log.w(TAG, "Use EditorInfo.IME_FLAG_FORCE_ASCII flag instead");
}
mTargetApplicationInfo =
TargetApplicationGetter.getCachedApplicationInfo(editorInfo.packageName);
if (null == mTargetApplicationInfo) {
new TargetApplicationGetter(this /* context */, this /* listener */)
.execute(editorInfo.packageName);
}
LatinImeLogger.onStartInputView(editorInfo);
// In landscape mode, this method gets called without the input view being created.
if (mainKeyboardView == null) {
return;
}
// Forward this event to the accessibility utilities, if enabled.
final AccessibilityUtils accessUtils = AccessibilityUtils.getInstance();
if (accessUtils.isTouchExplorationEnabled()) {
accessUtils.onStartInputViewInternal(mainKeyboardView, editorInfo, restarting);
}
final boolean selectionChanged = mLastSelectionStart != editorInfo.initialSelStart
|| mLastSelectionEnd != editorInfo.initialSelEnd;
final boolean inputTypeChanged = !mCurrentSettings.isSameInputType(editorInfo);
final boolean isDifferentTextField = !restarting || inputTypeChanged;
if (isDifferentTextField) {
final boolean currentSubtypeEnabled = mSubtypeSwitcher
.updateParametersOnStartInputViewAndReturnIfCurrentSubtypeEnabled();
if (!currentSubtypeEnabled) {
// Current subtype is disabled. Needs to update subtype and keyboard.
final InputMethodSubtype newSubtype = ImfUtils.getCurrentInputMethodSubtype(
this, mSubtypeSwitcher.getNoLanguageSubtype());
mSubtypeSwitcher.updateSubtype(newSubtype);
loadKeyboard();
}
}
// The EditorInfo might have a flag that affects fullscreen mode.
// Note: This call should be done by InputMethodService?
updateFullscreenMode();
mApplicationSpecifiedCompletions = null;
// The app calling setText() has the effect of clearing the composing
// span, so we should reset our state unconditionally, even if restarting is true.
mEnteredText = null;
resetComposingState(true /* alsoResetLastComposedWord */);
mDeleteCount = 0;
mSpaceState = SPACE_STATE_NONE;
if (mSuggestionStripView != null) {
// This will set the punctuation suggestions if next word suggestion is off;
// otherwise it will clear the suggestion strip.
setPunctuationSuggestions();
}
mConnection.resetCachesUponCursorMove(editorInfo.initialSelStart);
if (isDifferentTextField) {
mainKeyboardView.closing();
loadSettings();
if (mSuggest != null && mCurrentSettings.mCorrectionEnabled) {
mSuggest.setAutoCorrectionThreshold(mCurrentSettings.mAutoCorrectionThreshold);
}
switcher.loadKeyboard(editorInfo, mCurrentSettings);
} else if (restarting) {
// TODO: Come up with a more comprehensive way to reset the keyboard layout when
// a keyboard layout set doesn't get reloaded in this method.
switcher.resetKeyboardStateToAlphabet();
}
setSuggestionStripShownInternal(
isSuggestionsStripVisible(), /* needsInputViewShown */ false);
mLastSelectionStart = editorInfo.initialSelStart;
mLastSelectionEnd = editorInfo.initialSelEnd;
// If we come here something in the text state is very likely to have changed.
// We should update the shift state regardless of whether we are restarting or not, because
// this is not perceived as a layout change that may be disruptive like we may have with
// switcher.loadKeyboard; in apps like Talk, we come here when the text is sent and the
// field gets emptied and we need to re-evaluate the shift state, but not the whole layout
// which would be disruptive.
// Space state must be updated before calling updateShiftState
mKeyboardSwitcher.updateShiftState();
mHandler.cancelUpdateSuggestionStrip();
mHandler.cancelDoubleSpacesTimer();
mainKeyboardView.setMainDictionaryAvailability(mIsMainDictionaryAvailable);
mainKeyboardView.setKeyPreviewPopupEnabled(mCurrentSettings.mKeyPreviewPopupOn,
mCurrentSettings.mKeyPreviewPopupDismissDelay);
mainKeyboardView.setGestureHandlingEnabledByUser(mCurrentSettings.mGestureInputEnabled);
mainKeyboardView.setGesturePreviewMode(mCurrentSettings.mGesturePreviewTrailEnabled,
mCurrentSettings.mGestureFloatingPreviewTextEnabled);
if (TRACE) Debug.startMethodTracing("/data/trace/latinime");
}
|
diff --git a/java/tools/src/com/jopdesign/debug/jdwp/util/PacketPrinter.java b/java/tools/src/com/jopdesign/debug/jdwp/util/PacketPrinter.java
index f44ce82f..a2fcc84f 100644
--- a/java/tools/src/com/jopdesign/debug/jdwp/util/PacketPrinter.java
+++ b/java/tools/src/com/jopdesign/debug/jdwp/util/PacketPrinter.java
@@ -1,174 +1,176 @@
/*******************************************************************************
An implementation of the Java Debug Wire Protocol (JDWP) for JOP
Copyright (C) 2007 Paulo Abadie Guedes
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*******************************************************************************/
package com.jopdesign.debug.jdwp.util;
import java.io.FileNotFoundException;
import java.io.IOException;
import com.jopdesign.debug.jdwp.constants.JDWPConstants;
import com.jopdesign.debug.jdwp.sniffer.PacketInputStreamReader;
import com.sun.tools.jdi.PacketWrapper;
/**
* PacketPrinter.java
*
*
* @author Paulo Abadie Guedes
*
* 08/06/2007 - 16:22:18
*
*/
public class PacketPrinter
{
public static void main(String args[])
{
String [] data;
if(args.length > 0)
{
data = args;
}
else
{
data = new String[2];
data[0] = JDWPConstants.DEFAULT_SERVER_FILE;
data[1] = JDWPConstants.DEFAULT_CLIENT_FILE;
}
if(data.length == 1)
{
String name = data[0];
try
{
dumpJDWPPacketLog(name);
}
catch(FileNotFoundException exception)
{
System.out.print(" Failure: file not found -> ");
System.out.println(name);
}
catch(IOException exception)
{
System.out.print(" Failure: cannot open file -> ");
System.out.println(name);
}
}
else
{
try
{
printRequestAndAnswer(data[0], data[1]);
}
catch(IOException exception)
{
System.out.println("Failure: " + exception.getMessage());
exception.printStackTrace();
+ // exit with failure
+ System.exit(-1);
}
}
}
/**
* @param name
* @throws FileNotFoundException
* @throws IOException
*/
public static void dumpJDWPPacketLog(String name) throws FileNotFoundException, IOException
{
PacketList list = PacketInputStreamReader.readPacketList(name);
System.out.println("");
System.out.print(" Number of JDWP packets read from " + name + ": ");
System.out.println(list.size());
// printInfo(list, 20);
PacketPrinter.printInfo(list, list.size());
}
public static void printInfo(PacketList list, int numPackets)
{
int i, num;
num = list.size();
// avoid falling out of the list border
if(numPackets > num)
{
numPackets = num;
}
for(i = 0; i < numPackets; i++)
{
PacketWrapper packet = list.get(i);
packet.printInformation();
}
}
public static void printInfo(PacketList list)
{
printInfo(list, list.size());
}
/**
* Test:
*
* Read the set of messages from the server, build a list of packets.
* Read the set of messages from the client, build a list of packets.
*
* Print information about packets, matching request and answer.
*
* @throws FileNotFoundException
*/
public static void printRequestAndAnswer() throws IOException
{
printRequestAndAnswer(JDWPConstants.DEFAULT_SERVER_FILE,
JDWPConstants.DEFAULT_CLIENT_FILE);
}
public static void printRequestAndAnswer(String serverFile, String clientFile)
throws IOException
{
PacketList serverList = PacketInputStreamReader.readPacketList(serverFile);
PacketList clientList = PacketInputStreamReader.readPacketList(clientFile);
int i, count;
count = serverList.size();
for(i = 0; i < count; i++)
{
PacketWrapper packet = serverList.get(i);
PacketPrinter.printAnswerPackets(packet, clientList);
}
}
public static void printAnswerPackets(PacketWrapper packet, PacketList list)
{
PacketList replyList = list.getAnswerSublist(packet);
System.out.print(" Packet: ");
packet.printInformation();
System.out.println();
System.out.println(" Packet reply list: ");
printInfo(replyList);
System.out.println("----------------------------------------");
}
}
| true | true | public static void main(String args[])
{
String [] data;
if(args.length > 0)
{
data = args;
}
else
{
data = new String[2];
data[0] = JDWPConstants.DEFAULT_SERVER_FILE;
data[1] = JDWPConstants.DEFAULT_CLIENT_FILE;
}
if(data.length == 1)
{
String name = data[0];
try
{
dumpJDWPPacketLog(name);
}
catch(FileNotFoundException exception)
{
System.out.print(" Failure: file not found -> ");
System.out.println(name);
}
catch(IOException exception)
{
System.out.print(" Failure: cannot open file -> ");
System.out.println(name);
}
}
else
{
try
{
printRequestAndAnswer(data[0], data[1]);
}
catch(IOException exception)
{
System.out.println("Failure: " + exception.getMessage());
exception.printStackTrace();
}
}
}
| public static void main(String args[])
{
String [] data;
if(args.length > 0)
{
data = args;
}
else
{
data = new String[2];
data[0] = JDWPConstants.DEFAULT_SERVER_FILE;
data[1] = JDWPConstants.DEFAULT_CLIENT_FILE;
}
if(data.length == 1)
{
String name = data[0];
try
{
dumpJDWPPacketLog(name);
}
catch(FileNotFoundException exception)
{
System.out.print(" Failure: file not found -> ");
System.out.println(name);
}
catch(IOException exception)
{
System.out.print(" Failure: cannot open file -> ");
System.out.println(name);
}
}
else
{
try
{
printRequestAndAnswer(data[0], data[1]);
}
catch(IOException exception)
{
System.out.println("Failure: " + exception.getMessage());
exception.printStackTrace();
// exit with failure
System.exit(-1);
}
}
}
|
diff --git a/src/java/com/threerings/getdown/launcher/GetdownApplet.java b/src/java/com/threerings/getdown/launcher/GetdownApplet.java
index baa390d..f680c75 100644
--- a/src/java/com/threerings/getdown/launcher/GetdownApplet.java
+++ b/src/java/com/threerings/getdown/launcher/GetdownApplet.java
@@ -1,308 +1,318 @@
//
// $Id$
//
// Getdown - application installer, patcher and launcher
// Copyright (C) 2004-2006 Three Rings Design, 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.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
package com.threerings.getdown.launcher;
import java.awt.Container;
import java.awt.Image;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.security.Signature;
import java.security.cert.Certificate;
import javax.swing.JApplet;
import javax.swing.JPanel;
import java.io.IOException;
import java.io.FileOutputStream;
import java.io.File;
import java.io.PrintStream;
import netscape.javascript.JSObject;
import netscape.javascript.JSException;
import org.apache.commons.codec.binary.Base64;
import com.samskivert.util.RunAnywhere;
import com.samskivert.util.StringUtil;
import com.threerings.getdown.Log;
/**
* An applet that can be used to launch a Getdown application (when signed and
* given privileges).
*/
public class GetdownApplet extends JApplet
{
@Override // documentation inherited
public void init ()
{
// verify that we are not being hijacked to execute malicious code in the name of the
// signer
String appbase = getParameter("appbase");
String appname = getParameter("appname");
String imgpath = getParameter("bgimage");
if (appbase == null) {
appbase = "";
}
if (appname == null) {
appname = "";
}
if (imgpath == null) {
imgpath = "";
}
Log.info("App Base: " + appbase);
Log.info("App Name: " + appname);
File appdir = null;
try {
appdir = initGetdown(appbase, appname, imgpath);
// if a background image was specified, grabbit
try {
if (!StringUtil.isBlank(imgpath)) {
_bgimage = getImage(new URL(getDocumentBase(), imgpath));
}
} catch (Exception e) {
Log.info("Failed to load background image [path=" + imgpath + "].");
Log.logStackTrace(e);
}
// record a few things for posterity
Log.info("------------------ VM Info ------------------");
Log.info("-- OS Name: " + System.getProperty("os.name"));
Log.info("-- OS Arch: " + System.getProperty("os.arch"));
Log.info("-- OS Vers: " + System.getProperty("os.version"));
Log.info("-- Java Vers: " + System.getProperty("java.version"));
Log.info("-- Java Home: " + System.getProperty("java.home"));
Log.info("-- User Name: " + System.getProperty("user.name"));
Log.info("-- User Home: " + System.getProperty("user.home"));
Log.info("-- Cur dir: " + System.getProperty("user.dir"));
Log.info("---------------------------------------------");
} catch (Exception e) {
_errmsg = e.getMessage();
}
try {
_getdown = new Getdown(appdir, null) {
protected Container createContainer () {
getContentPane().removeAll();
return getContentPane();
}
protected void showContainer () {
((JPanel)getContentPane()).revalidate();
}
protected void disposeContainer () {
// nothing to do as we're in an applet
}
protected boolean invokeDirect () {
return "true".equalsIgnoreCase(getParameter("direct"));
}
protected JApplet getApplet () {
return GetdownApplet.this;
}
protected Image getBackgroundImage () {
return _bgimage == null ?
super.getBackgroundImage() : _bgimage;
}
protected void exit (int exitCode) {
// don't exit as we're in an applet
}
@Override protected void setStatus (
final String message, final int percent, final long remaining, boolean createUI)
{
super.setStatus(message, percent, remaining, createUI);
try {
JSObject.getWindow(GetdownApplet.this).call(
"getdownStatus", new Object[] { message, percent, remaining });
} catch (Throwable t) {
Log.warning("Failed to communicate status to JavaScript: " + t);
}
}
};
// set up our user interface immediately
_getdown.preInit();
} catch (Exception e) {
Log.logStackTrace(e);
}
}
@Override // documentation inherited
public void start ()
{
if (_errmsg != null) {
_getdown.updateStatus(_errmsg);
} else {
try {
_getdown.start();
} catch (Exception e) {
Log.logStackTrace(e);
}
}
}
@Override // documentation inherited
public void stop ()
{
// TODO
}
/**
* Does all the fiddly initialization of Getdown and throws an exception if something goes
* horribly wrong. If an exception is thrown we will abort the whole process and display an
* error message to the user.
*/
protected File initGetdown (String appbase, String appname, String imgpath)
throws Exception
{
// getdown requires full read/write permissions to the system; if we don't have this, then
// we need to not do anything unsafe, and display a message to the user telling them they
// need to (groan) close out of the web browser entirely and re-launch the browser, go to
// our site, and accept the certificate
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
try {
sm.checkWrite("getdown");
sm.checkPropertiesAccess();
} catch (SecurityException se) {
Log.warning("Signed applet rejected by user [se=" + se + "].");
throw new Exception("m.insufficient_permissions_error");
}
}
Object[] signers = GetdownApplet.class.getSigners();
if (signers.length == 0) {
Log.info("No signers, not verifying param signature.");
} else {
String signature = getParameter("signature");
if (signature == null) {
signature = "";
}
Log.info("Verifying signature '" + signature + "'.");
String params = appbase + appname + imgpath;
int validated = 0;
for (Object signer : signers) {
if (signer instanceof Certificate) {
Certificate cert = (Certificate)signer;
try {
Signature sig = Signature.getInstance("SHA1withRSA");
sig.initVerify(cert);
sig.update(params.getBytes());
if (!sig.verify(Base64.decodeBase64(signature.getBytes()))) {
Log.info("Signature does not match '" + cert.getPublicKey() + "'.");
}
validated++;
} catch (GeneralSecurityException gse) {
// no problem!
}
}
}
// if we couldn't find a key that validates our parameters, we are the hosed!
if (validated == 0) {
throw new Exception("m.corrupt_param_signature_error");
}
}
// pass through properties parameters
String properties = getParameter("properties");
if (properties != null) {
String[] proparray = properties.split(" ");
for (String property : proparray) {
String key = property.substring(property.indexOf("-D") + 2, property.indexOf("="));
String value = property.substring(property.indexOf("=") + 1);
System.setProperty(key, value);
}
}
// when run from an applet, we install to the user's home directory
String root;
if (RunAnywhere.isWindows()) {
+ String verStr = System.getProperty("os.version");
root = "Application Data";
+ try {
+ float version = Float.parseFloat(verStr);
+ if (version >= 6.0) {
+ // Vista makes us write it here.... Yay.
+ root = "AppData" + File.separator + "LocalLow";
+ }
+ } catch (Exception e) {
+ Log.warning("Couldn't parse OS version: " +verStr);
+ }
} else if (RunAnywhere.isMacOS()) {
root = "Library" + File.separator + "Application Support";
} else /* isLinux() or something wacky */ {
root = ".getdown";
}
File appdir = new File(System.getProperty("user.home") + File.separator + root +
File.separator + appname);
// if our application directory does not exist, auto-create it
if (!appdir.exists() || !appdir.isDirectory()) {
if (!appdir.mkdirs()) {
throw new Exception("m.create_appdir_failed");
}
}
// if an installer.txt file is desired, create that
String inststr = getParameter("installer");
if (!StringUtil.isBlank(inststr)) {
File infile = new File(appdir, "installer.txt");
if (!infile.exists()) {
writeToFile(infile, inststr);
}
}
// if our getdown.txt file does not exist, auto-create it
File gdfile = new File(appdir, "getdown.txt");
if (!gdfile.exists()) {
if (StringUtil.isBlank(appbase)) {
throw new Exception("m.missing_appbase");
}
if (!writeToFile(gdfile, "appbase = " + appbase)) {
throw new Exception("m.create_getdown_failed");
}
}
return appdir;
}
/**
* Creates the specified file and writes the supplied contents to it.
*/
protected boolean writeToFile (File tofile, String contents)
{
try {
PrintStream out = new PrintStream(new FileOutputStream(tofile));
out.println(contents);
out.close();
return true;
} catch (IOException ioe) {
Log.warning("Failed to create '" + tofile + "'.");
Log.logStackTrace(ioe);
return false;
}
}
/** Handles all the actual getting down. */
protected Getdown _getdown;
/** A background image drawn to make things look purdy. */
protected Image _bgimage;
/** An error encountered during initialization. */
protected String _errmsg;
}
| false | true | protected File initGetdown (String appbase, String appname, String imgpath)
throws Exception
{
// getdown requires full read/write permissions to the system; if we don't have this, then
// we need to not do anything unsafe, and display a message to the user telling them they
// need to (groan) close out of the web browser entirely and re-launch the browser, go to
// our site, and accept the certificate
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
try {
sm.checkWrite("getdown");
sm.checkPropertiesAccess();
} catch (SecurityException se) {
Log.warning("Signed applet rejected by user [se=" + se + "].");
throw new Exception("m.insufficient_permissions_error");
}
}
Object[] signers = GetdownApplet.class.getSigners();
if (signers.length == 0) {
Log.info("No signers, not verifying param signature.");
} else {
String signature = getParameter("signature");
if (signature == null) {
signature = "";
}
Log.info("Verifying signature '" + signature + "'.");
String params = appbase + appname + imgpath;
int validated = 0;
for (Object signer : signers) {
if (signer instanceof Certificate) {
Certificate cert = (Certificate)signer;
try {
Signature sig = Signature.getInstance("SHA1withRSA");
sig.initVerify(cert);
sig.update(params.getBytes());
if (!sig.verify(Base64.decodeBase64(signature.getBytes()))) {
Log.info("Signature does not match '" + cert.getPublicKey() + "'.");
}
validated++;
} catch (GeneralSecurityException gse) {
// no problem!
}
}
}
// if we couldn't find a key that validates our parameters, we are the hosed!
if (validated == 0) {
throw new Exception("m.corrupt_param_signature_error");
}
}
// pass through properties parameters
String properties = getParameter("properties");
if (properties != null) {
String[] proparray = properties.split(" ");
for (String property : proparray) {
String key = property.substring(property.indexOf("-D") + 2, property.indexOf("="));
String value = property.substring(property.indexOf("=") + 1);
System.setProperty(key, value);
}
}
// when run from an applet, we install to the user's home directory
String root;
if (RunAnywhere.isWindows()) {
root = "Application Data";
} else if (RunAnywhere.isMacOS()) {
root = "Library" + File.separator + "Application Support";
} else /* isLinux() or something wacky */ {
root = ".getdown";
}
File appdir = new File(System.getProperty("user.home") + File.separator + root +
File.separator + appname);
// if our application directory does not exist, auto-create it
if (!appdir.exists() || !appdir.isDirectory()) {
if (!appdir.mkdirs()) {
throw new Exception("m.create_appdir_failed");
}
}
// if an installer.txt file is desired, create that
String inststr = getParameter("installer");
if (!StringUtil.isBlank(inststr)) {
File infile = new File(appdir, "installer.txt");
if (!infile.exists()) {
writeToFile(infile, inststr);
}
}
// if our getdown.txt file does not exist, auto-create it
File gdfile = new File(appdir, "getdown.txt");
if (!gdfile.exists()) {
if (StringUtil.isBlank(appbase)) {
throw new Exception("m.missing_appbase");
}
if (!writeToFile(gdfile, "appbase = " + appbase)) {
throw new Exception("m.create_getdown_failed");
}
}
return appdir;
}
| protected File initGetdown (String appbase, String appname, String imgpath)
throws Exception
{
// getdown requires full read/write permissions to the system; if we don't have this, then
// we need to not do anything unsafe, and display a message to the user telling them they
// need to (groan) close out of the web browser entirely and re-launch the browser, go to
// our site, and accept the certificate
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
try {
sm.checkWrite("getdown");
sm.checkPropertiesAccess();
} catch (SecurityException se) {
Log.warning("Signed applet rejected by user [se=" + se + "].");
throw new Exception("m.insufficient_permissions_error");
}
}
Object[] signers = GetdownApplet.class.getSigners();
if (signers.length == 0) {
Log.info("No signers, not verifying param signature.");
} else {
String signature = getParameter("signature");
if (signature == null) {
signature = "";
}
Log.info("Verifying signature '" + signature + "'.");
String params = appbase + appname + imgpath;
int validated = 0;
for (Object signer : signers) {
if (signer instanceof Certificate) {
Certificate cert = (Certificate)signer;
try {
Signature sig = Signature.getInstance("SHA1withRSA");
sig.initVerify(cert);
sig.update(params.getBytes());
if (!sig.verify(Base64.decodeBase64(signature.getBytes()))) {
Log.info("Signature does not match '" + cert.getPublicKey() + "'.");
}
validated++;
} catch (GeneralSecurityException gse) {
// no problem!
}
}
}
// if we couldn't find a key that validates our parameters, we are the hosed!
if (validated == 0) {
throw new Exception("m.corrupt_param_signature_error");
}
}
// pass through properties parameters
String properties = getParameter("properties");
if (properties != null) {
String[] proparray = properties.split(" ");
for (String property : proparray) {
String key = property.substring(property.indexOf("-D") + 2, property.indexOf("="));
String value = property.substring(property.indexOf("=") + 1);
System.setProperty(key, value);
}
}
// when run from an applet, we install to the user's home directory
String root;
if (RunAnywhere.isWindows()) {
String verStr = System.getProperty("os.version");
root = "Application Data";
try {
float version = Float.parseFloat(verStr);
if (version >= 6.0) {
// Vista makes us write it here.... Yay.
root = "AppData" + File.separator + "LocalLow";
}
} catch (Exception e) {
Log.warning("Couldn't parse OS version: " +verStr);
}
} else if (RunAnywhere.isMacOS()) {
root = "Library" + File.separator + "Application Support";
} else /* isLinux() or something wacky */ {
root = ".getdown";
}
File appdir = new File(System.getProperty("user.home") + File.separator + root +
File.separator + appname);
// if our application directory does not exist, auto-create it
if (!appdir.exists() || !appdir.isDirectory()) {
if (!appdir.mkdirs()) {
throw new Exception("m.create_appdir_failed");
}
}
// if an installer.txt file is desired, create that
String inststr = getParameter("installer");
if (!StringUtil.isBlank(inststr)) {
File infile = new File(appdir, "installer.txt");
if (!infile.exists()) {
writeToFile(infile, inststr);
}
}
// if our getdown.txt file does not exist, auto-create it
File gdfile = new File(appdir, "getdown.txt");
if (!gdfile.exists()) {
if (StringUtil.isBlank(appbase)) {
throw new Exception("m.missing_appbase");
}
if (!writeToFile(gdfile, "appbase = " + appbase)) {
throw new Exception("m.create_getdown_failed");
}
}
return appdir;
}
|
diff --git a/src/com/directsupply/MisspelledSearchTermWordCount/Reduce.java b/src/com/directsupply/MisspelledSearchTermWordCount/Reduce.java
index 78bfb24..ce12585 100644
--- a/src/com/directsupply/MisspelledSearchTermWordCount/Reduce.java
+++ b/src/com/directsupply/MisspelledSearchTermWordCount/Reduce.java
@@ -1,23 +1,23 @@
package com.directsupply.MisspelledSearchTermWordCount;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
import java.io.IOException;
public class Reduce extends Reducer<Text, Text, Text, Text> {
@Override
public void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
int count = 0;
for (Text ignored : values) {
count++;
}
Text reduceOutput = new Text();
- reduceOutput.set(String.format("%s\t%d", key, count));
+ reduceOutput.set(String.format("%d", count));
context.write(key, reduceOutput);
}
}
| true | true | public void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
int count = 0;
for (Text ignored : values) {
count++;
}
Text reduceOutput = new Text();
reduceOutput.set(String.format("%s\t%d", key, count));
context.write(key, reduceOutput);
}
| public void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
int count = 0;
for (Text ignored : values) {
count++;
}
Text reduceOutput = new Text();
reduceOutput.set(String.format("%d", count));
context.write(key, reduceOutput);
}
|
diff --git a/src/rhsm/data/InstalledProduct.java b/src/rhsm/data/InstalledProduct.java
index a8028304..0cc1bfee 100644
--- a/src/rhsm/data/InstalledProduct.java
+++ b/src/rhsm/data/InstalledProduct.java
@@ -1,326 +1,334 @@
package rhsm.data;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import com.redhat.qe.tools.abstraction.AbstractCommandLineData;
/**
* @author jsefler
*
*/
public class InstalledProduct extends AbstractCommandLineData {
protected static String simpleDateFormat = "MM/dd/yyyy"; // 04/24/2011 https://bugzilla.redhat.com/show_bug.cgi?id=695234 https://bugzilla.redhat.com/show_bug.cgi?id=699442
/*
ProductName: Awesome OS for S390 Bits
Version: 3.11
Arch: s390x
Status: Not Subscribed
Starts: 09/19/2011
Expires: 09/20/2011
*/
// abstraction fields
public String productName;
public String productId;
public String version;
public String arch;
public String status;
public Calendar startDate;
public Calendar endDate;
public InstalledProduct(Map<String, String> productData) {
super(productData);
}
public InstalledProduct(String productName, String productId, String version, String arch, String status, Calendar startDate, Calendar endDate) {
super(null);
this.productName = productName;
this.productId = productId;
this.version = version;
this.arch = arch;
this.status = status;
this.startDate = startDate;
this.endDate = endDate;
}
@Override
public String toString() {
String string = "";
if (productName != null) string += String.format(" %s='%s'", "productName",productName);
if (productId != null) string += String.format(" %s='%s'", "productId",productId);
if (version != null) string += String.format(" %s='%s'", "version",version);
if (arch != null) string += String.format(" %s='%s'", "arch",arch);
if (status != null) string += String.format(" %s='%s'", "status",status);
if (startDate != null) string += String.format(" %s='%s'", "startDate",formatDateString(startDate));
if (endDate != null) string += String.format(" %s='%s'", "endDate",formatDateString(endDate));
return string.trim();
}
// DELETEME: The super.equals was fixed which should mean that this Override is not needed anymore.
// @Override
// public boolean equals(Object obj){
// InstalledProduct that = (InstalledProduct) obj;
//
// if (that.productName!=null && !that.productName.equals(this.productName)) return false;
// if (this.productName!=null && !this.productName.equals(that.productName)) return false;
//
// if (that.version!=null && !that.version.equals(this.version)) return false;
// if (this.version!=null && !this.version.equals(that.version)) return false;
//
// if (that.arch!=null && !that.arch.equals(this.arch)) return false;
// if (this.arch!=null && !this.arch.equals(that.arch)) return false;
//
// if (that.status!=null && !that.status.equals(this.status)) return false;
// if (this.status!=null && !this.status.equals(that.status)) return false;
//
// if (that.startDate!=null && !that.startDate.equals(this.startDate)) return false;
// if (this.startDate!=null && !this.startDate.equals(that.startDate)) return false;
//
// if (that.endDate!=null && !that.endDate.equals(this.endDate)) return false;
// if (this.endDate!=null && !this.endDate.equals(that.endDate)) return false;
//
// return true;
// }
@Override
protected Calendar parseDateString(String dateString){
return parseDateString(dateString, simpleDateFormat);
}
//@Override
public static String formatDateString(Calendar date){
DateFormat dateFormat = new SimpleDateFormat(simpleDateFormat);
return dateFormat.format(date.getTime());
}
/**
* @param stdoutListingOfInstalledProducts - stdout from "subscription-manager --list --installed"
* @return
*/
static public List<InstalledProduct> parse(String stdoutListingOfInstalledProducts) {
/* [root@jsefler-onprem-62server ~]# subscription-manager list --installed
+-------------------------------------------+
Installed Product Status
+-------------------------------------------+
ProductName: Awesome OS Developer Basic
Version: 1.0
Arch: ALL
Status: Not Subscribed
Starts: 09/19/2011
Expires: 09/20/2011
ProductName: Awesome OS for x86_64/i686/ia64/ppc/ppc64/s390x/s390 Bits
Version: 3.11
Arch: x86_64,i686,ia64,ppc,ppc64,s390x,s390
Status: Not Subscribed
Starts: 09/19/2011
Expires: 09/20/2011
Product Name: Red Hat Enterprise Linux Server
Product ID: 69
Version: 6.3
Arch: x86_64
Status: Not Subscribed
Starts:
Expires:
Product Name: Awesome OS Workstation Bits
Product ID: 27060
Version: 6.1
Arch: ALL
Status: Subscribed
Starts: 04/30/2012
Expires: 04/30/2013
Product Name: Load Balancing Bits
Product ID: 37070
Version: 1.0
Arch: ALL
Status: Subscribed
Starts: 06/26/2012
Ends: 06/26/2013
*/
Map<String,String> regexes = new HashMap<String,String>();
// abstraction field regex pattern (with a capturing group) Note: the captured group will be trim()ed
- regexes.put("productName", "^Product Name:(.*)");
+ regexes.put("productName", "^Product Name:(.*(\\n.*?)+)^\\w+\\s?\\w+:"); // changed by bug 864177 to have a multi-line value; this regex assumes that productName is NOT last in its subscription grouping since ^\w+\s?\w+: represents the start of the next property so as to capture a multi-line value // was a single line of data "^Product Name:(.*)");
regexes.put("productId", "^Product ID:(.*)");
regexes.put("version", "^Version:(.*)");
regexes.put("arch", "^Arch:(.*)");
regexes.put("status", "^Status:(.*)");
regexes.put("startDate", "^Starts:(.*)"); // Bug 812373 - Terminology Change to Subscription-Manager list --installed & --consumed
regexes.put("endDate", "^Ends:(.*)"); // Bug 812373 - Terminology Change to Subscription-Manager list --installed & --consumed
List<Map<String,String>> productCertList = new ArrayList<Map<String,String>>();
for(String field : regexes.keySet()){
Pattern pat = Pattern.compile(regexes.get(field), Pattern.MULTILINE);
addRegexMatchesToList(pat, stdoutListingOfInstalledProducts, productCertList, field);
}
List<InstalledProduct> productCerts = new ArrayList<InstalledProduct>();
- for(Map<String,String> prodCertMap : productCertList)
+ for(Map<String,String> prodCertMap : productCertList) {
+ // normalize newlines from productName when it spans multiple lines (introduced by bug 864177)
+ String key = "productName", productName = prodCertMap.get(key);
+ if (productName!=null) {
+ prodCertMap.remove(key);
+ productName = productName.replaceAll("\\s*\\n\\s*", " ");
+ prodCertMap.put(key, productName);
+ }
productCerts.add(new InstalledProduct(prodCertMap));
+ }
return productCerts;
}
}
// DELETEME 9/20/2011 PRE-IMPLEMENTATION OF Bug 736424 - CLI function "subscription-manager list --installed" reports TOO much information
//public class InstalledProduct extends AbstractCommandLineData {
// protected static String simpleDateFormat = "MM/dd/yyyy"; // 04/24/2011 https://bugzilla.redhat.com/show_bug.cgi?id=695234 https://bugzilla.redhat.com/show_bug.cgi?id=699442
//
// // abstraction fields
// public String productName;
// public String status;
// public Calendar expires;
// public BigInteger serialNumber; // subscription; // name changed by bug https://bugzilla.redhat.com/show_bug.cgi?id=712415
// public Long contractNumber;
// public BigInteger accountNumber;
//
// public InstalledProduct(Map<String, String> productData) {
// super(productData);
// }
//
// public InstalledProduct(String productName, String status, Calendar expires, BigInteger serialNumber, Long contractNumber, BigInteger accountNumber) {
// super(null);
// this.productName = productName;
// this.status = status;
// this.expires = expires;
// this.serialNumber = serialNumber;
// this.contractNumber = contractNumber;
// this.accountNumber = accountNumber;
// }
//
// @Override
// public String toString() {
//
// String string = "";
// if (productName != null) string += String.format(" %s='%s'", "productName",productName);
// if (status != null) string += String.format(" %s='%s'", "status",status);
// if (expires != null) string += String.format(" %s='%s'", "expires",formatDateString(expires));
// if (serialNumber != null) string += String.format(" %s='%s'", "serialNumber",serialNumber);
// if (contractNumber != null) string += String.format(" %s='%s'", "contractNumber",contractNumber);
// if (accountNumber != null) string += String.format(" %s='%s'", "accountNumber",accountNumber);
//
// return string.trim();
// }
//
// @Override
// public boolean equals(Object obj){
// InstalledProduct that = (InstalledProduct) obj;
//
// if (that.productName!=null && !that.productName.equals(this.productName)) return false;
// if (this.productName!=null && !this.productName.equals(that.productName)) return false;
//
// if (that.status!=null && !that.status.equals(this.status)) return false;
// if (this.status!=null && !this.status.equals(that.status)) return false;
//
// if (that.expires!=null && !that.expires.equals(this.expires)) return false;
// if (this.expires!=null && !this.expires.equals(that.expires)) return false;
//
// if (that.serialNumber!=null && !that.serialNumber.equals(this.serialNumber)) return false;
// if (this.serialNumber!=null && !this.serialNumber.equals(that.serialNumber)) return false;
//
// if (that.contractNumber!=null && !that.contractNumber.equals(this.contractNumber)) return false;
// if (this.contractNumber!=null && !this.contractNumber.equals(that.contractNumber)) return false;
//
// if (that.accountNumber!=null && !that.accountNumber.equals(this.accountNumber)) return false;
// if (this.accountNumber!=null && !this.accountNumber.equals(that.accountNumber)) return false;
//
// if (that.productName!=null && !that.productName.equals(this.productName)) return false;
// if (this.productName!=null && !this.productName.equals(that.productName)) return false;
//
// if (that.productName!=null && !that.productName.equals(this.productName)) return false;
// if (this.productName!=null && !this.productName.equals(that.productName)) return false;
//
// return true;
// }
//
// @Override
// protected Calendar parseDateString(String dateString){
// return parseDateString(dateString, simpleDateFormat);
// }
//
// //@Override
// public static String formatDateString(Calendar date){
// DateFormat dateFormat = new SimpleDateFormat(simpleDateFormat);
// return dateFormat.format(date.getTime());
// }
//
// /**
// * @param stdoutListingOfProductCerts - stdout from "subscription-manager-cli list"
// * @return
// */
// static public List<InstalledProduct> parse(String stdoutListingOfProductCerts) {
// /*
// # subscription-manager-cli list
// +-------------------------------------------+
// Installed Product Status
// +-------------------------------------------+
//
// ProductName: Shared Storage (GFS)
// Status: Not Installed
// Expires: 2011-07-01
// Subscription: 17
// ContractNumber: 0
//
// ProductName: Red Hat Enterprise Linux High Availability (for RHEL 6 Entitlement)
// Status: Not Subscribed
// Expires:
// Subscription:
// ContractNumber:
//
// ProductName: Red Hat Enterprise Linux 6 Entitlement Alpha
// Status: Subscribed
// Expires: 2011-01-24
// Subscription: 1151289234191548136
// ContractNumber: 1970595
//
//
// ProductName: Awesome OS Scalable Filesystem Bits
// Status: Subscribed
// Expires: 07/17/2012
// SerialNumber: 5945536885441836861
// ContractNumber: 2
// AccountNumber: 12331131231
// */
//
// Map<String,String> regexes = new HashMap<String,String>();
//
// // abstraction field regex pattern (with a capturing group) Note: the captured group will be trim()ed
// regexes.put("productName", "^ProductName:(.*)");
// regexes.put("status", "^Status:(.*)");
// regexes.put("expires", "^Expires:(.*)");
// regexes.put("serialNumber", "^SerialNumber:(.*)");
// regexes.put("contractNumber", "^ContractNumber:(.*)");
// regexes.put("accountNumber", "^AccountNumber:(.*)");
//
// List<Map<String,String>> productCertList = new ArrayList<Map<String,String>>();
// for(String field : regexes.keySet()){
// Pattern pat = Pattern.compile(regexes.get(field), Pattern.MULTILINE);
// addRegexMatchesToList(pat, stdoutListingOfProductCerts, productCertList, field);
// }
//
// List<InstalledProduct> productCerts = new ArrayList<InstalledProduct>();
// for(Map<String,String> prodCertMap : productCertList)
// productCerts.add(new InstalledProduct(prodCertMap));
// return productCerts;
// }
//}
| false | true | static public List<InstalledProduct> parse(String stdoutListingOfInstalledProducts) {
/* [root@jsefler-onprem-62server ~]# subscription-manager list --installed
+-------------------------------------------+
Installed Product Status
+-------------------------------------------+
ProductName: Awesome OS Developer Basic
Version: 1.0
Arch: ALL
Status: Not Subscribed
Starts: 09/19/2011
Expires: 09/20/2011
ProductName: Awesome OS for x86_64/i686/ia64/ppc/ppc64/s390x/s390 Bits
Version: 3.11
Arch: x86_64,i686,ia64,ppc,ppc64,s390x,s390
Status: Not Subscribed
Starts: 09/19/2011
Expires: 09/20/2011
Product Name: Red Hat Enterprise Linux Server
Product ID: 69
Version: 6.3
Arch: x86_64
Status: Not Subscribed
Starts:
Expires:
Product Name: Awesome OS Workstation Bits
Product ID: 27060
Version: 6.1
Arch: ALL
Status: Subscribed
Starts: 04/30/2012
Expires: 04/30/2013
Product Name: Load Balancing Bits
Product ID: 37070
Version: 1.0
Arch: ALL
Status: Subscribed
Starts: 06/26/2012
Ends: 06/26/2013
*/
Map<String,String> regexes = new HashMap<String,String>();
// abstraction field regex pattern (with a capturing group) Note: the captured group will be trim()ed
regexes.put("productName", "^Product Name:(.*)");
regexes.put("productId", "^Product ID:(.*)");
regexes.put("version", "^Version:(.*)");
regexes.put("arch", "^Arch:(.*)");
regexes.put("status", "^Status:(.*)");
regexes.put("startDate", "^Starts:(.*)"); // Bug 812373 - Terminology Change to Subscription-Manager list --installed & --consumed
regexes.put("endDate", "^Ends:(.*)"); // Bug 812373 - Terminology Change to Subscription-Manager list --installed & --consumed
List<Map<String,String>> productCertList = new ArrayList<Map<String,String>>();
for(String field : regexes.keySet()){
Pattern pat = Pattern.compile(regexes.get(field), Pattern.MULTILINE);
addRegexMatchesToList(pat, stdoutListingOfInstalledProducts, productCertList, field);
}
List<InstalledProduct> productCerts = new ArrayList<InstalledProduct>();
for(Map<String,String> prodCertMap : productCertList)
productCerts.add(new InstalledProduct(prodCertMap));
return productCerts;
}
| static public List<InstalledProduct> parse(String stdoutListingOfInstalledProducts) {
/* [root@jsefler-onprem-62server ~]# subscription-manager list --installed
+-------------------------------------------+
Installed Product Status
+-------------------------------------------+
ProductName: Awesome OS Developer Basic
Version: 1.0
Arch: ALL
Status: Not Subscribed
Starts: 09/19/2011
Expires: 09/20/2011
ProductName: Awesome OS for x86_64/i686/ia64/ppc/ppc64/s390x/s390 Bits
Version: 3.11
Arch: x86_64,i686,ia64,ppc,ppc64,s390x,s390
Status: Not Subscribed
Starts: 09/19/2011
Expires: 09/20/2011
Product Name: Red Hat Enterprise Linux Server
Product ID: 69
Version: 6.3
Arch: x86_64
Status: Not Subscribed
Starts:
Expires:
Product Name: Awesome OS Workstation Bits
Product ID: 27060
Version: 6.1
Arch: ALL
Status: Subscribed
Starts: 04/30/2012
Expires: 04/30/2013
Product Name: Load Balancing Bits
Product ID: 37070
Version: 1.0
Arch: ALL
Status: Subscribed
Starts: 06/26/2012
Ends: 06/26/2013
*/
Map<String,String> regexes = new HashMap<String,String>();
// abstraction field regex pattern (with a capturing group) Note: the captured group will be trim()ed
regexes.put("productName", "^Product Name:(.*(\\n.*?)+)^\\w+\\s?\\w+:"); // changed by bug 864177 to have a multi-line value; this regex assumes that productName is NOT last in its subscription grouping since ^\w+\s?\w+: represents the start of the next property so as to capture a multi-line value // was a single line of data "^Product Name:(.*)");
regexes.put("productId", "^Product ID:(.*)");
regexes.put("version", "^Version:(.*)");
regexes.put("arch", "^Arch:(.*)");
regexes.put("status", "^Status:(.*)");
regexes.put("startDate", "^Starts:(.*)"); // Bug 812373 - Terminology Change to Subscription-Manager list --installed & --consumed
regexes.put("endDate", "^Ends:(.*)"); // Bug 812373 - Terminology Change to Subscription-Manager list --installed & --consumed
List<Map<String,String>> productCertList = new ArrayList<Map<String,String>>();
for(String field : regexes.keySet()){
Pattern pat = Pattern.compile(regexes.get(field), Pattern.MULTILINE);
addRegexMatchesToList(pat, stdoutListingOfInstalledProducts, productCertList, field);
}
List<InstalledProduct> productCerts = new ArrayList<InstalledProduct>();
for(Map<String,String> prodCertMap : productCertList) {
// normalize newlines from productName when it spans multiple lines (introduced by bug 864177)
String key = "productName", productName = prodCertMap.get(key);
if (productName!=null) {
prodCertMap.remove(key);
productName = productName.replaceAll("\\s*\\n\\s*", " ");
prodCertMap.put(key, productName);
}
productCerts.add(new InstalledProduct(prodCertMap));
}
return productCerts;
}
|
diff --git a/org.eclipse.help.ui/src/org/eclipse/help/ui/internal/views/SearchPart.java b/org.eclipse.help.ui/src/org/eclipse/help/ui/internal/views/SearchPart.java
index 1c26f5a30..ca6722e51 100644
--- a/org.eclipse.help.ui/src/org/eclipse/help/ui/internal/views/SearchPart.java
+++ b/org.eclipse.help.ui/src/org/eclipse/help/ui/internal/views/SearchPart.java
@@ -1,737 +1,737 @@
/*******************************************************************************
* Copyright (c) 2000, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.help.ui.internal.views;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.jobs.IJobChangeEvent;
import org.eclipse.core.runtime.jobs.IJobChangeListener;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.help.HelpSystem;
import org.eclipse.help.internal.base.BaseHelpSystem;
import org.eclipse.help.internal.search.federated.FederatedSearchEntry;
import org.eclipse.help.internal.search.federated.FederatedSearchJob;
import org.eclipse.help.search.ISearchEngineResult;
import org.eclipse.help.search.ISearchEngineResultCollector;
import org.eclipse.help.search.ISearchScope;
import org.eclipse.help.ui.internal.HelpUIResources;
import org.eclipse.help.ui.internal.IHelpUIConstants;
import org.eclipse.help.ui.internal.Messages;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.preference.PreferenceDialog;
import org.eclipse.jface.preference.PreferenceManager;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.actions.ActionFactory;
import org.eclipse.ui.forms.AbstractFormPart;
import org.eclipse.ui.forms.IFormColors;
import org.eclipse.ui.forms.events.HyperlinkAdapter;
import org.eclipse.ui.forms.events.HyperlinkEvent;
import org.eclipse.ui.forms.widgets.FormText;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.Hyperlink;
import org.eclipse.ui.forms.widgets.Section;
import org.eclipse.ui.forms.widgets.TableWrapData;
import org.eclipse.ui.forms.widgets.TableWrapLayout;
public class SearchPart extends AbstractFormPart implements IHelpPart, IHelpUIConstants {
private ReusableHelpPart parent;
protected static java.util.List previousSearchQueryData = new java.util.ArrayList(20);
private static final String HREF_TOGGLE = "__toggle__"; //$NON-NLS-1$
private static final String HREF_SEARCH_HELP = "/org.eclipse.platform.doc.user/tasks/tsearch.htm"; //$NON-NLS-1$
private static boolean SEARCH_HELP_AVAILABLE = false;
static {
InputStream is = HelpSystem.getHelpContent(HREF_SEARCH_HELP);
if (is != null) {
// don't leak the input stream
try {
is.close();
SEARCH_HELP_AVAILABLE = true;
} catch (IOException e) {
// ignore
}
}
}
private String id;
private Composite container;
private Composite filteringGroup;
private FormText searchWordText;
private Chevron searchWordChevron;
private ComboPart searchWordCombo;
private Section scopeSection;
private Button goButton;
private Button shellDefaultButton;
private Hyperlink scopeSetLink;
private Hyperlink advancedLink;
private Observer engineObserver;
private ScopeSetManager scopeSetManager;
private static final int COMBO_HISTORY_SIZE = 10;
private JobListener jobListener;
private boolean searchPending;
private class JobListener implements IJobChangeListener, Runnable {
private boolean searchInProgress = false;
public void aboutToRun(IJobChangeEvent event) {
}
public void awake(IJobChangeEvent event) {
}
public void done(IJobChangeEvent event) {
if (event.getJob().belongsTo(FederatedSearchJob.FAMILY)) {
Job[] searchJobs = Job.getJobManager().find(FederatedSearchJob.FAMILY);
if (searchJobs.length == 0) {
// search finished
searchInProgress = false;
if (container.isDisposed())
return;
container.getDisplay().asyncExec(this);
SearchResultsPart results = (SearchResultsPart) parent
.findPart(IHelpUIConstants.HV_FSEARCH_RESULT);
results.completed();
}
}
}
public void running(IJobChangeEvent event) {
}
public void scheduled(IJobChangeEvent event) {
if (!searchInProgress && event.getJob().belongsTo(FederatedSearchJob.FAMILY)) {
searchInProgress = true;
container.getDisplay().asyncExec(this);
}
}
public void sleeping(IJobChangeEvent event) {
}
public void run() {
searchWordCombo.getControl().setEnabled(!searchInProgress);
if (!searchInProgress)
goButton.setEnabled(true);
if (searchInProgress)
goButton.setText(Messages.SearchPart_stop);
else
goButton.setText(Messages.SearchPart_go);
parent.getForm().getForm().setBusy(searchInProgress);
goButton.getParent().layout();
}
}
/**
* @param parent
* @param toolkit
* @param style
*/
public SearchPart(final Composite parent, FormToolkit toolkit) {
container = toolkit.createComposite(parent);
scopeSetManager = new ScopeSetManager();
TableWrapLayout layout = new TableWrapLayout();
layout.numColumns = 2;
container.setLayout(layout);
// Search Expression
searchWordText = toolkit.createFormText(container, false);
searchWordChevron = new Chevron(searchWordText, SWT.NULL);
toolkit.adapt(searchWordChevron, true, true);
searchWordChevron.setHoverDecorationColor(toolkit.getHyperlinkGroup().getActiveForeground());
searchWordChevron.setDecorationColor(toolkit.getColors().getColor(IFormColors.TB_TOGGLE));
searchWordText.setControl(HREF_TOGGLE, searchWordChevron);
searchWordText.addHyperlinkListener(new HyperlinkAdapter() {
public void linkActivated(HyperlinkEvent e) {
SearchPart.this.parent.showURL(HREF_SEARCH_HELP, true);
}
});
searchWordChevron.addHyperlinkListener(new HyperlinkAdapter() {
public void linkActivated(HyperlinkEvent e) {
parent.getDisplay().asyncExec(new Runnable() {
public void run() {
toggleSearchWordText();
}
});
}
});
searchWordText.setImage(IHelpUIConstants.IMAGE_HELP, HelpUIResources
.getImage(IHelpUIConstants.IMAGE_HELP));
updateSearchWordText();
TableWrapData td = new TableWrapData();
td.colspan = 2;
searchWordText.setLayoutData(td);
// Pattern combo
searchWordCombo = new ComboPart(container, toolkit, toolkit.getBorderStyle());
updateSearchCombo(null);
td = new TableWrapData(TableWrapData.FILL_GRAB);
td.maxWidth = 100;
td.valign = TableWrapData.MIDDLE;
searchWordCombo.getControl().setLayoutData(td);
searchWordCombo.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
if (searchWordCombo.getSelectionIndex() < 0)
return;
searchFromHistory(searchWordCombo.getSelectionIndex());
}
});
goButton = toolkit.createButton(container, Messages.SearchPart_go, SWT.PUSH);
goButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
handleButtonPressed();
}
});
goButton.setEnabled(false);
searchWordCombo.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
goButton.setEnabled(searchWordCombo.getText().length() > 0);
}
});
searchWordCombo.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.character == '\r') {
- if (goButton.isEnabled())
+ if (goButton.isEnabled() && searchWordCombo.getSelectionIndex() < 0)
doSearch(searchWordCombo.getText());
}
}
});
searchWordCombo.getControl().addListener(SWT.FocusIn, new Listener() {
public void handleEvent(Event event) {
shellDefaultButton = null;
Shell shell = searchWordCombo.getControl().getShell();
Button button = shell.getDefaultButton();
if (button != null) {
shellDefaultButton = button;
shell.setDefaultButton(goButton);
}
}
});
searchWordCombo.getControl().addListener(SWT.FocusOut, new Listener() {
public void handleEvent(Event event) {
if (shellDefaultButton != null) {
Shell shell = searchWordCombo.getControl().getShell();
shell.setDefaultButton(shellDefaultButton);
shellDefaultButton = null;
}
}
});
scopeSection = toolkit.createSection(container, Section.TWISTIE | Section.COMPACT
| Section.LEFT_TEXT_CLIENT_ALIGNMENT);
scopeSection.setText(Messages.limit_to);
td = new TableWrapData();
td.colspan = 2;
td.align = TableWrapData.FILL;
scopeSection.setLayoutData(td);
filteringGroup = toolkit.createComposite(scopeSection);
scopeSection.setClient(filteringGroup);
TableWrapLayout flayout = new TableWrapLayout();
flayout.numColumns = 2;
filteringGroup.setLayout(flayout);
createScopeSet(scopeSection, toolkit);
toolkit.paintBordersFor(filteringGroup);
toolkit.paintBordersFor(container);
jobListener = new JobListener();
Job.getJobManager().addJobChangeListener(jobListener);
}
private void createAdvancedLink(Composite parent, FormToolkit toolkit) {
advancedLink = toolkit.createHyperlink(parent, Messages.FederatedSearchPart_advanced, SWT.NULL);
advancedLink.addHyperlinkListener(new HyperlinkAdapter() {
public void linkActivated(HyperlinkEvent e) {
doAdvanced();
}
});
TableWrapData td = new TableWrapData();
td.colspan = 2;
advancedLink.setLayoutData(td);
}
private void createScopeSet(Section section, FormToolkit toolkit) {
scopeSetLink = toolkit.createHyperlink(section, null, SWT.WRAP);
scopeSetLink.addHyperlinkListener(new HyperlinkAdapter() {
public void linkActivated(HyperlinkEvent e) {
doChangeScopeSet();
}
});
scopeSetLink.setToolTipText(Messages.FederatedSearchPart_changeScopeSet);
section.setTextClient(scopeSetLink);
ScopeSet active = scopeSetManager.getActiveSet();
setActiveScopeSet(active);
}
private void toggleSearchWordText() {
updateSearchWordText();
SearchPart.this.parent.reflow();
}
private void updateSearchWordText() {
StringBuffer buff = new StringBuffer();
buff.append("<form>"); //$NON-NLS-1$
buff.append("<p>"); //$NON-NLS-1$
buff.append(Messages.expression);
if (searchWordChevron.isExpanded()) {
searchWordChevron.setToolTipText(Messages.SearchPart_collapse);
buff.append("<control href=\""); //$NON-NLS-1$
buff.append(HREF_TOGGLE);
buff.append("\"/>"); //$NON-NLS-1$
buff.append("</p><p>"); //$NON-NLS-1$
buff.append(Messages.expression_label);
// Only add the link if available
if (SEARCH_HELP_AVAILABLE) {
buff.append("</p><p>"); //$NON-NLS-1$
buff.append("<img href=\""); //$NON-NLS-1$
buff.append(IHelpUIConstants.IMAGE_HELP);
buff.append("\"/> "); //$NON-NLS-1$
buff.append("<a href=\""); //$NON-NLS-1$
buff.append(HREF_SEARCH_HELP);
buff.append("\">"); //$NON-NLS-1$
buff.append(Messages.SearchPart_learnMore);
buff.append("</a>"); //$NON-NLS-1$
}
} else {
searchWordChevron.setToolTipText(Messages.SearchPart_expand);
buff.append("<control href=\""); //$NON-NLS-1$
buff.append(HREF_TOGGLE);
buff.append("\"/>"); //$NON-NLS-1$
}
buff.append("</p>"); //$NON-NLS-1$
buff.append("</form>"); //$NON-NLS-1$
searchWordText.setText(buff.toString(), true, false);
}
private void setActiveScopeSet(ScopeSet set) {
scopeSetLink.setText(set.getName());
scopeSetManager.setActiveSet(set);
updateMasters(set);
scopeSection.layout();
if (parent != null)
parent.reflow();
}
private void updateMasters(ScopeSet set) {
Control[] children = ((Composite) scopeSection.getClient()).getChildren();
for (int i = 0; i < children.length; i++) {
Control child = children[i];
if (child instanceof Button) {
Button master = (Button) child;
Object data = master.getData();
if (data != null && data instanceof EngineDescriptor) {
EngineDescriptor ed = (EngineDescriptor) data;
master.setSelection(set.getEngineEnabled(ed));
}
}
}
}
private void loadEngines(final Composite container, final FormToolkit toolkit) {
EngineDescriptorManager descManager = parent.getEngineManager();
EngineDescriptor[] descriptors = descManager.getDescriptors();
for (int i = 0; i < descriptors.length; i++) {
EngineDescriptor desc = descriptors[i];
loadEngine(desc, container, toolkit);
}
engineObserver = new Observer() {
public void update(Observable o, Object arg) {
EngineDescriptorManager.DescriptorEvent event = (EngineDescriptorManager.DescriptorEvent) arg;
int kind = event.getKind();
EngineDescriptor desc = event.getDescriptor();
if (kind == IHelpUIConstants.ADD) {
advancedLink.dispose();
loadEngine(desc, container, toolkit);
createAdvancedLink(container, toolkit);
parent.reflow();
} else if (kind == IHelpUIConstants.REMOVE) {
removeEngine(desc);
} else {
updateEngine(desc);
}
}
};
descManager.addObserver(engineObserver);
updateMasters(scopeSetManager.getActiveSet());
}
private EngineDescriptor loadEngine(final EngineDescriptor edesc, Composite container, FormToolkit toolkit) {
Label ilabel = toolkit.createLabel(container, null);
ilabel.setImage(edesc.getIconImage());
ilabel.setData(edesc);
final Button master = toolkit.createButton(container, edesc.getLabel(), SWT.CHECK);
master.setData(edesc);
master.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
scopeSetManager.getActiveSet().setEngineEnabled(edesc, master.getSelection());
}
});
String desc = edesc.getDescription();
if (desc != null) {
Label spacer = toolkit.createLabel(container, null);
spacer.setData(edesc);
Label dlabel = toolkit.createLabel(container, desc, SWT.WRAP);
dlabel.setForeground(toolkit.getColors().getColor(IFormColors.TITLE));
dlabel.setLayoutData(new TableWrapData(TableWrapData.FILL_GRAB));
dlabel.setMenu(container.getMenu());
dlabel.setData(edesc);
}
return edesc;
}
private void removeEngine(EngineDescriptor desc) {
boolean reflowNeeded = false;
Control[] children = ((Composite) scopeSection.getClient()).getChildren();
for (int i = 0; i < children.length; i++) {
Control child = children[i];
EngineDescriptor ed = (EngineDescriptor) child.getData();
if (ed == desc) {
child.setMenu(null);
child.dispose();
reflowNeeded = true;
}
}
if (reflowNeeded)
parent.reflow();
}
private void updateEngine(EngineDescriptor desc) {
Control[] children = ((Composite) scopeSection.getClient()).getChildren();
boolean reflowNeeded = false;
for (int i = 0; i < children.length; i++) {
Control child = children[i];
EngineDescriptor ed = (EngineDescriptor) child.getData();
if (ed == desc) {
Button b = (Button) children[i + 1];
b.setText(desc.getLabel());
Label d = (Label) children[i + 3];
d.setText(desc.getDescription());
d.getParent().layout();
reflowNeeded = true;
break;
}
}
if (reflowNeeded)
parent.reflow();
}
public void startSearch(String text) {
searchWordCombo.setText(text);
doSearch(text);
}
private void storeSearchHistory(String expression) {
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=95479
HistoryScopeSet sset = scopeSetManager.findSearchSet(expression);
if (sset == null) {
sset = new HistoryScopeSet(expression);
scopeSetManager.add(sset);
}
ScopeSet activeSet = scopeSetManager.getActiveSet();
sset.copyFrom(activeSet);
sset.save();
updateSearchCombo(sset);
searchWordCombo.setText(expression);
}
private void updateSearchCombo(HistoryScopeSet current) {
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=95479
ScopeSet[] sets = scopeSetManager.getScopeSets(true);
ArrayList items = new ArrayList();
ArrayList toDelete = new ArrayList();
// if (current!=null)
// items.add(current.getExpression());
for (int i = sets.length - 1; i >= 0; i--) {
HistoryScopeSet sset = (HistoryScopeSet) sets[i];
if (current != null && sset == current)
continue;
if (sets.length - i > COMBO_HISTORY_SIZE)
toDelete.add(sset);
items.add(sset.getExpression());
}
for (int i = 0; i < toDelete.size(); i++) {
HistoryScopeSet sset = (HistoryScopeSet) toDelete.get(i);
scopeSetManager.remove(sset);
}
if (items.size() > 0)
searchWordCombo.setItems((String[]) items.toArray(new String[items.size()]));
}
private void searchFromHistory(int index) {
String expression = searchWordCombo.getSelection();
ScopeSet set = scopeSetManager.findSearchSet(expression);
if (set == null)
return;
setActiveScopeSet(set);
doSearch(expression, true);
}
private void handleButtonPressed() {
if (searchWordCombo.getControl().isEnabled())
doSearch(searchWordCombo.getText());
else {
goButton.setEnabled(false);
stop();
}
}
private void doSearch(String text) {
doSearch(text, false);
}
private void doSearch(String text, boolean fromHistory) {
ScopeSet set = scopeSetManager.getActiveSet();
if (!fromHistory && set instanceof HistoryScopeSet) {
String setExpression = ((HistoryScopeSet) set).getExpression();
if (setExpression.equals(text))
fromHistory = true;
}
if (!fromHistory) {
storeSearchHistory(text);
boolean switchedSet = scopeSetManager.restoreLastExplicitSet();
set = scopeSetManager.getActiveSet();
if (switchedSet)
setActiveScopeSet(set);
}
ArrayList entries = new ArrayList();
final SearchResultsPart results = (SearchResultsPart) parent
.findPart(IHelpUIConstants.HV_FSEARCH_RESULT);
ArrayList eds = new ArrayList();
EngineDescriptor[] engineDescriptors = parent.getEngineManager().getDescriptors();
for (int i = 0; i < engineDescriptors.length; i++) {
final EngineDescriptor ed = engineDescriptors[i];
if (set.getEngineEnabled(ed) && ed.getEngine() != null) {
ISearchScope scope = ed.createSearchScope(set.getPreferenceStore());
FederatedSearchEntry entry = new FederatedSearchEntry(ed.getId(), ed.getLabel(), scope, ed
.getEngine(), new ISearchEngineResultCollector() {
public void accept(ISearchEngineResult searchResult) {
results.add(ed, searchResult);
}
public void accept(ISearchEngineResult[] searchResults) {
results.add(ed, searchResults);
}
public void error(IStatus status) {
results.error(ed, status);
}
});
entries.add(entry);
eds.add(ed);
}
}
if (entries.size() == 0)
return;
FederatedSearchEntry[] array = (FederatedSearchEntry[]) entries
.toArray(new FederatedSearchEntry[entries.size()]);
if (scopeSection.isExpanded()) {
scopeSection.setExpanded(false);
parent.reflow();
}
results.clearResults();
results.startNewSearch(text, eds);
BaseHelpSystem.getSearchManager().search(text, array);
}
private void doAdvanced() {
ScopeSet set = scopeSetManager.getActiveSet();
PreferenceManager manager = new ScopePreferenceManager(parent.getEngineManager(), set);
PreferenceDialog dialog = new ScopePreferenceDialog(container.getShell(), manager, parent
.getEngineManager(), set.isEditable());
dialog.setPreferenceStore(set.getPreferenceStore());
dialog.create();
dialog.getShell().setText(NLS.bind(Messages.ScopePreferenceDialog_wtitle, set.getName()));
dialog.open();
updateMasters(set);
}
private void doChangeScopeSet() {
ScopeSetDialog dialog = new ScopeSetDialog(container.getShell(), scopeSetManager, parent
.getEngineManager());
dialog.setInput(scopeSetManager);
dialog.create();
dialog.getShell().setText(Messages.ScopeSetDialog_wtitle);
if (dialog.open() == ScopeSetDialog.OK) {
ScopeSet set = dialog.getActiveSet();
if (set != null)
setActiveScopeSet(set);
}
}
public void dispose() {
ScopeSet activeSet = scopeSetManager.getActiveSet();
if (activeSet != null)
activeSet.save();
if (engineObserver != null) {
parent.getEngineManager().deleteObserver(engineObserver);
engineObserver = null;
}
Job.getJobManager().removeJobChangeListener(jobListener);
stop();
super.dispose();
}
/*
* (non-Javadoc)
*
* @see org.eclipse.help.ui.internal.views.IHelpPart#getControl()
*/
public Control getControl() {
return container;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.help.ui.internal.views.IHelpPart#init(org.eclipse.help.ui.internal.views.NewReusableHelpPart)
*/
public void init(ReusableHelpPart parent, String id, IMemento memento) {
this.parent = parent;
this.id = id;
loadEngines(filteringGroup, parent.getForm().getToolkit());
createAdvancedLink(filteringGroup, parent.getForm().getToolkit());
parent.hookFormText(searchWordText);
if (memento != null)
restorePart(memento);
}
private void restorePart(IMemento memento) {
String setName = memento.getString("activeSet"); //$NON-NLS-1$
if (setName != null) {
ScopeSet sset = scopeSetManager.findSet(setName);
if (sset != null)
scopeSetManager.setActiveSet(sset);
}
String expression = memento.getString("expression"); //$NON-NLS-1$
if (expression != null && expression.length() > 0) {
searchWordCombo.setText(expression);
searchPending = true;
markStale();
}
}
public void refresh() {
super.refresh();
if (searchPending) {
searchPending = false;
doSearch(searchWordCombo.getText());
}
}
public String getId() {
return id;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.help.ui.internal.views.IHelpPart#setVisible(boolean)
*/
public void setVisible(boolean visible) {
getControl().setVisible(visible);
}
/*
* (non-Javadoc)
*
* @see org.eclipse.help.ui.internal.views.IHelpPart#fillContextMenu(org.eclipse.jface.action.IMenuManager)
*/
public boolean fillContextMenu(IMenuManager manager) {
return parent.fillFormContextMenu(searchWordText, manager);
}
/*
* (non-Javadoc)
*
* @see org.eclipse.help.ui.internal.views.IHelpPart#hasFocusControl(org.eclipse.swt.widgets.Control)
*/
public boolean hasFocusControl(Control control) {
return control == searchWordText || control == searchWordCombo.getControl()
|| scopeSection.getClient() == control;
}
public void setFocus() {
searchWordCombo.getControl().setFocus();
}
public IAction getGlobalAction(String id) {
if (id.equals(ActionFactory.COPY.getId()))
return parent.getCopyAction();
return null;
}
public void stop() {
SearchResultsPart results = (SearchResultsPart) parent.findPart(IHelpUIConstants.HV_FSEARCH_RESULT);
results.canceling();
Job.getJobManager().cancel(FederatedSearchJob.FAMILY);
}
public void toggleRoleFilter() {
}
public void refilter() {
}
public void saveState(IMemento memento) {
ScopeSet sset = scopeSetManager.getActiveSet();
if (sset != null)
memento.putString("activeSet", sset.getName()); //$NON-NLS-1$
memento.putString("expression", searchWordCombo.getText()); //$NON-NLS-1$
}
}
| true | true | public SearchPart(final Composite parent, FormToolkit toolkit) {
container = toolkit.createComposite(parent);
scopeSetManager = new ScopeSetManager();
TableWrapLayout layout = new TableWrapLayout();
layout.numColumns = 2;
container.setLayout(layout);
// Search Expression
searchWordText = toolkit.createFormText(container, false);
searchWordChevron = new Chevron(searchWordText, SWT.NULL);
toolkit.adapt(searchWordChevron, true, true);
searchWordChevron.setHoverDecorationColor(toolkit.getHyperlinkGroup().getActiveForeground());
searchWordChevron.setDecorationColor(toolkit.getColors().getColor(IFormColors.TB_TOGGLE));
searchWordText.setControl(HREF_TOGGLE, searchWordChevron);
searchWordText.addHyperlinkListener(new HyperlinkAdapter() {
public void linkActivated(HyperlinkEvent e) {
SearchPart.this.parent.showURL(HREF_SEARCH_HELP, true);
}
});
searchWordChevron.addHyperlinkListener(new HyperlinkAdapter() {
public void linkActivated(HyperlinkEvent e) {
parent.getDisplay().asyncExec(new Runnable() {
public void run() {
toggleSearchWordText();
}
});
}
});
searchWordText.setImage(IHelpUIConstants.IMAGE_HELP, HelpUIResources
.getImage(IHelpUIConstants.IMAGE_HELP));
updateSearchWordText();
TableWrapData td = new TableWrapData();
td.colspan = 2;
searchWordText.setLayoutData(td);
// Pattern combo
searchWordCombo = new ComboPart(container, toolkit, toolkit.getBorderStyle());
updateSearchCombo(null);
td = new TableWrapData(TableWrapData.FILL_GRAB);
td.maxWidth = 100;
td.valign = TableWrapData.MIDDLE;
searchWordCombo.getControl().setLayoutData(td);
searchWordCombo.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
if (searchWordCombo.getSelectionIndex() < 0)
return;
searchFromHistory(searchWordCombo.getSelectionIndex());
}
});
goButton = toolkit.createButton(container, Messages.SearchPart_go, SWT.PUSH);
goButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
handleButtonPressed();
}
});
goButton.setEnabled(false);
searchWordCombo.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
goButton.setEnabled(searchWordCombo.getText().length() > 0);
}
});
searchWordCombo.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.character == '\r') {
if (goButton.isEnabled())
doSearch(searchWordCombo.getText());
}
}
});
searchWordCombo.getControl().addListener(SWT.FocusIn, new Listener() {
public void handleEvent(Event event) {
shellDefaultButton = null;
Shell shell = searchWordCombo.getControl().getShell();
Button button = shell.getDefaultButton();
if (button != null) {
shellDefaultButton = button;
shell.setDefaultButton(goButton);
}
}
});
searchWordCombo.getControl().addListener(SWT.FocusOut, new Listener() {
public void handleEvent(Event event) {
if (shellDefaultButton != null) {
Shell shell = searchWordCombo.getControl().getShell();
shell.setDefaultButton(shellDefaultButton);
shellDefaultButton = null;
}
}
});
scopeSection = toolkit.createSection(container, Section.TWISTIE | Section.COMPACT
| Section.LEFT_TEXT_CLIENT_ALIGNMENT);
scopeSection.setText(Messages.limit_to);
td = new TableWrapData();
td.colspan = 2;
td.align = TableWrapData.FILL;
scopeSection.setLayoutData(td);
filteringGroup = toolkit.createComposite(scopeSection);
scopeSection.setClient(filteringGroup);
TableWrapLayout flayout = new TableWrapLayout();
flayout.numColumns = 2;
filteringGroup.setLayout(flayout);
createScopeSet(scopeSection, toolkit);
toolkit.paintBordersFor(filteringGroup);
toolkit.paintBordersFor(container);
jobListener = new JobListener();
Job.getJobManager().addJobChangeListener(jobListener);
}
| public SearchPart(final Composite parent, FormToolkit toolkit) {
container = toolkit.createComposite(parent);
scopeSetManager = new ScopeSetManager();
TableWrapLayout layout = new TableWrapLayout();
layout.numColumns = 2;
container.setLayout(layout);
// Search Expression
searchWordText = toolkit.createFormText(container, false);
searchWordChevron = new Chevron(searchWordText, SWT.NULL);
toolkit.adapt(searchWordChevron, true, true);
searchWordChevron.setHoverDecorationColor(toolkit.getHyperlinkGroup().getActiveForeground());
searchWordChevron.setDecorationColor(toolkit.getColors().getColor(IFormColors.TB_TOGGLE));
searchWordText.setControl(HREF_TOGGLE, searchWordChevron);
searchWordText.addHyperlinkListener(new HyperlinkAdapter() {
public void linkActivated(HyperlinkEvent e) {
SearchPart.this.parent.showURL(HREF_SEARCH_HELP, true);
}
});
searchWordChevron.addHyperlinkListener(new HyperlinkAdapter() {
public void linkActivated(HyperlinkEvent e) {
parent.getDisplay().asyncExec(new Runnable() {
public void run() {
toggleSearchWordText();
}
});
}
});
searchWordText.setImage(IHelpUIConstants.IMAGE_HELP, HelpUIResources
.getImage(IHelpUIConstants.IMAGE_HELP));
updateSearchWordText();
TableWrapData td = new TableWrapData();
td.colspan = 2;
searchWordText.setLayoutData(td);
// Pattern combo
searchWordCombo = new ComboPart(container, toolkit, toolkit.getBorderStyle());
updateSearchCombo(null);
td = new TableWrapData(TableWrapData.FILL_GRAB);
td.maxWidth = 100;
td.valign = TableWrapData.MIDDLE;
searchWordCombo.getControl().setLayoutData(td);
searchWordCombo.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
if (searchWordCombo.getSelectionIndex() < 0)
return;
searchFromHistory(searchWordCombo.getSelectionIndex());
}
});
goButton = toolkit.createButton(container, Messages.SearchPart_go, SWT.PUSH);
goButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
handleButtonPressed();
}
});
goButton.setEnabled(false);
searchWordCombo.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
goButton.setEnabled(searchWordCombo.getText().length() > 0);
}
});
searchWordCombo.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.character == '\r') {
if (goButton.isEnabled() && searchWordCombo.getSelectionIndex() < 0)
doSearch(searchWordCombo.getText());
}
}
});
searchWordCombo.getControl().addListener(SWT.FocusIn, new Listener() {
public void handleEvent(Event event) {
shellDefaultButton = null;
Shell shell = searchWordCombo.getControl().getShell();
Button button = shell.getDefaultButton();
if (button != null) {
shellDefaultButton = button;
shell.setDefaultButton(goButton);
}
}
});
searchWordCombo.getControl().addListener(SWT.FocusOut, new Listener() {
public void handleEvent(Event event) {
if (shellDefaultButton != null) {
Shell shell = searchWordCombo.getControl().getShell();
shell.setDefaultButton(shellDefaultButton);
shellDefaultButton = null;
}
}
});
scopeSection = toolkit.createSection(container, Section.TWISTIE | Section.COMPACT
| Section.LEFT_TEXT_CLIENT_ALIGNMENT);
scopeSection.setText(Messages.limit_to);
td = new TableWrapData();
td.colspan = 2;
td.align = TableWrapData.FILL;
scopeSection.setLayoutData(td);
filteringGroup = toolkit.createComposite(scopeSection);
scopeSection.setClient(filteringGroup);
TableWrapLayout flayout = new TableWrapLayout();
flayout.numColumns = 2;
filteringGroup.setLayout(flayout);
createScopeSet(scopeSection, toolkit);
toolkit.paintBordersFor(filteringGroup);
toolkit.paintBordersFor(container);
jobListener = new JobListener();
Job.getJobManager().addJobChangeListener(jobListener);
}
|
diff --git a/modules/core/src/main/java/com/griefcraft/modules/worldguard/WorldGuardModule.java b/modules/core/src/main/java/com/griefcraft/modules/worldguard/WorldGuardModule.java
index 7d4f7db8..37089a1f 100644
--- a/modules/core/src/main/java/com/griefcraft/modules/worldguard/WorldGuardModule.java
+++ b/modules/core/src/main/java/com/griefcraft/modules/worldguard/WorldGuardModule.java
@@ -1,159 +1,159 @@
/*
* Copyright 2011 Tyler Blair. 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.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''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 AUTHOR 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.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and contributors and should not be interpreted as representing official policies,
* either expressed or implied, of anybody else.
*/
package com.griefcraft.modules.worldguard;
import com.griefcraft.lwc.LWC;
import com.griefcraft.scripting.JavaModule;
import com.griefcraft.scripting.event.LWCProtectionRegisterEvent;
import com.griefcraft.util.Colors;
import com.griefcraft.util.config.Configuration;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.bukkit.BukkitPlayer;
import com.sk89q.worldguard.bukkit.BukkitUtil;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.protection.GlobalRegionManager;
import com.sk89q.worldguard.protection.managers.RegionManager;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
public class WorldGuardModule extends JavaModule {
/**
* The WorldGuard module configuration
*/
private Configuration configuration = Configuration.load("worldguard.yml");
/**
* The world guard plugin if it is enabled
*/
private WorldGuardPlugin worldGuard = null;
@Override
public void load(LWC lwc) {
Plugin plugin = lwc.getPlugin().getServer().getPluginManager().getPlugin("WorldGuard");
if (plugin != null) {
worldGuard = (WorldGuardPlugin) plugin;
}
}
@Override
public void onRegisterProtection(LWCProtectionRegisterEvent event) {
if (worldGuard == null) {
return;
}
if (!configuration.getBoolean("worldguard.enabled", false)) {
return;
}
Player player = event.getPlayer();
Block block = event.getBlock();
// Load the region manager for the world
GlobalRegionManager globalRegionManager = worldGuard.getGlobalRegionManager();
RegionManager regionManager = globalRegionManager.get(block.getWorld());
// Are we enforcing building?
if (configuration.getBoolean("worldguard.requireBuildRights", true)) {
if (!globalRegionManager.canBuild(player, block)) {
player.sendMessage(Colors.Red + "You need build rights in this region to protect using LWC");
event.setCancelled(true);
return;
}
}
// Create a vector for the region
Vector vector = BukkitUtil.toVector(block);
// Load the regions the block encompasses
List<String> regions = regionManager.getApplicableRegionsIDs(vector);
// check each region
for (String region : regions) {
// Should we deny them?
// we don't need to explicitly call isRegionAllowed because isRegionBlacklisted checks that as well
boolean deny = isRegionBlacklisted(region);
if (deny) {
- player.sendMessage(Colors.Red + "You cannot protect that " + LWC.materialToString(block) + " outside of WorldGuard regions");
+ player.sendMessage(Colors.Red + "LWC protections are not allowed in this region!");
event.setCancelled(true);
}
}
}
/**
* Check if a region is blacklisted
*
* @param region
* @return
*/
private boolean isRegionBlacklisted(String region) {
if (!isRegionAllowed(region)) {
return true;
}
List<String> blacklistedRegions = configuration.getStringList("worldguard.blacklistedRegions", new ArrayList<String>());
return blacklistedRegions.contains("*") || blacklistedRegions.contains(region);
}
/**
* Check if a region is allowed to be built in
*
* @param region
* @return
*/
private boolean isRegionAllowed(String region) {
List<String> allowedRegions = configuration.getStringList("worldguard.regions", new ArrayList<String>());
return allowedRegions.contains("*") || allowedRegions.contains(region);
}
/**
* Set a config value in the configuration
*
* @param path
* @param value
*/
public void set(String path, Object value) {
configuration.setProperty(path, value);
}
/**
* Save the configuration
*/
public boolean save() {
return configuration.save();
}
}
| true | true | public void onRegisterProtection(LWCProtectionRegisterEvent event) {
if (worldGuard == null) {
return;
}
if (!configuration.getBoolean("worldguard.enabled", false)) {
return;
}
Player player = event.getPlayer();
Block block = event.getBlock();
// Load the region manager for the world
GlobalRegionManager globalRegionManager = worldGuard.getGlobalRegionManager();
RegionManager regionManager = globalRegionManager.get(block.getWorld());
// Are we enforcing building?
if (configuration.getBoolean("worldguard.requireBuildRights", true)) {
if (!globalRegionManager.canBuild(player, block)) {
player.sendMessage(Colors.Red + "You need build rights in this region to protect using LWC");
event.setCancelled(true);
return;
}
}
// Create a vector for the region
Vector vector = BukkitUtil.toVector(block);
// Load the regions the block encompasses
List<String> regions = regionManager.getApplicableRegionsIDs(vector);
// check each region
for (String region : regions) {
// Should we deny them?
// we don't need to explicitly call isRegionAllowed because isRegionBlacklisted checks that as well
boolean deny = isRegionBlacklisted(region);
if (deny) {
player.sendMessage(Colors.Red + "You cannot protect that " + LWC.materialToString(block) + " outside of WorldGuard regions");
event.setCancelled(true);
}
}
}
| public void onRegisterProtection(LWCProtectionRegisterEvent event) {
if (worldGuard == null) {
return;
}
if (!configuration.getBoolean("worldguard.enabled", false)) {
return;
}
Player player = event.getPlayer();
Block block = event.getBlock();
// Load the region manager for the world
GlobalRegionManager globalRegionManager = worldGuard.getGlobalRegionManager();
RegionManager regionManager = globalRegionManager.get(block.getWorld());
// Are we enforcing building?
if (configuration.getBoolean("worldguard.requireBuildRights", true)) {
if (!globalRegionManager.canBuild(player, block)) {
player.sendMessage(Colors.Red + "You need build rights in this region to protect using LWC");
event.setCancelled(true);
return;
}
}
// Create a vector for the region
Vector vector = BukkitUtil.toVector(block);
// Load the regions the block encompasses
List<String> regions = regionManager.getApplicableRegionsIDs(vector);
// check each region
for (String region : regions) {
// Should we deny them?
// we don't need to explicitly call isRegionAllowed because isRegionBlacklisted checks that as well
boolean deny = isRegionBlacklisted(region);
if (deny) {
player.sendMessage(Colors.Red + "LWC protections are not allowed in this region!");
event.setCancelled(true);
}
}
}
|
diff --git a/org.eclipse.mylyn.bugzilla.ui/src/org/eclipse/mylyn/internal/bugzilla/ui/editor/AbstractBugEditor.java b/org.eclipse.mylyn.bugzilla.ui/src/org/eclipse/mylyn/internal/bugzilla/ui/editor/AbstractBugEditor.java
index b4855b031..e99032836 100644
--- a/org.eclipse.mylyn.bugzilla.ui/src/org/eclipse/mylyn/internal/bugzilla/ui/editor/AbstractBugEditor.java
+++ b/org.eclipse.mylyn.bugzilla.ui/src/org/eclipse/mylyn/internal/bugzilla/ui/editor/AbstractBugEditor.java
@@ -1,1614 +1,1613 @@
/*******************************************************************************
* Copyright (c) 2003 - 2006 University Of British Columbia and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* University Of British Columbia - initial API and implementation
*******************************************************************************/
package org.eclipse.mylar.internal.bugzilla.ui.editor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.action.GroupMarker;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.resource.JFaceColors;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.util.*;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.mylar.bugzilla.core.Attribute;
import org.eclipse.mylar.bugzilla.core.Comment;
import org.eclipse.mylar.bugzilla.core.IBugzillaBug;
import org.eclipse.mylar.internal.bugzilla.core.BugzillaPlugin;
import org.eclipse.mylar.internal.bugzilla.core.BugzillaTools;
import org.eclipse.mylar.internal.bugzilla.core.IBugzillaAttributeListener;
import org.eclipse.mylar.internal.bugzilla.core.IBugzillaConstants;
import org.eclipse.mylar.internal.bugzilla.core.IBugzillaReportSelection;
import org.eclipse.mylar.internal.bugzilla.ui.tasklist.BugzillaRepositoryConnector;
import org.eclipse.mylar.internal.core.util.MylarStatusHandler;
import org.eclipse.mylar.internal.tasklist.ui.editors.MylarTaskEditor;
import org.eclipse.mylar.provisional.tasklist.MylarTaskListPlugin;
import org.eclipse.mylar.provisional.tasklist.TaskRepository;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.ControlListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.ISelectionListener;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.actions.ActionFactory;
import org.eclipse.ui.actions.RetargetAction;
import org.eclipse.ui.internal.WorkbenchImages;
import org.eclipse.ui.internal.WorkbenchMessages;
import org.eclipse.ui.internal.help.WorkbenchHelpSystem;
import org.eclipse.ui.internal.ide.IDEInternalWorkbenchImages;
import org.eclipse.ui.part.EditorPart;
import org.eclipse.ui.views.contentoutline.ContentOutline;
import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
/**
* Abstract base implementation for an editor to view a bugzilla report.
*
* @author Mik Kersten (some hardening of prototype)
*/
public abstract class AbstractBugEditor extends EditorPart implements Listener {
protected TaskRepository repository;
public static final int WRAP_LENGTH = 90;
protected Display display;
public static final Font TITLE_FONT = JFaceResources.getBannerFont();
public static final Font TEXT_FONT = JFaceResources.getDefaultFont();
public static final Font COMMENT_FONT = JFaceResources.getFontRegistry().get(JFaceResources.TEXT_FONT);
public static final Font HEADER_FONT = JFaceResources.getDefaultFont();
public static final int DESCRIPTION_WIDTH = 79 * 7;
public static final int DESCRIPTION_HEIGHT = 10 * 14;
protected Color background;
protected Color foreground;
protected AbstractBugEditorInput bugzillaInput;
private MylarTaskEditor parentEditor = null;
protected BugzillaOutlineNode bugzillaOutlineModel = null;
/**
* Style option for function <code>newLayout</code>. This will create a
* plain-styled, selectable text label.
*/
protected final String VALUE = "VALUE";
/**
* Style option for function <code>newLayout</code>. This will create a
* bolded, selectable header. It will also have an arrow image before the
* text (simply for decoration).
*/
protected final String HEADER = "HEADER";
/**
* Style option for function <code>newLayout</code>. This will create a
* bolded, unselectable label.
*/
protected final String PROPERTY = "PROPERTY";
protected final int HORZ_INDENT = 0;
protected Combo oSCombo;
protected Combo versionCombo;
protected Combo platformCombo;
protected Combo priorityCombo;
protected Combo severityCombo;
protected Combo milestoneCombo;
protected Combo componentCombo;
protected Text urlText;
protected Text summaryText;
protected Text assignedTo;
protected Button submitButton;
// protected Button saveButton;
protected int scrollIncrement;
protected int scrollVertPageIncrement;
protected int scrollHorzPageIncrement;
public boolean isDirty = false;
/** Manager controlling the context menu */
protected MenuManager contextMenuManager;
protected StyledText currentSelectedText;
protected static final String cutActionDefId = "org.eclipse.ui.edit.cut"; //$NON-NLS-1$
protected static final String copyActionDefId = "org.eclipse.ui.edit.copy"; //$NON-NLS-1$
protected static final String pasteActionDefId = "org.eclipse.ui.edit.paste"; //$NON-NLS-1$
protected RetargetAction cutAction;
protected BugzillaEditorCopyAction copyAction;
protected RetargetAction pasteAction;
protected Composite editorComposite;
// protected CLabel titleLabel;
protected ScrolledComposite scrolledComposite;
protected Composite infoArea;
// protected Hyperlink linkToBug;
// protected StyledText generalTitleText;
private List<IBugzillaAttributeListener> attributesListeners = new ArrayList<IBugzillaAttributeListener>();
protected final ISelectionProvider selectionProvider = new ISelectionProvider() {
public void addSelectionChangedListener(ISelectionChangedListener listener) {
selectionChangedListeners.add(listener);
}
public ISelection getSelection() {
return null;
}
public void removeSelectionChangedListener(ISelectionChangedListener listener) {
selectionChangedListeners.remove(listener);
}
public void setSelection(ISelection selection) {
// No implementation.
}
};
@SuppressWarnings("deprecation")
protected ListenerList selectionChangedListeners = new ListenerList();
protected HashMap<Combo, String> comboListenerMap = new HashMap<Combo, String>();
private IBugzillaReportSelection lastSelected = null;
protected final ISelectionListener selectionListener = new ISelectionListener() {
public void selectionChanged(IWorkbenchPart part, ISelection selection) {
if ((part instanceof ContentOutline) && (selection instanceof StructuredSelection)) {
Object select = ((StructuredSelection) selection).getFirstElement();
if (select instanceof BugzillaOutlineNode) {
BugzillaOutlineNode n = (BugzillaOutlineNode) select;
if (n != null && lastSelected != null
&& BugzillaTools.getHandle(n).equals(BugzillaTools.getHandle(lastSelected))) {
// we don't need to set the selection if it is alredy
// set
return;
}
lastSelected = n;
Object data = n.getData();
boolean highlight = true;
if (n.getKey().toLowerCase().equals("comments")) {
highlight = false;
}
if (n.getKey().toLowerCase().equals("new comment")) {
selectNewComment();
} else if (n.getKey().toLowerCase().equals("new description")) {
selectNewDescription();
} else if (data != null) {
select(data, highlight);
}
}
}
}
};
/**
* Creates a new <code>AbstractBugEditor</code>. Sets up the default
* fonts and cut/copy/paste actions.
*/
public AbstractBugEditor() {
// set the scroll increments so the editor scrolls normally with the
// scroll wheel
FontData[] fd = TEXT_FONT.getFontData();
int cushion = 4;
scrollIncrement = fd[0].getHeight() + cushion;
scrollVertPageIncrement = 0;
scrollHorzPageIncrement = 0;
// set up actions for the context menu
cutAction = new RetargetAction(ActionFactory.CUT.getId(), WorkbenchMessages.Workbench_cut);
cutAction.setToolTipText(WorkbenchMessages.Workbench_cutToolTip);// WorkbenchMessages.getString("Workbench.cutToolTip"));
// //$NON-NLS-1$
cutAction.setImageDescriptor(WorkbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_CUT));
cutAction.setHoverImageDescriptor(WorkbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_CUT));
cutAction.setDisabledImageDescriptor(WorkbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_CUT_DISABLED));
cutAction.setAccelerator(SWT.CTRL | 'x');
cutAction.setActionDefinitionId(cutActionDefId);
pasteAction = new RetargetAction(ActionFactory.PASTE.getId(), WorkbenchMessages.Workbench_paste);
pasteAction.setToolTipText(WorkbenchMessages.Workbench_pasteToolTip);// WorkbenchMessages.getString("Workbench.pasteToolTip"));
// //$NON-NLS-1$
pasteAction.setImageDescriptor(WorkbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_PASTE));
pasteAction.setHoverImageDescriptor(WorkbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_PASTE));
pasteAction.setDisabledImageDescriptor(WorkbenchImages
.getImageDescriptor(ISharedImages.IMG_TOOL_PASTE_DISABLED));
pasteAction.setAccelerator(SWT.CTRL | 'v');
pasteAction.setActionDefinitionId(pasteActionDefId);
copyAction = new BugzillaEditorCopyAction(this);
copyAction.setText(WorkbenchMessages.Workbench_copy);// WorkbenchMessages.getString("Workbench.copy"));
copyAction.setImageDescriptor(WorkbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_COPY));
copyAction.setHoverImageDescriptor(WorkbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_COPY));
copyAction.setDisabledImageDescriptor(WorkbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_COPY_DISABLED));
copyAction.setAccelerator(SWT.CTRL | 'c');
copyAction.setEnabled(false);
}
/**
* @return The bug this editor is displaying.
*/
public abstract IBugzillaBug getBug();
/**
* @return Any currently selected text.
*/
protected StyledText getCurrentText() {
return currentSelectedText;
}
/**
* @return The action used to copy selected text from a bug editor to the
* clipboard.
*/
protected BugzillaEditorCopyAction getCopyAction() {
return copyAction;
}
@Override
public void createPartControl(Composite parent) {
editorComposite = new Composite(parent, SWT.NONE);
GridLayout layout = new GridLayout();
layout.marginHeight = 0;
layout.marginWidth = 0;
layout.verticalSpacing = 0;
layout.horizontalSpacing = 0;
editorComposite.setLayout(layout);
display = parent.getDisplay();
background = JFaceColors.getBannerBackground(display);
foreground = JFaceColors.getBannerForeground(display);
// Create the title for the editor
// createTitleArea(editorComposite);
// Label titleBarSeparator = new Label(editorComposite, SWT.HORIZONTAL | SWT.SEPARATOR);
background = JFaceColors.getBannerBackground(display);
foreground = JFaceColors.getBannerForeground(display);
// GridData gd = new GridData(GridData.FILL_HORIZONTAL);
// titleBarSeparator.setLayoutData(gd);
// Put the bug info onto the editor
createInfoArea(editorComposite);
WorkbenchHelpSystem.getInstance().setHelp(editorComposite, IBugzillaConstants.EDITOR_PAGE_CONTEXT);
infoArea.setMenu(contextMenuManager.createContextMenu(infoArea));
getSite().getPage().addSelectionListener(selectionListener);
getSite().setSelectionProvider(selectionProvider);
}
// protected Composite createTitleArea(Composite parent) {
// // Get the background color for the title area
//
// // Create the title area which will contain
// // a title, message, and image.
// Composite titleArea = new Composite(parent, SWT.NO_FOCUS);
// GridLayout layout = new GridLayout();
// layout.marginHeight = 0;
// layout.marginWidth = 0;
// layout.verticalSpacing = 0;
// layout.horizontalSpacing = 0;
// layout.numColumns = 2;
// titleArea.setLayout(layout);
// titleArea.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
// titleArea.setBackground(background);
//
// // Message label
// titleLabel = new CLabel(titleArea, SWT.LEFT);
// JFaceColors.setColors(titleLabel, foreground, background);
// titleLabel.setFont(TITLE_FONT);
//
// final IPropertyChangeListener fontListener = new IPropertyChangeListener() {
// public void propertyChange(PropertyChangeEvent event) {
// if (JFaceResources.HEADER_FONT.equals(event.getProperty())) {
// titleLabel.setFont(TITLE_FONT);
// }
// }
// };
// titleLabel.addDisposeListener(new DisposeListener() {
// public void widgetDisposed(DisposeEvent event) {
// JFaceResources.getFontRegistry().removeListener(fontListener);
// }
// });
// JFaceResources.getFontRegistry().addListener(fontListener);
// GridData gd = new GridData(GridData.FILL_BOTH);
// titleLabel.setLayoutData(gd);
//
// // Title image
// Label titleImage = new Label(titleArea, SWT.LEFT);
// titleImage.setBackground(background);
// titleImage.setImage(WorkbenchImages.getImage(IDEInternalWorkbenchImages.IMG_OBJS_WELCOME_BANNER));
// gd = new GridData();
// gd.horizontalAlignment = GridData.END;
// titleImage.setLayoutData(gd);
// return titleArea;
// }
/**
* Creates the part of the editor that contains the information about the
* the bug.
*
* @param parent
* The composite to put the info area into.
* @return The info area composite.
*/
protected Composite createInfoArea(Composite parent) {
createContextMenu();
scrolledComposite = new ScrolledComposite(parent, SWT.V_SCROLL | SWT.H_SCROLL);
scrolledComposite.setLayoutData(new GridData(GridData.FILL_BOTH));
infoArea = new Composite(this.scrolledComposite, SWT.NONE);
scrolledComposite.setMinSize(infoArea.computeSize(SWT.DEFAULT, SWT.DEFAULT));
GridLayout infoLayout = new GridLayout();
infoLayout.numColumns = 1;
infoLayout.verticalSpacing = 0;
infoLayout.horizontalSpacing = 0;
infoLayout.marginWidth = 0;
infoArea.setLayout(infoLayout);
infoArea.setBackground(background);
if (getBug() == null) {
// close();
MessageDialog.openError(Display.getDefault().getActiveShell(), "Bugzilla Client Errror",
"Could not resolve the requested bug, check Bugzilla server and version.");
Composite composite = new Composite(parent, SWT.NULL);
Label noBugLabel = new Label(composite, SWT.NULL);
noBugLabel.setText("Could not resolve bug");
return composite;
}
createLayouts();
this.scrolledComposite.setContent(infoArea);
Point p = infoArea.computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
this.scrolledComposite.setMinHeight(p.y);
this.scrolledComposite.setMinWidth(p.x);
this.scrolledComposite.setExpandHorizontal(true);
this.scrolledComposite.setExpandVertical(true);
// make the editor scroll properly with a scroll editor
scrolledComposite.addControlListener(new ControlListener() {
public void controlMoved(ControlEvent e) {
// don't care when the control moved
}
public void controlResized(ControlEvent e) {
scrolledComposite.getVerticalBar().setIncrement(scrollIncrement);
scrolledComposite.getHorizontalBar().setIncrement(scrollIncrement);
scrollVertPageIncrement = scrolledComposite.getClientArea().height;
scrollHorzPageIncrement = scrolledComposite.getClientArea().width;
scrolledComposite.getVerticalBar().setPageIncrement(scrollVertPageIncrement);
scrolledComposite.getHorizontalBar().setPageIncrement(scrollHorzPageIncrement);
}
});
return infoArea;
}
/**
* Create a context menu for this editor.
*/
protected void createContextMenu() {
contextMenuManager = new MenuManager("#BugEditor");
contextMenuManager.setRemoveAllWhenShown(true);
contextMenuManager.addMenuListener(new IMenuListener() {
public void menuAboutToShow(IMenuManager manager) {
manager.add(cutAction);
manager.add(copyAction);
manager.add(pasteAction);
manager.add(new Separator());
manager.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS));
if (currentSelectedText == null || currentSelectedText.getSelectionText().length() == 0) {
copyAction.setEnabled(false);
} else {
copyAction.setEnabled(true);
}
}
});
getSite().registerContextMenu("#BugEditor", contextMenuManager, getSite().getSelectionProvider());
}
/**
* Creates all of the layouts that display the information on the bug.
*/
protected void createLayouts() {
createAttributeLayout();
createDescriptionLayout();
createCommentLayout();
createButtonLayouts();
}
/**
* Creates the attribute layout, which contains most of the basic attributes
* of the bug (some of which are editable).
*/
protected void createAttributeLayout() {
String title = getTitleString();
String keywords = "";
String url = "";
- // Attributes Composite- this holds all the combo fiels and text
- // fields
+ // Attributes Composite- this holds all the combo fiels and text fields
Composite attributesComposite = new Composite(infoArea, SWT.NONE);
GridLayout attributesLayout = new GridLayout();
attributesLayout.numColumns = 4;
attributesLayout.horizontalSpacing = 14;
attributesLayout.verticalSpacing = 6;
attributesComposite.setLayout(attributesLayout);
GridData attributesData = new GridData(GridData.FILL_BOTH);
attributesData.horizontalSpan = 1;
attributesData.grabExcessVerticalSpace = false;
attributesComposite.setLayoutData(attributesData);
attributesComposite.setBackground(background);
// End Attributes Composite
// Attributes Title Area
Composite attributesTitleComposite = new Composite(attributesComposite, SWT.NONE);
GridLayout attributesTitleLayout = new GridLayout();
attributesTitleLayout.horizontalSpacing = 0;
attributesTitleLayout.marginWidth = 0;
attributesTitleComposite.setLayout(attributesTitleLayout);
attributesTitleComposite.setBackground(background);
GridData attributesTitleData = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
attributesTitleData.horizontalSpan = 4;
attributesTitleData.grabExcessVerticalSpace = false;
attributesTitleComposite.setLayoutData(attributesTitleData);
// End Attributes Title
// Set the Attributes Title
// newAttributesLayout(attributesTitleComposite);
// titleLabel.setText(title);
bugzillaInput.setToolTipText(title);
int currentCol = 1;
String ccValue = null;
// Populate Attributes
for (Iterator<Attribute> it = getBug().getAttributes().iterator(); it.hasNext();) {
Attribute attribute = it.next();
String key = attribute.getParameterName();
String name = attribute.getName();
String value = checkText(attribute.getValue());
Map<String, String> values = attribute.getOptionValues();
// make sure we don't try to display a hidden field
if (attribute.isHidden() || (key != null && key.equals("status_whiteboard")))
continue;
if (values == null)
values = new HashMap<String, String>();
if (key == null)
key = "";
GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
data.horizontalSpan = 1;
data.horizontalIndent = HORZ_INDENT;
if (key.equals("short_desc") || key.equals("keywords")) {
keywords = value;
} else if (key.equals("newcc")) {
ccValue = value;
if (value == null)
ccValue = "";
} else if (key.equals("bug_file_loc")) {
url = value;
} else if (key.equals("op_sys")) {
newLayout(attributesComposite, 1, name, PROPERTY);
oSCombo = new Combo(attributesComposite, SWT.NO_BACKGROUND | SWT.MULTI | SWT.V_SCROLL | SWT.READ_ONLY);
oSCombo.setFont(TEXT_FONT);
oSCombo.setLayoutData(data);
oSCombo.setBackground(background);
Set<String> s = values.keySet();
String[] a = s.toArray(new String[s.size()]);
Arrays.sort(a);
for (int i = 0; i < a.length; i++) {
oSCombo.add(a[i]);
}
if (oSCombo.indexOf(value) != -1) {
oSCombo.select(oSCombo.indexOf(value));
} else {
oSCombo.select(oSCombo.indexOf("All"));
}
oSCombo.addListener(SWT.Modify, this);
comboListenerMap.put(oSCombo, name);
oSCombo.addListener(SWT.FocusIn, new GenericListener());
currentCol += 2;
} else if (key.equals("version")) {
newLayout(attributesComposite, 1, name, PROPERTY);
versionCombo = new Combo(attributesComposite, SWT.NO_BACKGROUND | SWT.MULTI | SWT.V_SCROLL
| SWT.READ_ONLY);
versionCombo.setFont(TEXT_FONT);
versionCombo.setLayoutData(data);
versionCombo.setBackground(background);
Set<String> s = values.keySet();
String[] a = s.toArray(new String[s.size()]);
Arrays.sort(a);
for (int i = 0; i < a.length; i++) {
versionCombo.add(a[i]);
}
versionCombo.select(versionCombo.indexOf(value));
versionCombo.addListener(SWT.Modify, this);
versionCombo.addListener(SWT.FocusIn, new GenericListener());
comboListenerMap.put(versionCombo, name);
currentCol += 2;
} else if (key.equals("priority")) {
newLayout(attributesComposite, 1, name, PROPERTY);
priorityCombo = new Combo(attributesComposite, SWT.NO_BACKGROUND | SWT.MULTI | SWT.V_SCROLL
| SWT.READ_ONLY);
priorityCombo.setFont(TEXT_FONT);
priorityCombo.setLayoutData(data);
priorityCombo.setBackground(background);
Set<String> s = values.keySet();
String[] a = s.toArray(new String[s.size()]);
Arrays.sort(a);
for (int i = 0; i < a.length; i++) {
priorityCombo.add(a[i]);
}
priorityCombo.select(priorityCombo.indexOf(value));
priorityCombo.addListener(SWT.Modify, this);
priorityCombo.addListener(SWT.FocusIn, new GenericListener());
comboListenerMap.put(priorityCombo, name);
currentCol += 2;
} else if (key.equals("bug_severity")) {
newLayout(attributesComposite, 1, name, PROPERTY);
severityCombo = new Combo(attributesComposite, SWT.NO_BACKGROUND | SWT.MULTI | SWT.V_SCROLL
| SWT.READ_ONLY);
severityCombo.setFont(TEXT_FONT);
severityCombo.setLayoutData(data);
severityCombo.setBackground(background);
Set<String> s = values.keySet();
String[] a = s.toArray(new String[s.size()]);
Arrays.sort(a);
for (int i = 0; i < a.length; i++) {
severityCombo.add(a[i]);
}
severityCombo.select(severityCombo.indexOf(value));
severityCombo.addListener(SWT.Modify, this);
severityCombo.addListener(SWT.FocusIn, new GenericListener());
comboListenerMap.put(severityCombo, name);
currentCol += 2;
} else if (key.equals("target_milestone")) {
newLayout(attributesComposite, 1, name, PROPERTY);
milestoneCombo = new Combo(attributesComposite, SWT.NO_BACKGROUND | SWT.MULTI | SWT.V_SCROLL
| SWT.READ_ONLY);
milestoneCombo.setFont(TEXT_FONT);
milestoneCombo.setLayoutData(data);
milestoneCombo.setBackground(background);
Set<String> s = values.keySet();
String[] a = s.toArray(new String[s.size()]);
Arrays.sort(a);
for (int i = 0; i < a.length; i++) {
milestoneCombo.add(a[i]);
}
milestoneCombo.select(milestoneCombo.indexOf(value));
milestoneCombo.addListener(SWT.Modify, this);
milestoneCombo.addListener(SWT.FocusIn, new GenericListener());
comboListenerMap.put(milestoneCombo, name);
currentCol += 2;
} else if (key.equals("rep_platform")) {
newLayout(attributesComposite, 1, name, PROPERTY);
platformCombo = new Combo(attributesComposite, SWT.NO_BACKGROUND | SWT.MULTI | SWT.V_SCROLL
| SWT.READ_ONLY);
platformCombo.setFont(TEXT_FONT);
platformCombo.setLayoutData(data);
platformCombo.setBackground(background);
Set<String> s = values.keySet();
String[] a = s.toArray(new String[s.size()]);
Arrays.sort(a);
for (int i = 0; i < a.length; i++) {
platformCombo.add(a[i]);
}
platformCombo.select(platformCombo.indexOf(value));
platformCombo.addListener(SWT.Modify, this);
platformCombo.addListener(SWT.FocusIn, new GenericListener());
comboListenerMap.put(platformCombo, name);
currentCol += 2;
} else if (key.equals("product")) {
newLayout(attributesComposite, 1, name, PROPERTY);
newLayout(attributesComposite, 1, value, VALUE).addListener(SWT.FocusIn, new GenericListener());
currentCol += 2;
} else if (key.equals("assigned_to")) {
newLayout(attributesComposite, 1, name, PROPERTY);
assignedTo = new Text(attributesComposite, SWT.BORDER | SWT.SINGLE | SWT.WRAP);
assignedTo.setFont(TEXT_FONT);
assignedTo.setText(value);
data = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
data.horizontalSpan = 1;
assignedTo.setLayoutData(data);
assignedTo.addListener(SWT.KeyUp, new Listener() {
public void handleEvent(Event event) {
String sel = assignedTo.getText();
Attribute a = getBug().getAttribute("Assign To");
if (!(a.getNewValue().equals(sel))) {
a.setNewValue(sel);
changeDirtyStatus(true);
}
}
});
assignedTo.addListener(SWT.FocusIn, new GenericListener());
currentCol += 2;
} else if (key.equals("component")) {
newLayout(attributesComposite, 1, name, PROPERTY);
componentCombo = new Combo(attributesComposite, SWT.NO_BACKGROUND | SWT.MULTI | SWT.V_SCROLL
| SWT.READ_ONLY);
componentCombo.setFont(TEXT_FONT);
componentCombo.setLayoutData(data);
componentCombo.setBackground(background);
Set<String> s = values.keySet();
String[] a = s.toArray(new String[s.size()]);
Arrays.sort(a);
for (int i = 0; i < a.length; i++) {
componentCombo.add(a[i]);
}
componentCombo.select(componentCombo.indexOf(value));
componentCombo.addListener(SWT.Modify, this);
componentCombo.addListener(SWT.FocusIn, new GenericListener());
comboListenerMap.put(componentCombo, name);
currentCol += 2;
} else if (name.equals("Summary")) {
// Don't show the summary here.
continue;
} else if (values.isEmpty()) {
newLayout(attributesComposite, 1, name, PROPERTY);
newLayout(attributesComposite, 1, value, VALUE).addListener(SWT.FocusIn, new GenericListener());
currentCol += 2;
}
if (currentCol > attributesLayout.numColumns) {
currentCol -= attributesLayout.numColumns;
}
}
// End Populate Attributes
// make sure that we are in the first column
if (currentCol > 1) {
while (currentCol <= attributesLayout.numColumns) {
newLayout(attributesComposite, 1, "", PROPERTY);
currentCol++;
}
}
// URL, Keywords, Summary Text Fields
addUrlText(url, attributesComposite);
// keywords text field (not editable)
addKeywordsList(keywords, attributesComposite);
if (ccValue != null) {
addCCList(ccValue, attributesComposite);
}
addSummaryText(attributesComposite);
// End URL, Keywords, Summary Text Fields
}
/**
* Adds a text field to display and edit the bug's URL attribute.
*
* @param url
* The URL attribute of the bug.
* @param attributesComposite
* The composite to add the text field to.
*/
protected void addUrlText(String url, Composite attributesComposite) {
newLayout(attributesComposite, 1, "URL:", PROPERTY);
urlText = new Text(attributesComposite, SWT.BORDER | SWT.SINGLE | SWT.WRAP);
urlText.setFont(TEXT_FONT);
GridData urlTextData = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
urlTextData.horizontalSpan = 3;
urlTextData.widthHint = 200;
urlText.setLayoutData(urlTextData);
urlText.setText(url);
urlText.addListener(SWT.KeyUp, new Listener() {
public void handleEvent(Event event) {
String sel = urlText.getText();
Attribute a = getBug().getAttribute("URL");
if (!(a.getNewValue().equals(sel))) {
a.setNewValue(sel);
changeDirtyStatus(true);
}
}
});
urlText.addListener(SWT.FocusIn, new GenericListener());
}
/**
* Adds a text field and selection list to display and edit the bug's
* keywords.
*
* @param keywords
* The current list of keywords for this bug.
* @param attributesComposite
* The composite to add the widgets to.
*/
protected abstract void addKeywordsList(String keywords, Composite attributesComposite);
protected abstract void addCCList(String value, Composite attributesComposite);
/**
* Adds a text field to display and edit the bug's summary.
*
* @param attributesComposite
* The composite to add the text field to.
*/
protected void addSummaryText(Composite attributesComposite) {
newLayout(attributesComposite, 1, "Summary:", PROPERTY);
summaryText = new Text(attributesComposite, SWT.BORDER | SWT.SINGLE | SWT.WRAP);
summaryText.setFont(TEXT_FONT);
GridData summaryTextData = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
summaryTextData.horizontalSpan = 3;
summaryTextData.widthHint = 200;
summaryText.setLayoutData(summaryTextData);
summaryText.setText(getBug().getSummary());
summaryText.addListener(SWT.KeyUp, new SummaryListener());
summaryText.addListener(SWT.FocusIn, new GenericListener());
}
/**
* Creates the description layout, which displays and possibly edits the
* bug's description.
*/
protected abstract void createDescriptionLayout();
/**
* Creates the comment layout, which displays the bug's comments and
* possibly lets the user enter a new one.
*/
protected abstract void createCommentLayout();
/**
* Creates the button layout. This displays options and buttons at the
* bottom of the editor to allow actions to be performed on the bug.
*/
protected void createButtonLayouts() {
Composite buttonComposite = new Composite(infoArea, SWT.NONE);
GridLayout buttonLayout = new GridLayout();
buttonLayout.numColumns = 4;
buttonComposite.setLayout(buttonLayout);
buttonComposite.setBackground(background);
GridData buttonData = new GridData(GridData.FILL_BOTH);
buttonData.horizontalSpan = 1;
buttonData.grabExcessVerticalSpace = false;
buttonComposite.setLayoutData(buttonData);
addRadioButtons(buttonComposite);
addActionButtons(buttonComposite);
}
/**
* Adds radio buttons to this composite.
*
* @param buttonComposite
* Composite to add the radio buttons to.
*/
abstract protected void addRadioButtons(Composite buttonComposite);
/**
* Adds buttons to this composite. Subclasses can override this method to
* provide different/additional buttons.
*
* @param buttonComposite
* Composite to add the buttons to.
*/
protected void addActionButtons(Composite buttonComposite) {
submitButton = new Button(buttonComposite, SWT.NONE);
submitButton.setFont(TEXT_FONT);
GridData submitButtonData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
submitButtonData.widthHint = AbstractBugEditor.WRAP_LENGTH;
submitButtonData.heightHint = 20;
submitButton.setText("Submit");
submitButton.setLayoutData(submitButtonData);
submitButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
submitBug();
}
});
submitButton.addListener(SWT.FocusIn, new GenericListener());
// This is not needed anymore since we have the save working properly
// with ctrl-s and file->save
// saveButton = new Button(buttonComposite, SWT.NONE);
// saveButton.setFont(TEXT_FONT);
// GridData saveButtonData = new
// GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
// saveButtonData.widthHint = 100;
// saveButtonData.heightHint = 20;
// saveButton.setText("Save Offline");
// saveButton.setLayoutData(saveButtonData);
// saveButton.addListener(SWT.Selection, new Listener() {
// public void handleEvent(Event e) {
// saveBug();
// updateEditor();
// }
// });
// saveButton.addListener(SWT.FocusIn, new GenericListener());
}
/**
* Make sure that a String that is <code>null</code> is changed to a null
* string
*
* @param text
* The text to check if it is null or not
* @return If the text is <code>null</code>, then return the null string (<code>""</code>).
* Otherwise, return the text.
*/
public static String checkText(String text) {
if (text == null)
return "";
else
return text;
}
/**
* @return A string to use as a title for this editor.
*/
protected abstract String getTitleString();
/**
* Creates an uneditable text field for displaying data.
*
* @param composite
* The composite to put this text field into. Its layout style
* should be a grid with columns.
* @param colSpan
* The number of columns that this text field should span.
* @param text
* The text that for this text field.
* @param style
* The style for this text field. See below for valid values
* (default is HEADER).
* @return The new styled text.
* @see VALUE
* @see PROPERTY
* @see HEADER
*/
protected StyledText newLayout(Composite composite, int colSpan, String text, String style) {
GridData data = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
data.horizontalSpan = colSpan;
StyledText stext;
if (style.equalsIgnoreCase(VALUE)) {
StyledText styledText = new StyledText(composite, SWT.MULTI | SWT.READ_ONLY);
styledText.setFont(TEXT_FONT);
styledText.setText(checkText(text));
styledText.setBackground(background);
data.horizontalIndent = HORZ_INDENT;
styledText.setLayoutData(data);
styledText.setEditable(false);
styledText.getCaret().setVisible(false);
styledText.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
StyledText c = (StyledText) e.widget;
if (c != null && c.getSelectionCount() > 0) {
if (currentSelectedText != null) {
if (!c.equals(currentSelectedText)) {
currentSelectedText.setSelectionRange(0, 0);
}
}
}
currentSelectedText = c;
}
});
styledText.setMenu(contextMenuManager.createContextMenu(styledText));
stext = styledText;
} else if (style.equalsIgnoreCase(PROPERTY)) {
StyledText styledText = new StyledText(composite, SWT.MULTI | SWT.READ_ONLY);
styledText.setFont(TEXT_FONT);
styledText.setText(checkText(text));
styledText.setBackground(background);
data.horizontalIndent = HORZ_INDENT;
styledText.setLayoutData(data);
StyleRange sr = new StyleRange(styledText.getOffsetAtLine(0), text.length(), foreground, background,
SWT.BOLD);
styledText.setStyleRange(sr);
styledText.getCaret().setVisible(false);
styledText.setEnabled(false);
styledText.setMenu(contextMenuManager.createContextMenu(styledText));
stext = styledText;
} else {
Composite generalTitleGroup = new Composite(composite, SWT.NONE);
generalTitleGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
generalTitleGroup.setLayoutData(data);
GridLayout generalTitleLayout = new GridLayout();
generalTitleLayout.numColumns = 2;
generalTitleLayout.marginWidth = 0;
generalTitleLayout.marginHeight = 9;
generalTitleGroup.setLayout(generalTitleLayout);
generalTitleGroup.setBackground(background);
Label image = new Label(generalTitleGroup, SWT.NONE);
image.setBackground(background);
image.setImage(WorkbenchImages.getImage(IDEInternalWorkbenchImages.IMG_OBJS_WELCOME_ITEM));
GridData gd = new GridData(GridData.FILL_BOTH);
gd.verticalAlignment = GridData.VERTICAL_ALIGN_BEGINNING;
image.setLayoutData(gd);
StyledText titleText = new StyledText(generalTitleGroup, SWT.MULTI | SWT.READ_ONLY);
titleText.setText(checkText(text));
titleText.setFont(HEADER_FONT);
titleText.setBackground(background);
StyleRange sr = new StyleRange(titleText.getOffsetAtLine(0), text.length(), foreground, background,
SWT.BOLD);
titleText.setStyleRange(sr);
titleText.getCaret().setVisible(false);
titleText.setEditable(false);
titleText.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
StyledText c = (StyledText) e.widget;
if (c != null && c.getSelectionCount() > 0) {
if (currentSelectedText != null) {
if (!c.equals(currentSelectedText)) {
currentSelectedText.setSelectionRange(0, 0);
}
}
}
currentSelectedText = c;
}
});
// create context menu
generalTitleGroup.setMenu(contextMenuManager.createContextMenu(generalTitleGroup));
titleText.setMenu(contextMenuManager.createContextMenu(titleText));
image.setMenu(contextMenuManager.createContextMenu(image));
stext = titleText;
}
composite.setMenu(contextMenuManager.createContextMenu(composite));
return stext;
}
// /**
// * This creates the title header for the info area. Its style is similar to
// * one from calling the function <code>newLayout</code> with the style
// * <code>HEADER</code>.
// *
// * @param composite
// * The composite to put this text field into. Its layout style
// * should be a grid with columns.
// */
// protected void newAttributesLayout(Composite composite) {
// GridData data = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
// data.horizontalSpan = 4;
// Composite generalTitleGroup = new Composite(composite, SWT.NONE);
// generalTitleGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
// generalTitleGroup.setLayoutData(data);
// GridLayout generalTitleLayout = new GridLayout();
// generalTitleLayout.numColumns = 3;
// generalTitleLayout.marginWidth = 0;
// generalTitleLayout.marginHeight = 9;
// generalTitleGroup.setLayout(generalTitleLayout);
// generalTitleGroup.setBackground(background);
//
// Label image = new Label(generalTitleGroup, SWT.NONE);
// image.setBackground(background);
// image.setImage(WorkbenchImages.getImage(IDEInternalWorkbenchImages.IMG_OBJS_WELCOME_ITEM));
//
// GridData gd = new GridData(GridData.FILL_BOTH);
// gd.verticalAlignment = GridData.VERTICAL_ALIGN_BEGINNING;
// image.setLayoutData(gd);
// generalTitleText = new StyledText(generalTitleGroup, SWT.MULTI | SWT.READ_ONLY);
// generalTitleText.setBackground(background);
// generalTitleText.getCaret().setVisible(false);
// generalTitleText.setEditable(false);
// generalTitleText.addSelectionListener(new SelectionAdapter() {
//
// @Override
// public void widgetSelected(SelectionEvent e) {
// StyledText c = (StyledText) e.widget;
// if (c != null && c.getSelectionCount() > 0) {
// if (currentSelectedText != null) {
// if (!c.equals(currentSelectedText)) {
// currentSelectedText.setSelectionRange(0, 0);
// }
// }
// }
// currentSelectedText = c;
// }
// });
// create context menu
// generalTitleGroup.setMenu(contextMenuManager.createContextMenu(generalTitleGroup));
// generalTitleText.setMenu(contextMenuManager.createContextMenu(generalTitleText));
// linkToBug = new Hyperlink(generalTitleGroup, SWT.MULTI | SWT.READ_ONLY);
// linkToBug.setBackground(background);
// setGeneralTitleText();
// image.setMenu(contextMenuManager.createContextMenu(image));
// composite.setMenu(contextMenuManager.createContextMenu(composite));
// }
/**
* This refreshes the text in the title label of the info area (it contains
* elements which can change).
*/
protected void setGeneralTitleText() {
// String text = "[Open in Internal Browser]";
// linkToBug.setText(text);
// linkToBug.setFont(TEXT_FONT);
// if (this instanceof ExistingBugEditor) {
// linkToBug.setUnderlined(true);
// linkToBug.setForeground(JFaceColors.getHyperlinkText(Display.getCurrent()));
// linkToBug.addMouseListener(new MouseListener() {
//
// public void mouseDoubleClick(MouseEvent e) {
// }
//
// public void mouseUp(MouseEvent e) {
// }
//
// public void mouseDown(MouseEvent e) {
// TaskListUiUtil.openUrl(getTitle(), getTitleToolTip(), BugzillaRepositoryUtil.getBugUrlWithoutLogin(
// bugzillaInput.getBug().getRepositoryUrl(), bugzillaInput.getBug().getId()));
// if (e.stateMask == SWT.MOD3) {
// // XXX come back to look at this ui
// close();
// }
//
// }
// });
// } else {
// linkToBug.setEnabled(false);
// }
// linkToBug.addListener(SWT.FocusIn, new GenericListener());
//
// // Resize the composite, in case the new summary is longer than the
// // previous one.
// // Then redraw it to show the changes.
// linkToBug.getParent().pack(true);
// linkToBug.redraw();
// String text = getTitleString();
// generalTitleText.setText(text);
// StyleRange sr = new StyleRange(generalTitleText.getOffsetAtLine(0), text.length(), foreground, background,
// SWT.BOLD);
// generalTitleText.setStyleRange(sr);
// generalTitleText.addListener(SWT.FocusIn, new GenericListener());
//
// // Resize the composite, in case the new summary is longer than the
// // previous one.
// // Then redraw it to show the changes.
// generalTitleText.getParent().pack(true);
// generalTitleText.redraw();
}
/**
* Creates some blank space underneath the supplied composite.
*
* @param parent
* The composite to add the blank space to.
*/
protected void createSeparatorSpace(Composite parent) {
GridData separatorData = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
separatorData.verticalSpan = 1;
separatorData.grabExcessVerticalSpace = false;
Composite separatorComposite = new Composite(parent, SWT.NONE);
GridLayout separatorLayout = new GridLayout();
separatorLayout.marginHeight = 0;
separatorLayout.verticalSpacing = 0;
separatorComposite.setLayout(separatorLayout);
separatorComposite.setBackground(background);
separatorComposite.setLayoutData(separatorData);
newLayout(separatorComposite, 1, "", VALUE);
}
/**
* Submit the changes to the bug to the bugzilla server.
* (Public for testing purposes)
*/
protected abstract void submitBug();
/**
* If there is no locally saved copy of the current bug, then it saved
* offline. Otherwise, any changes are updated in the file.
*/
public void saveBug() {
try {
updateBug();
IBugzillaBug bug = getBug();
// if (bug.hasChanges()) {
// BugzillaPlugin.getDefault().fireOfflineStatusChanged(bug,
// BugzillaOfflineStaus.SAVED_WITH_OUTGOING_CHANGES);
// } else {
// BugzillaPlugin.getDefault().fireOfflineStatusChanged(bug, BugzillaOfflineStaus.SAVED);
// }
final BugzillaRepositoryConnector bugzillaRepositoryClient = (BugzillaRepositoryConnector)MylarTaskListPlugin.getRepositoryManager().getRepositoryConnector(BugzillaPlugin.REPOSITORY_KIND);
changeDirtyStatus(false);
bugzillaRepositoryClient.saveBugReport(bug);//OfflineView.saveOffline(getBug(), true);
} catch (Exception e) {
MylarStatusHandler.fail(e, "bug save offline failed", true);
}
// OfflineView.checkWindow();
// OfflineView.refreshView();
}
/**
* Updates the <code>IBugzillaBug</code> object to contain the latest data
* entered in the data fields.
*/
protected abstract void updateBug();
/**
* Resets the data fields to contain the data currently in the
* <code>IBugzillaBug</code> object.
*/
protected abstract void restoreBug();
/**
* Refreshes any text labels in the editor that contain information that
* might change.
*/
protected void updateEditor() {
// Reset all summary occurrences, since it might have
// been edited.
// String title = getTitleString();
// titleLabel.setText(title);
setGeneralTitleText();
}
// /**
// * Break text up into lines of about 80 characters so that it is displayed
// * properly in bugzilla
// *
// * @param origText
// * The string to be formatted
// * @return The formatted text
// */
// public static String formatText(String origText) {
// if (BugzillaPlugin.getDefault().isServerCompatability220()) {
// return origText;
// }
//
// String[] textArray = new String[(origText.length() / WRAP_LENGTH + 1) * 2];
// for (int i = 0; i < textArray.length; i++)
// textArray[i] = null;
// int j = 0;
// while (true) {
// int spaceIndex = origText.indexOf(" ", WRAP_LENGTH - 5);
// if (spaceIndex == origText.length() || spaceIndex == -1) {
// textArray[j] = origText;
// break;
// }
// textArray[j] = origText.substring(0, spaceIndex);
// origText = origText.substring(spaceIndex + 1, origText.length());
// j++;
// }
//
// String newText = "";
//
// for (int i = 0; i < textArray.length; i++) {
// if (textArray[i] == null)
// break;
// newText += textArray[i] + "\n";
// }
// return newText;
// }
// /**
// * function to set the url to post the bug to
// *
// * @param form
// * A reference to a BugzillaReportSubmitForm that the bug is going to
// * be posted to
// * @param formName
// * The form that we wish to use to submit the bug
// */
// public static void setURL(BugzillaReportSubmitForm form, TaskRepository repository, String formName) {
// // String baseURL = BugzillaPlugin.getDefault().getServerName();
// String baseURL = repository.getUrl().toExternalForm();
// if (!baseURL.endsWith("/"))
// baseURL += "/";
// try {
// form.setURL(baseURL + formName);
// } catch (MalformedURLException e) {
// // we should be ok here
// }
//
// // add the login information to the bug post
// form.add("Bugzilla_login", repository.getUserName());
// form.add("Bugzilla_password", repository.getPassword());
// }
@Override
public void setFocus() {
scrolledComposite.setFocus();
}
@Override
public boolean isDirty() {
return isDirty;
}
/**
* Updates the dirty status of this editor page. The dirty status is true if
* the bug report has been modified but not saved. The title of the editor
* is also updated to reflect the status.
*
* @param newDirtyStatus
* is true when the bug report has been modified but not saved
*/
public void changeDirtyStatus(boolean newDirtyStatus) {
isDirty = newDirtyStatus;
if (parentEditor == null) {
firePropertyChange(PROP_DIRTY);
} else {
parentEditor.markDirty();
}
}
/**
* Updates the title of the editor to reflect dirty status. If the bug
* report has been modified but not saved, then an indicator will appear in
* the title.
*/
protected void updateEditorTitle() {
setPartName(bugzillaInput.getName());
}
@Override
public boolean isSaveAsAllowed() {
return false;
}
@Override
public void doSave(IProgressMonitor monitor) {
saveBug();
updateEditor();
// XXX notify that saved ofline?
}
@Override
public void doSaveAs() {
// we don't save, so no need to implement
}
/**
* @return The composite for the whole editor.
*/
public Composite getEditorComposite() {
return editorComposite;
}
@Override
public void dispose() {
super.dispose();
isDisposed = true;
getSite().getPage().removeSelectionListener(selectionListener);
}
public void handleEvent(Event event) {
if (event.widget instanceof Combo) {
Combo combo = (Combo) event.widget;
if (comboListenerMap.containsKey(combo)) {
String sel = combo.getItem(combo.getSelectionIndex());
Attribute attribute = getBug().getAttribute(comboListenerMap.get(combo));
if (sel != null && !(sel.equals(attribute.getNewValue()))) {
attribute.setNewValue(sel);
for (IBugzillaAttributeListener client : attributesListeners) {
client.attributeChanged(attribute.getName(), sel);
}
changeDirtyStatus(true);
}
}
}
}
/**
* Fires a <code>SelectionChangedEvent</code> to all listeners registered
* under <code>selectionChangedListeners</code>.
*
* @param event
* The selection event.
*/
protected void fireSelectionChanged(final SelectionChangedEvent event) {
Object[] listeners = selectionChangedListeners.getListeners();
for (int i = 0; i < listeners.length; i++) {
final ISelectionChangedListener l = (ISelectionChangedListener) listeners[i];
SafeRunnable.run(new SafeRunnable() {
public void run() {
l.selectionChanged(event);
}
});
}
}
/**
* A generic listener for selection of unimportant items. The default
* selection item sent out is the entire bug object.
*/
protected class GenericListener implements Listener {
public void handleEvent(Event event) {
IBugzillaBug bug = getBug();
fireSelectionChanged(new SelectionChangedEvent(selectionProvider, new StructuredSelection(
new BugzillaReportSelection(bug.getId(), bug.getRepositoryUrl(), bug.getLabel(), false, bug
.getSummary()))));
}
}
/**
* A listener to check if the summary field was modified.
*/
protected class SummaryListener implements Listener {
public void handleEvent(Event event) {
handleSummaryEvent();
}
}
/**
* Check if the summary field was modified, and update it if necessary.
*/
public abstract void handleSummaryEvent();
/*----------------------------------------------------------*
* CODE TO SCROLL TO A COMMENT OR OTHER PIECE OF TEXT
*----------------------------------------------------------*/
/** List of the StyledText's so that we can get the previous and the next */
protected ArrayList<StyledText> texts = new ArrayList<StyledText>();
protected HashMap<Object, StyledText> textHash = new HashMap<Object, StyledText>();
/** Index into the styled texts */
protected int textsindex = 0;
protected Text addCommentsTextBox = null;
protected Text descriptionTextBox = null;
private StyledText previousText = null;
/**
* Selects the given object in the editor.
*
* @param commentNumber
* The comment number to be selected
*/
public void select(int commentNumber) {
if (commentNumber == -1)
return;
for (Object o : textHash.keySet()) {
if (o instanceof Comment) {
if (((Comment) o).getNumber() == commentNumber) {
select(o, true);
}
}
}
}
/**
* Selects the given object in the editor.
*
* @param o
* The object to be selected.
* @param highlight
* Whether or not the object should be highlighted.
*/
public void select(Object o, boolean highlight) {
if (textHash.containsKey(o)) {
StyledText t = textHash.get(o);
if (t != null) {
focusOn(t, highlight);
}
} else if (o instanceof IBugzillaBug) {
focusOn(null, highlight);
}
}
public void selectDescription() {
for (Object o : textHash.keySet()) {
if (o.equals(bugzillaInput.getBug().getDescription())) {
select(o, true);
}
}
}
public void selectNewComment() {
focusOn(addCommentsTextBox, false);
}
public void selectNewDescription() {
focusOn(descriptionTextBox, false);
}
/**
* Scroll to a specified piece of text
*
* @param selectionComposite
* The StyledText to scroll to
*/
private void focusOn(Control selectionComposite, boolean highlight) {
int pos = 0;
if (previousText != null && !previousText.isDisposed()) {
previousText.setSelection(0);
}
if (selectionComposite instanceof StyledText)
previousText = (StyledText) selectionComposite;
if (selectionComposite != null) {
if (highlight && selectionComposite instanceof StyledText && !selectionComposite.isDisposed())
((StyledText) selectionComposite).setSelection(0, ((StyledText) selectionComposite).getText().length());
// get the position of the text in the composite
pos = 0;
Control s = selectionComposite;
if (s.isDisposed())
return;
s.setEnabled(true);
s.setFocus();
s.forceFocus();
while (s != null && s != getEditorComposite()) {
if (!s.isDisposed()) {
pos += s.getLocation().y;
s = s.getParent();
}
}
pos = scrolledComposite.getOrigin().y + pos - 60;
}
if (!scrolledComposite.isDisposed())
scrolledComposite.setOrigin(0, pos);
}
private BugzillaOutlinePage outlinePage = null;
@Override
public Object getAdapter(Class adapter) {
if (IContentOutlinePage.class.equals(adapter)) {
if (outlinePage == null && bugzillaInput != null) {
outlinePage = new BugzillaOutlinePage(bugzillaOutlineModel);
}
return outlinePage;
}
return super.getAdapter(adapter);
}
public BugzillaOutlineNode getOutlineModel() {
return bugzillaOutlineModel;
}
public BugzillaOutlinePage getOutline() {
return outlinePage;
}
private boolean isDisposed = false;
public boolean isDisposed() {
return isDisposed;
}
public void close() {
Display activeDisplay = getSite().getShell().getDisplay();
activeDisplay.asyncExec(new Runnable() {
public void run() {
if (getSite() != null && getSite().getPage() != null && !AbstractBugEditor.this.isDisposed())
if (parentEditor != null) {
getSite().getPage().closeEditor(parentEditor, false);
} else {
getSite().getPage().closeEditor(AbstractBugEditor.this, false);
}
}
});
}
public void addAttributeListener(IBugzillaAttributeListener listener) {
attributesListeners.add(listener);
}
public void removeAttributeListener(IBugzillaAttributeListener listener) {
attributesListeners.remove(listener);
}
public void setParentEditor(MylarTaskEditor parentEditor) {
this.parentEditor = parentEditor;
}
public BugzillaOutlineNode getBugzillaOutlineModel() {
return bugzillaOutlineModel;
}
public void setBugzillaOutlineModel(BugzillaOutlineNode bugzillaOutlineModel) {
this.bugzillaOutlineModel = bugzillaOutlineModel;
}
}
| true | true | protected void createAttributeLayout() {
String title = getTitleString();
String keywords = "";
String url = "";
// Attributes Composite- this holds all the combo fiels and text
// fields
Composite attributesComposite = new Composite(infoArea, SWT.NONE);
GridLayout attributesLayout = new GridLayout();
attributesLayout.numColumns = 4;
attributesLayout.horizontalSpacing = 14;
attributesLayout.verticalSpacing = 6;
attributesComposite.setLayout(attributesLayout);
GridData attributesData = new GridData(GridData.FILL_BOTH);
attributesData.horizontalSpan = 1;
attributesData.grabExcessVerticalSpace = false;
attributesComposite.setLayoutData(attributesData);
attributesComposite.setBackground(background);
// End Attributes Composite
// Attributes Title Area
Composite attributesTitleComposite = new Composite(attributesComposite, SWT.NONE);
GridLayout attributesTitleLayout = new GridLayout();
attributesTitleLayout.horizontalSpacing = 0;
attributesTitleLayout.marginWidth = 0;
attributesTitleComposite.setLayout(attributesTitleLayout);
attributesTitleComposite.setBackground(background);
GridData attributesTitleData = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
attributesTitleData.horizontalSpan = 4;
attributesTitleData.grabExcessVerticalSpace = false;
attributesTitleComposite.setLayoutData(attributesTitleData);
// End Attributes Title
// Set the Attributes Title
// newAttributesLayout(attributesTitleComposite);
// titleLabel.setText(title);
bugzillaInput.setToolTipText(title);
int currentCol = 1;
String ccValue = null;
// Populate Attributes
for (Iterator<Attribute> it = getBug().getAttributes().iterator(); it.hasNext();) {
Attribute attribute = it.next();
String key = attribute.getParameterName();
String name = attribute.getName();
String value = checkText(attribute.getValue());
Map<String, String> values = attribute.getOptionValues();
// make sure we don't try to display a hidden field
if (attribute.isHidden() || (key != null && key.equals("status_whiteboard")))
continue;
if (values == null)
values = new HashMap<String, String>();
if (key == null)
key = "";
GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
data.horizontalSpan = 1;
data.horizontalIndent = HORZ_INDENT;
if (key.equals("short_desc") || key.equals("keywords")) {
keywords = value;
} else if (key.equals("newcc")) {
ccValue = value;
if (value == null)
ccValue = "";
} else if (key.equals("bug_file_loc")) {
url = value;
} else if (key.equals("op_sys")) {
newLayout(attributesComposite, 1, name, PROPERTY);
oSCombo = new Combo(attributesComposite, SWT.NO_BACKGROUND | SWT.MULTI | SWT.V_SCROLL | SWT.READ_ONLY);
oSCombo.setFont(TEXT_FONT);
oSCombo.setLayoutData(data);
oSCombo.setBackground(background);
Set<String> s = values.keySet();
String[] a = s.toArray(new String[s.size()]);
Arrays.sort(a);
for (int i = 0; i < a.length; i++) {
oSCombo.add(a[i]);
}
if (oSCombo.indexOf(value) != -1) {
oSCombo.select(oSCombo.indexOf(value));
} else {
oSCombo.select(oSCombo.indexOf("All"));
}
oSCombo.addListener(SWT.Modify, this);
comboListenerMap.put(oSCombo, name);
oSCombo.addListener(SWT.FocusIn, new GenericListener());
currentCol += 2;
} else if (key.equals("version")) {
newLayout(attributesComposite, 1, name, PROPERTY);
versionCombo = new Combo(attributesComposite, SWT.NO_BACKGROUND | SWT.MULTI | SWT.V_SCROLL
| SWT.READ_ONLY);
versionCombo.setFont(TEXT_FONT);
versionCombo.setLayoutData(data);
versionCombo.setBackground(background);
Set<String> s = values.keySet();
String[] a = s.toArray(new String[s.size()]);
Arrays.sort(a);
for (int i = 0; i < a.length; i++) {
versionCombo.add(a[i]);
}
versionCombo.select(versionCombo.indexOf(value));
versionCombo.addListener(SWT.Modify, this);
versionCombo.addListener(SWT.FocusIn, new GenericListener());
comboListenerMap.put(versionCombo, name);
currentCol += 2;
} else if (key.equals("priority")) {
newLayout(attributesComposite, 1, name, PROPERTY);
priorityCombo = new Combo(attributesComposite, SWT.NO_BACKGROUND | SWT.MULTI | SWT.V_SCROLL
| SWT.READ_ONLY);
priorityCombo.setFont(TEXT_FONT);
priorityCombo.setLayoutData(data);
priorityCombo.setBackground(background);
Set<String> s = values.keySet();
String[] a = s.toArray(new String[s.size()]);
Arrays.sort(a);
for (int i = 0; i < a.length; i++) {
priorityCombo.add(a[i]);
}
priorityCombo.select(priorityCombo.indexOf(value));
priorityCombo.addListener(SWT.Modify, this);
priorityCombo.addListener(SWT.FocusIn, new GenericListener());
comboListenerMap.put(priorityCombo, name);
currentCol += 2;
} else if (key.equals("bug_severity")) {
newLayout(attributesComposite, 1, name, PROPERTY);
severityCombo = new Combo(attributesComposite, SWT.NO_BACKGROUND | SWT.MULTI | SWT.V_SCROLL
| SWT.READ_ONLY);
severityCombo.setFont(TEXT_FONT);
severityCombo.setLayoutData(data);
severityCombo.setBackground(background);
Set<String> s = values.keySet();
String[] a = s.toArray(new String[s.size()]);
Arrays.sort(a);
for (int i = 0; i < a.length; i++) {
severityCombo.add(a[i]);
}
severityCombo.select(severityCombo.indexOf(value));
severityCombo.addListener(SWT.Modify, this);
severityCombo.addListener(SWT.FocusIn, new GenericListener());
comboListenerMap.put(severityCombo, name);
currentCol += 2;
} else if (key.equals("target_milestone")) {
newLayout(attributesComposite, 1, name, PROPERTY);
milestoneCombo = new Combo(attributesComposite, SWT.NO_BACKGROUND | SWT.MULTI | SWT.V_SCROLL
| SWT.READ_ONLY);
milestoneCombo.setFont(TEXT_FONT);
milestoneCombo.setLayoutData(data);
milestoneCombo.setBackground(background);
Set<String> s = values.keySet();
String[] a = s.toArray(new String[s.size()]);
Arrays.sort(a);
for (int i = 0; i < a.length; i++) {
milestoneCombo.add(a[i]);
}
milestoneCombo.select(milestoneCombo.indexOf(value));
milestoneCombo.addListener(SWT.Modify, this);
milestoneCombo.addListener(SWT.FocusIn, new GenericListener());
comboListenerMap.put(milestoneCombo, name);
currentCol += 2;
} else if (key.equals("rep_platform")) {
newLayout(attributesComposite, 1, name, PROPERTY);
platformCombo = new Combo(attributesComposite, SWT.NO_BACKGROUND | SWT.MULTI | SWT.V_SCROLL
| SWT.READ_ONLY);
platformCombo.setFont(TEXT_FONT);
platformCombo.setLayoutData(data);
platformCombo.setBackground(background);
Set<String> s = values.keySet();
String[] a = s.toArray(new String[s.size()]);
Arrays.sort(a);
for (int i = 0; i < a.length; i++) {
platformCombo.add(a[i]);
}
platformCombo.select(platformCombo.indexOf(value));
platformCombo.addListener(SWT.Modify, this);
platformCombo.addListener(SWT.FocusIn, new GenericListener());
comboListenerMap.put(platformCombo, name);
currentCol += 2;
} else if (key.equals("product")) {
newLayout(attributesComposite, 1, name, PROPERTY);
newLayout(attributesComposite, 1, value, VALUE).addListener(SWT.FocusIn, new GenericListener());
currentCol += 2;
} else if (key.equals("assigned_to")) {
newLayout(attributesComposite, 1, name, PROPERTY);
assignedTo = new Text(attributesComposite, SWT.BORDER | SWT.SINGLE | SWT.WRAP);
assignedTo.setFont(TEXT_FONT);
assignedTo.setText(value);
data = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
data.horizontalSpan = 1;
assignedTo.setLayoutData(data);
assignedTo.addListener(SWT.KeyUp, new Listener() {
public void handleEvent(Event event) {
String sel = assignedTo.getText();
Attribute a = getBug().getAttribute("Assign To");
if (!(a.getNewValue().equals(sel))) {
a.setNewValue(sel);
changeDirtyStatus(true);
}
}
});
assignedTo.addListener(SWT.FocusIn, new GenericListener());
currentCol += 2;
} else if (key.equals("component")) {
newLayout(attributesComposite, 1, name, PROPERTY);
componentCombo = new Combo(attributesComposite, SWT.NO_BACKGROUND | SWT.MULTI | SWT.V_SCROLL
| SWT.READ_ONLY);
componentCombo.setFont(TEXT_FONT);
componentCombo.setLayoutData(data);
componentCombo.setBackground(background);
Set<String> s = values.keySet();
String[] a = s.toArray(new String[s.size()]);
Arrays.sort(a);
for (int i = 0; i < a.length; i++) {
componentCombo.add(a[i]);
}
componentCombo.select(componentCombo.indexOf(value));
componentCombo.addListener(SWT.Modify, this);
componentCombo.addListener(SWT.FocusIn, new GenericListener());
comboListenerMap.put(componentCombo, name);
currentCol += 2;
} else if (name.equals("Summary")) {
// Don't show the summary here.
continue;
} else if (values.isEmpty()) {
newLayout(attributesComposite, 1, name, PROPERTY);
newLayout(attributesComposite, 1, value, VALUE).addListener(SWT.FocusIn, new GenericListener());
currentCol += 2;
}
if (currentCol > attributesLayout.numColumns) {
currentCol -= attributesLayout.numColumns;
}
}
// End Populate Attributes
// make sure that we are in the first column
if (currentCol > 1) {
while (currentCol <= attributesLayout.numColumns) {
newLayout(attributesComposite, 1, "", PROPERTY);
currentCol++;
}
}
// URL, Keywords, Summary Text Fields
addUrlText(url, attributesComposite);
// keywords text field (not editable)
addKeywordsList(keywords, attributesComposite);
if (ccValue != null) {
addCCList(ccValue, attributesComposite);
}
addSummaryText(attributesComposite);
// End URL, Keywords, Summary Text Fields
}
| protected void createAttributeLayout() {
String title = getTitleString();
String keywords = "";
String url = "";
// Attributes Composite- this holds all the combo fiels and text fields
Composite attributesComposite = new Composite(infoArea, SWT.NONE);
GridLayout attributesLayout = new GridLayout();
attributesLayout.numColumns = 4;
attributesLayout.horizontalSpacing = 14;
attributesLayout.verticalSpacing = 6;
attributesComposite.setLayout(attributesLayout);
GridData attributesData = new GridData(GridData.FILL_BOTH);
attributesData.horizontalSpan = 1;
attributesData.grabExcessVerticalSpace = false;
attributesComposite.setLayoutData(attributesData);
attributesComposite.setBackground(background);
// End Attributes Composite
// Attributes Title Area
Composite attributesTitleComposite = new Composite(attributesComposite, SWT.NONE);
GridLayout attributesTitleLayout = new GridLayout();
attributesTitleLayout.horizontalSpacing = 0;
attributesTitleLayout.marginWidth = 0;
attributesTitleComposite.setLayout(attributesTitleLayout);
attributesTitleComposite.setBackground(background);
GridData attributesTitleData = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
attributesTitleData.horizontalSpan = 4;
attributesTitleData.grabExcessVerticalSpace = false;
attributesTitleComposite.setLayoutData(attributesTitleData);
// End Attributes Title
// Set the Attributes Title
// newAttributesLayout(attributesTitleComposite);
// titleLabel.setText(title);
bugzillaInput.setToolTipText(title);
int currentCol = 1;
String ccValue = null;
// Populate Attributes
for (Iterator<Attribute> it = getBug().getAttributes().iterator(); it.hasNext();) {
Attribute attribute = it.next();
String key = attribute.getParameterName();
String name = attribute.getName();
String value = checkText(attribute.getValue());
Map<String, String> values = attribute.getOptionValues();
// make sure we don't try to display a hidden field
if (attribute.isHidden() || (key != null && key.equals("status_whiteboard")))
continue;
if (values == null)
values = new HashMap<String, String>();
if (key == null)
key = "";
GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
data.horizontalSpan = 1;
data.horizontalIndent = HORZ_INDENT;
if (key.equals("short_desc") || key.equals("keywords")) {
keywords = value;
} else if (key.equals("newcc")) {
ccValue = value;
if (value == null)
ccValue = "";
} else if (key.equals("bug_file_loc")) {
url = value;
} else if (key.equals("op_sys")) {
newLayout(attributesComposite, 1, name, PROPERTY);
oSCombo = new Combo(attributesComposite, SWT.NO_BACKGROUND | SWT.MULTI | SWT.V_SCROLL | SWT.READ_ONLY);
oSCombo.setFont(TEXT_FONT);
oSCombo.setLayoutData(data);
oSCombo.setBackground(background);
Set<String> s = values.keySet();
String[] a = s.toArray(new String[s.size()]);
Arrays.sort(a);
for (int i = 0; i < a.length; i++) {
oSCombo.add(a[i]);
}
if (oSCombo.indexOf(value) != -1) {
oSCombo.select(oSCombo.indexOf(value));
} else {
oSCombo.select(oSCombo.indexOf("All"));
}
oSCombo.addListener(SWT.Modify, this);
comboListenerMap.put(oSCombo, name);
oSCombo.addListener(SWT.FocusIn, new GenericListener());
currentCol += 2;
} else if (key.equals("version")) {
newLayout(attributesComposite, 1, name, PROPERTY);
versionCombo = new Combo(attributesComposite, SWT.NO_BACKGROUND | SWT.MULTI | SWT.V_SCROLL
| SWT.READ_ONLY);
versionCombo.setFont(TEXT_FONT);
versionCombo.setLayoutData(data);
versionCombo.setBackground(background);
Set<String> s = values.keySet();
String[] a = s.toArray(new String[s.size()]);
Arrays.sort(a);
for (int i = 0; i < a.length; i++) {
versionCombo.add(a[i]);
}
versionCombo.select(versionCombo.indexOf(value));
versionCombo.addListener(SWT.Modify, this);
versionCombo.addListener(SWT.FocusIn, new GenericListener());
comboListenerMap.put(versionCombo, name);
currentCol += 2;
} else if (key.equals("priority")) {
newLayout(attributesComposite, 1, name, PROPERTY);
priorityCombo = new Combo(attributesComposite, SWT.NO_BACKGROUND | SWT.MULTI | SWT.V_SCROLL
| SWT.READ_ONLY);
priorityCombo.setFont(TEXT_FONT);
priorityCombo.setLayoutData(data);
priorityCombo.setBackground(background);
Set<String> s = values.keySet();
String[] a = s.toArray(new String[s.size()]);
Arrays.sort(a);
for (int i = 0; i < a.length; i++) {
priorityCombo.add(a[i]);
}
priorityCombo.select(priorityCombo.indexOf(value));
priorityCombo.addListener(SWT.Modify, this);
priorityCombo.addListener(SWT.FocusIn, new GenericListener());
comboListenerMap.put(priorityCombo, name);
currentCol += 2;
} else if (key.equals("bug_severity")) {
newLayout(attributesComposite, 1, name, PROPERTY);
severityCombo = new Combo(attributesComposite, SWT.NO_BACKGROUND | SWT.MULTI | SWT.V_SCROLL
| SWT.READ_ONLY);
severityCombo.setFont(TEXT_FONT);
severityCombo.setLayoutData(data);
severityCombo.setBackground(background);
Set<String> s = values.keySet();
String[] a = s.toArray(new String[s.size()]);
Arrays.sort(a);
for (int i = 0; i < a.length; i++) {
severityCombo.add(a[i]);
}
severityCombo.select(severityCombo.indexOf(value));
severityCombo.addListener(SWT.Modify, this);
severityCombo.addListener(SWT.FocusIn, new GenericListener());
comboListenerMap.put(severityCombo, name);
currentCol += 2;
} else if (key.equals("target_milestone")) {
newLayout(attributesComposite, 1, name, PROPERTY);
milestoneCombo = new Combo(attributesComposite, SWT.NO_BACKGROUND | SWT.MULTI | SWT.V_SCROLL
| SWT.READ_ONLY);
milestoneCombo.setFont(TEXT_FONT);
milestoneCombo.setLayoutData(data);
milestoneCombo.setBackground(background);
Set<String> s = values.keySet();
String[] a = s.toArray(new String[s.size()]);
Arrays.sort(a);
for (int i = 0; i < a.length; i++) {
milestoneCombo.add(a[i]);
}
milestoneCombo.select(milestoneCombo.indexOf(value));
milestoneCombo.addListener(SWT.Modify, this);
milestoneCombo.addListener(SWT.FocusIn, new GenericListener());
comboListenerMap.put(milestoneCombo, name);
currentCol += 2;
} else if (key.equals("rep_platform")) {
newLayout(attributesComposite, 1, name, PROPERTY);
platformCombo = new Combo(attributesComposite, SWT.NO_BACKGROUND | SWT.MULTI | SWT.V_SCROLL
| SWT.READ_ONLY);
platformCombo.setFont(TEXT_FONT);
platformCombo.setLayoutData(data);
platformCombo.setBackground(background);
Set<String> s = values.keySet();
String[] a = s.toArray(new String[s.size()]);
Arrays.sort(a);
for (int i = 0; i < a.length; i++) {
platformCombo.add(a[i]);
}
platformCombo.select(platformCombo.indexOf(value));
platformCombo.addListener(SWT.Modify, this);
platformCombo.addListener(SWT.FocusIn, new GenericListener());
comboListenerMap.put(platformCombo, name);
currentCol += 2;
} else if (key.equals("product")) {
newLayout(attributesComposite, 1, name, PROPERTY);
newLayout(attributesComposite, 1, value, VALUE).addListener(SWT.FocusIn, new GenericListener());
currentCol += 2;
} else if (key.equals("assigned_to")) {
newLayout(attributesComposite, 1, name, PROPERTY);
assignedTo = new Text(attributesComposite, SWT.BORDER | SWT.SINGLE | SWT.WRAP);
assignedTo.setFont(TEXT_FONT);
assignedTo.setText(value);
data = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
data.horizontalSpan = 1;
assignedTo.setLayoutData(data);
assignedTo.addListener(SWT.KeyUp, new Listener() {
public void handleEvent(Event event) {
String sel = assignedTo.getText();
Attribute a = getBug().getAttribute("Assign To");
if (!(a.getNewValue().equals(sel))) {
a.setNewValue(sel);
changeDirtyStatus(true);
}
}
});
assignedTo.addListener(SWT.FocusIn, new GenericListener());
currentCol += 2;
} else if (key.equals("component")) {
newLayout(attributesComposite, 1, name, PROPERTY);
componentCombo = new Combo(attributesComposite, SWT.NO_BACKGROUND | SWT.MULTI | SWT.V_SCROLL
| SWT.READ_ONLY);
componentCombo.setFont(TEXT_FONT);
componentCombo.setLayoutData(data);
componentCombo.setBackground(background);
Set<String> s = values.keySet();
String[] a = s.toArray(new String[s.size()]);
Arrays.sort(a);
for (int i = 0; i < a.length; i++) {
componentCombo.add(a[i]);
}
componentCombo.select(componentCombo.indexOf(value));
componentCombo.addListener(SWT.Modify, this);
componentCombo.addListener(SWT.FocusIn, new GenericListener());
comboListenerMap.put(componentCombo, name);
currentCol += 2;
} else if (name.equals("Summary")) {
// Don't show the summary here.
continue;
} else if (values.isEmpty()) {
newLayout(attributesComposite, 1, name, PROPERTY);
newLayout(attributesComposite, 1, value, VALUE).addListener(SWT.FocusIn, new GenericListener());
currentCol += 2;
}
if (currentCol > attributesLayout.numColumns) {
currentCol -= attributesLayout.numColumns;
}
}
// End Populate Attributes
// make sure that we are in the first column
if (currentCol > 1) {
while (currentCol <= attributesLayout.numColumns) {
newLayout(attributesComposite, 1, "", PROPERTY);
currentCol++;
}
}
// URL, Keywords, Summary Text Fields
addUrlText(url, attributesComposite);
// keywords text field (not editable)
addKeywordsList(keywords, attributesComposite);
if (ccValue != null) {
addCCList(ccValue, attributesComposite);
}
addSummaryText(attributesComposite);
// End URL, Keywords, Summary Text Fields
}
|
diff --git a/src/com/roshka/raf/params/ParametersProcessor.java b/src/com/roshka/raf/params/ParametersProcessor.java
index 5f1cd8d..db50d21 100644
--- a/src/com/roshka/raf/params/ParametersProcessor.java
+++ b/src/com/roshka/raf/params/ParametersProcessor.java
@@ -1,122 +1,122 @@
package com.roshka.raf.params;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import com.roshka.raf.exception.RAFException;
import com.roshka.raf.refl.RAFParameter;
import com.roshka.raf.route.Route;
public class ParametersProcessor {
private HttpServletRequest req;
private Route route;
public ParametersProcessor(HttpServletRequest req, Route route) {
this.req = req;
this.route = route;
}
private Object getNullOrZero(Class<?> clazz)
{
Object ret = null;
if (clazz.isPrimitive()) {
if (clazz.equals(Byte.TYPE)) {
ret = (byte)0;
} else if (clazz.equals(Short.TYPE)) {
ret = (short)0;
} else if (clazz.equals(Integer.TYPE)) {
ret = 0;
} else if (clazz.equals(Long.TYPE)) {
ret = 0L;
} else if (clazz.equals(Float.TYPE)) {
ret = 0.0f;
} else if (clazz.equals(Double.TYPE)) {
ret = 0.0;
} else if (clazz.equals(Boolean.TYPE)) {
ret = false;
} else if (clazz.equals(Character.TYPE)) {
ret = '\0';
}
} else {
ret = null;
}
return ret;
}
private Object getValue(Class<?> clazz, RAFParameter rp, String value)
throws RAFException
{
String parameterName;
parameterName = rp.getParameterName();
Object ret = null;
if (clazz.isPrimitive()) {
if (clazz.equals(Byte.TYPE)) {
ret = NumberProcessor.parseByte(parameterName, value);
} else if (clazz.equals(Short.TYPE)) {
ret = NumberProcessor.parseShort(parameterName, value);
} else if (clazz.equals(Integer.TYPE)) {
ret = NumberProcessor.parseInt(parameterName, value);
} else if (clazz.equals(Long.TYPE)) {
- ret = NumberProcessor.parseShort(parameterName, value);
+ ret = NumberProcessor.parseLong(parameterName, value);
} else if (clazz.equals(Float.TYPE)) {
ret = NumberProcessor.parseFloat(parameterName, value);
} else if (clazz.equals(Double.TYPE)) {
ret = NumberProcessor.parseDouble(parameterName, value);
} else if (clazz.equals(Boolean.TYPE)) {
ret = BooleanProcessor.parseBoolean(parameterName, value);
} else if (clazz.equals(Character.TYPE)) {
ret = CharacterProcessor.parseCharacter(parameterName, value);
}
} else {
if (clazz.equals(String.class)) {
ret = value;
} else if (clazz.equals(BigDecimal.class)) {
ret = NumberProcessor.parseBigDecimal(parameterName, value);
} else if (clazz.equals(BigInteger.class)) {
ret = NumberProcessor.parseBigInteger(parameterName, value);
} else if (clazz.equals(java.util.Date.class)) {
ret = DateProcessor.parseUtilDate(parameterName, rp.getDateFormat(), value);
} else if (clazz.equals(java.sql.Date.class)) {
ret = DateProcessor.parseSqlDate(parameterName, rp.getDateFormat(), value);
} else if (clazz.isAssignableFrom(java.util.Calendar.class)) {
ret = DateProcessor.parseCalendar(parameterName, rp.getDateFormat(), value);
}
}
return ret;
}
public Object[] getParameters()
throws RAFException
{
List<RAFParameter> rafParameters = route.getActionMethod().getParameters();
List<Object> objects = new ArrayList<Object>();
for (RAFParameter rafParameter : rafParameters) {
String paramValue = req.getParameter(rafParameter.getParameterName());
// check mandatory parameter
if (paramValue == null && rafParameter.isMandatory()) {
throw new RAFException(RAFException.ERRCODE_INVALID_PARAMETER_VALUE, String.format("Parameter %s is mandatory", rafParameter.getParameterName()));
} else if (paramValue != null) {
objects.add(getValue(rafParameter.getClazz(), rafParameter, paramValue));
} else {
// add null (or default value parameter)
if (!rafParameter.getDefaultValue().equalsIgnoreCase(Globals.DEFAULT_UNASSIGNED_PARAMETER)) {
objects.add(getValue(rafParameter.getClazz(), rafParameter, rafParameter.getDefaultValue()));
} else {
objects.add(getNullOrZero(rafParameter.getClazz()));
}
}
}
return objects.toArray(new Object[0]);
}
}
| true | true | private Object getValue(Class<?> clazz, RAFParameter rp, String value)
throws RAFException
{
String parameterName;
parameterName = rp.getParameterName();
Object ret = null;
if (clazz.isPrimitive()) {
if (clazz.equals(Byte.TYPE)) {
ret = NumberProcessor.parseByte(parameterName, value);
} else if (clazz.equals(Short.TYPE)) {
ret = NumberProcessor.parseShort(parameterName, value);
} else if (clazz.equals(Integer.TYPE)) {
ret = NumberProcessor.parseInt(parameterName, value);
} else if (clazz.equals(Long.TYPE)) {
ret = NumberProcessor.parseShort(parameterName, value);
} else if (clazz.equals(Float.TYPE)) {
ret = NumberProcessor.parseFloat(parameterName, value);
} else if (clazz.equals(Double.TYPE)) {
ret = NumberProcessor.parseDouble(parameterName, value);
} else if (clazz.equals(Boolean.TYPE)) {
ret = BooleanProcessor.parseBoolean(parameterName, value);
} else if (clazz.equals(Character.TYPE)) {
ret = CharacterProcessor.parseCharacter(parameterName, value);
}
} else {
if (clazz.equals(String.class)) {
ret = value;
} else if (clazz.equals(BigDecimal.class)) {
ret = NumberProcessor.parseBigDecimal(parameterName, value);
} else if (clazz.equals(BigInteger.class)) {
ret = NumberProcessor.parseBigInteger(parameterName, value);
} else if (clazz.equals(java.util.Date.class)) {
ret = DateProcessor.parseUtilDate(parameterName, rp.getDateFormat(), value);
} else if (clazz.equals(java.sql.Date.class)) {
ret = DateProcessor.parseSqlDate(parameterName, rp.getDateFormat(), value);
} else if (clazz.isAssignableFrom(java.util.Calendar.class)) {
ret = DateProcessor.parseCalendar(parameterName, rp.getDateFormat(), value);
}
}
return ret;
}
| private Object getValue(Class<?> clazz, RAFParameter rp, String value)
throws RAFException
{
String parameterName;
parameterName = rp.getParameterName();
Object ret = null;
if (clazz.isPrimitive()) {
if (clazz.equals(Byte.TYPE)) {
ret = NumberProcessor.parseByte(parameterName, value);
} else if (clazz.equals(Short.TYPE)) {
ret = NumberProcessor.parseShort(parameterName, value);
} else if (clazz.equals(Integer.TYPE)) {
ret = NumberProcessor.parseInt(parameterName, value);
} else if (clazz.equals(Long.TYPE)) {
ret = NumberProcessor.parseLong(parameterName, value);
} else if (clazz.equals(Float.TYPE)) {
ret = NumberProcessor.parseFloat(parameterName, value);
} else if (clazz.equals(Double.TYPE)) {
ret = NumberProcessor.parseDouble(parameterName, value);
} else if (clazz.equals(Boolean.TYPE)) {
ret = BooleanProcessor.parseBoolean(parameterName, value);
} else if (clazz.equals(Character.TYPE)) {
ret = CharacterProcessor.parseCharacter(parameterName, value);
}
} else {
if (clazz.equals(String.class)) {
ret = value;
} else if (clazz.equals(BigDecimal.class)) {
ret = NumberProcessor.parseBigDecimal(parameterName, value);
} else if (clazz.equals(BigInteger.class)) {
ret = NumberProcessor.parseBigInteger(parameterName, value);
} else if (clazz.equals(java.util.Date.class)) {
ret = DateProcessor.parseUtilDate(parameterName, rp.getDateFormat(), value);
} else if (clazz.equals(java.sql.Date.class)) {
ret = DateProcessor.parseSqlDate(parameterName, rp.getDateFormat(), value);
} else if (clazz.isAssignableFrom(java.util.Calendar.class)) {
ret = DateProcessor.parseCalendar(parameterName, rp.getDateFormat(), value);
}
}
return ret;
}
|
diff --git a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/EclipseGeneratorApplication.java b/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/EclipseGeneratorApplication.java
index 0703985ca..bb632d262 100644
--- a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/EclipseGeneratorApplication.java
+++ b/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/EclipseGeneratorApplication.java
@@ -1,435 +1,429 @@
/*******************************************************************************
* Copyright (c) 2007, 2008 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.equinox.internal.p2.metadata.generator;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.equinox.app.IApplication;
import org.eclipse.equinox.app.IApplicationContext;
import org.eclipse.equinox.internal.p2.artifact.repository.ArtifactRepositoryManager;
import org.eclipse.equinox.internal.p2.core.ProvisioningEventBus;
import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper;
import org.eclipse.equinox.internal.p2.metadata.repository.MetadataRepositoryManager;
import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository;
import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepositoryManager;
import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException;
import org.eclipse.equinox.internal.provisional.p2.core.eventbus.IProvisioningEventBus;
import org.eclipse.equinox.internal.provisional.p2.core.repository.IRepository;
import org.eclipse.equinox.internal.provisional.p2.metadata.generator.EclipseInstallGeneratorInfoProvider;
import org.eclipse.equinox.internal.provisional.p2.metadata.generator.Generator;
import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository;
import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager;
import org.eclipse.osgi.util.NLS;
import org.osgi.framework.ServiceRegistration;
public class EclipseGeneratorApplication implements IApplication {
// The mapping rules for in-place generation need to construct paths into the structure
// of an eclipse installation; in the future the default artifact mapping declared in
// SimpleArtifactRepository may change, for example, to not have a 'bundles' directory
// instead of a 'plugins' directory, so a separate constant is defined and used here.
static final private String[][] INPLACE_MAPPING_RULES = { {"(& (classifier=osgi.bundle) (format=packed)", "${repoUrl}/features/${id}_${version}.jar.pack.gz"}, //$NON-NLS-1$//$NON-NLS-2$
{"(& (classifier=org.eclipse.update.feature))", "${repoUrl}/features/${id}_${version}.jar"}, //$NON-NLS-1$//$NON-NLS-2$
{"(& (classifier=osgi.bundle))", "${repoUrl}/plugins/${id}_${version}.jar"}, //$NON-NLS-1$//$NON-NLS-2$
{"(& (classifier=binary))", "${repoUrl}/binary/${id}_${version}"}}; //$NON-NLS-1$//$NON-NLS-2$
static final public String PUBLISH_PACK_FILES_AS_SIBLINGS = "publishPackFilesAsSiblings"; //$NON-NLS-1$
private ArtifactRepositoryManager defaultArtifactManager;
private ServiceRegistration registrationDefaultArtifactManager;
private MetadataRepositoryManager defaultMetadataManager;
private ServiceRegistration registrationDefaultMetadataManager;
private IProvisioningEventBus bus;
private ServiceRegistration registrationBus;
private Generator.GeneratorResult incrementalResult = null;
private boolean generateRootIU = true;
private String metadataLocation;
private String metadataRepoName;
private String artifactLocation;
private String artifactRepoName;
private String operation;
private String argument;
private String features;
private String bundles;
private String base;
//whether repository xml files should be compressed
private String compress = "false"; //$NON-NLS-1$
private File getExecutableName(String base, EclipseInstallGeneratorInfoProvider provider) {
File location = provider.getExecutableLocation();
if (location == null)
return new File(base, EclipseInstallGeneratorInfoProvider.getDefaultExecutableName(null));
if (location.isAbsolute())
return location;
return new File(base, location.getPath());
}
private void initialize(EclipseInstallGeneratorInfoProvider provider) throws ProvisionException {
if ("-source".equalsIgnoreCase(operation)) //$NON-NLS-1$
provider.initialize(new File(argument));
else if ("-inplace".equalsIgnoreCase(operation)) { //$NON-NLS-1$
provider.initialize(new File(argument));
initializeForInplace(provider);
} else if ("-config".equalsIgnoreCase(operation)) { //$NON-NLS-1$
provider.initialize(new File(argument), new File(argument, "configuration"), getExecutableName(argument, provider), null, null); //$NON-NLS-1$
} else if ("-updateSite".equalsIgnoreCase(operation)) { //$NON-NLS-1$
provider.setAddDefaultIUs(false);
provider.initialize(new File(argument), null, null, new File[] {new File(argument, "plugins")}, new File(argument, "features")); //$NON-NLS-1$ //$NON-NLS-2$
initializeForInplace(provider);
} else {
// base is set but we expect everything else to have been set using
// explicit args. Note that if we are coming in via an Ant task, we have
// to ensure all the values are passed in
if (base != null) {
File[] bundlesLocation = bundles == null ? null : new File[] {new File(bundles)};
File featuresLocation = features == null ? null : new File(features);
provider.initialize(new File(base), null, null, bundlesLocation, featuresLocation);
}
}
initializeRepositories(provider);
}
private void initializeArtifactRepository(EclipseInstallGeneratorInfoProvider provider) throws ProvisionException {
if (artifactLocation == null)
return;
IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(Activator.context, IArtifactRepositoryManager.class.getName());
URL location;
try {
location = new URL(artifactLocation);
} catch (MalformedURLException e) {
throw new IllegalArgumentException(NLS.bind(Messages.exception_artifactRepoLocationURL, artifactLocation));
}
- String repositoryName = artifactRepoName != null ? artifactRepoName : artifactLocation + " - artifacts"; //$NON-NLS-1$
+ String repositoryName = (artifactRepoName != null && artifactRepoName.length() > 0) ? artifactRepoName : artifactLocation + " - artifacts"; //$NON-NLS-1$
Map properties = new HashMap(1);
properties.put(IRepository.PROP_COMPRESSED, compress);
if (provider.reuseExistingPack200Files())
properties.put(PUBLISH_PACK_FILES_AS_SIBLINGS, Boolean.TRUE.toString());
IArtifactRepository result = null;
try {
result = manager.createRepository(location, repositoryName, IArtifactRepositoryManager.TYPE_SIMPLE_REPOSITORY, properties);
manager.removeRepository(location);
provider.setArtifactRepository(result);
- // TODO is this needed?
- if (artifactRepoName != null)
- result.setName(artifactRepoName);
return;
} catch (ProvisionException e) {
//fall through a load existing repo
}
IArtifactRepository repository = manager.loadRepository(location, null);
if (repository != null) {
manager.removeRepository(location);
if (!repository.isModifiable())
throw new IllegalArgumentException(NLS.bind(Messages.exception_artifactRepoNotWritable, location));
provider.setArtifactRepository(repository);
if (provider.reuseExistingPack200Files())
repository.setProperty(PUBLISH_PACK_FILES_AS_SIBLINGS, "true"); //$NON-NLS-1$
if (!provider.append())
repository.removeAll();
}
return;
}
public void initializeForInplace(EclipseInstallGeneratorInfoProvider provider) {
File location = provider.getBaseLocation();
if (location == null)
location = provider.getBundleLocations()[0];
try {
metadataLocation = location.toURL().toExternalForm();
artifactLocation = location.toURL().toExternalForm();
} catch (MalformedURLException e) {
// ought not happen...
}
provider.setPublishArtifactRepository(true);
provider.setPublishArtifacts(false);
provider.setMappingRules(INPLACE_MAPPING_RULES);
}
private void initializeMetadataRepository(EclipseInstallGeneratorInfoProvider provider) throws ProvisionException {
URL location;
try {
location = new URL(metadataLocation);
} catch (MalformedURLException e) {
throw new IllegalArgumentException(NLS.bind(Messages.exception_metadataRepoLocationURL, artifactLocation));
}
// First try to create a simple repo, this will fail if one already exists
// We try creating a repo first instead of just loading what is there because we don't want a repo based
// on a site.xml if there is one there.
- String repositoryName = metadataRepoName == null ? metadataLocation + " - metadata" : metadataRepoName; //$NON-NLS-1$
+ String repositoryName = (metadataRepoName == null || metadataRepoName.length() == 0) ? metadataLocation + " - metadata" : metadataRepoName; //$NON-NLS-1$
Map properties = new HashMap(1);
properties.put(IRepository.PROP_COMPRESSED, compress);
IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(Activator.context, IMetadataRepositoryManager.class.getName());
try {
IMetadataRepository result = manager.createRepository(location, repositoryName, IMetadataRepositoryManager.TYPE_SIMPLE_REPOSITORY, properties);
manager.removeRepository(location);
- // TODO is this needed?
- if (metadataRepoName != null)
- result.setName(metadataRepoName);
provider.setMetadataRepository(result);
return;
} catch (ProvisionException e) {
//fall through and load the existing repo
}
IMetadataRepository repository = manager.loadRepository(location, null);
if (repository != null) {
manager.removeRepository(location);
// don't set the compress flag here because we don't want to change the format
// of an already existing repository
if (!repository.isModifiable())
throw new IllegalArgumentException(NLS.bind(Messages.exception_metadataRepoNotWritable, location));
provider.setMetadataRepository(repository);
if (!provider.append())
repository.removeAll();
return;
}
}
private void initializeRepositories(EclipseInstallGeneratorInfoProvider provider) throws ProvisionException {
initializeArtifactRepository(provider);
initializeMetadataRepository(provider);
}
public void setCompress(String value) {
if (Boolean.valueOf(value).booleanValue())
compress = "true"; //$NON-NLS-1$
}
public void processCommandLineArguments(String[] args, EclipseInstallGeneratorInfoProvider provider) throws Exception {
if (args == null)
return;
for (int i = 0; i < args.length; i++) {
// check for args without parameters (i.e., a flag arg)
if (args[i].equalsIgnoreCase("-publishArtifacts") || args[i].equalsIgnoreCase("-pa")) //$NON-NLS-1$ //$NON-NLS-2$
provider.setPublishArtifacts(true);
if (args[i].equalsIgnoreCase("-publishArtifactRepository") || args[i].equalsIgnoreCase("-par")) //$NON-NLS-1$ //$NON-NLS-2$
provider.setPublishArtifactRepository(true);
if (args[i].equalsIgnoreCase("-append")) //$NON-NLS-1$
provider.setAppend(true);
if (args[i].equalsIgnoreCase("-noDefaultIUs")) //$NON-NLS-1$
provider.setAddDefaultIUs(false);
if (args[i].equalsIgnoreCase("-compress")) //$NON-NLS-1$
compress = "true"; //$NON-NLS-1$
if (args[i].equalsIgnoreCase("-reusePack200Files")) //$NON-NLS-1$
provider.reuseExistingPack200Files(true);
// check for args with parameters. If we are at the last argument or if the next one
// has a '-' as the first character, then we can't have an arg with a parm so continue.
if (i == args.length - 1 || args[i + 1].startsWith("-")) //$NON-NLS-1$
continue;
String arg = args[++i];
if (args[i - 1].equalsIgnoreCase("-source")) { //$NON-NLS-1$
operation = args[i - 1];
argument = arg;
}
if (args[i - 1].equalsIgnoreCase("-inplace")) { //$NON-NLS-1$
operation = args[i - 1];
argument = arg;
}
if (args[i - 1].equalsIgnoreCase("-config")) { //$NON-NLS-1$
operation = args[i - 1];
argument = arg;
}
if (args[i - 1].equalsIgnoreCase("-updateSite")) { //$NON-NLS-1$
operation = args[i - 1];
argument = arg;
}
if (args[i - 1].equalsIgnoreCase("-exe")) //$NON-NLS-1$
provider.setExecutableLocation(arg);
if (args[i - 1].equalsIgnoreCase("-launcherConfig")) //$NON-NLS-1$
provider.setLauncherConfig(arg);
if (args[i - 1].equalsIgnoreCase("-metadataRepository") || args[i - 1].equalsIgnoreCase("-mr")) //$NON-NLS-1$ //$NON-NLS-2$
metadataLocation = arg;
if (args[i - 1].equalsIgnoreCase("-metadataRepositoryName")) //$NON-NLS-1$
metadataRepoName = arg;
if (args[i - 1].equalsIgnoreCase("-artifactRepository") | args[i - 1].equalsIgnoreCase("-ar")) //$NON-NLS-1$ //$NON-NLS-2$
artifactLocation = arg;
if (args[i - 1].equalsIgnoreCase("-artifactRepositoryName")) //$NON-NLS-1$
artifactRepoName = arg;
if (args[i - 1].equalsIgnoreCase("-flavor")) //$NON-NLS-1$
provider.setFlavor(arg);
if (args[i - 1].equalsIgnoreCase("-productFile")) //$NON-NLS-1$
provider.setProductFile(arg);
if (args[i - 1].equalsIgnoreCase("-features")) //$NON-NLS-1$
features = arg;
if (args[i - 1].equalsIgnoreCase("-bundles")) //$NON-NLS-1$
bundles = arg;
if (args[i - 1].equalsIgnoreCase("-base")) //$NON-NLS-1$
base = arg;
if (args[i - 1].equalsIgnoreCase("-root")) //$NON-NLS-1$
provider.setRootId(arg);
if (args[i - 1].equalsIgnoreCase("-rootVersion")) //$NON-NLS-1$
provider.setRootVersion(arg);
if (args[i - 1].equalsIgnoreCase("-p2.os")) //$NON-NLS-1$
provider.setOS(arg);
if (args[i - 1].equalsIgnoreCase("-site")) //$NON-NLS-1$
provider.setSiteLocation(new URL(arg));
}
}
private void registerDefaultArtifactRepoManager() {
if (ServiceHelper.getService(Activator.getContext(), IArtifactRepositoryManager.class.getName()) == null) {
defaultArtifactManager = new ArtifactRepositoryManager();
registrationDefaultArtifactManager = Activator.getContext().registerService(IArtifactRepositoryManager.class.getName(), defaultArtifactManager, null);
}
}
private void registerDefaultMetadataRepoManager() {
if (ServiceHelper.getService(Activator.getContext(), IMetadataRepositoryManager.class.getName()) == null) {
defaultMetadataManager = new MetadataRepositoryManager();
registrationDefaultMetadataManager = Activator.getContext().registerService(IMetadataRepositoryManager.class.getName(), defaultMetadataManager, null);
}
}
private void registerEventBus() {
if (ServiceHelper.getService(Activator.getContext(), IProvisioningEventBus.SERVICE_NAME) == null) {
bus = new ProvisioningEventBus();
registrationBus = Activator.getContext().registerService(IProvisioningEventBus.SERVICE_NAME, bus, null);
}
}
public Object run(String args[]) throws Exception {
EclipseInstallGeneratorInfoProvider provider = new EclipseInstallGeneratorInfoProvider();
processCommandLineArguments(args, provider);
Object result = run(provider);
if (result != IApplication.EXIT_OK)
for (int i = 0; i < args.length; i++)
System.out.println(args[i]);
return result;
}
public Object run(EclipseInstallGeneratorInfoProvider provider) throws Exception {
registerEventBus();
registerDefaultMetadataRepoManager();
registerDefaultArtifactRepoManager();
initialize(provider);
if (provider.getBaseLocation() == null && provider.getProductFile() == null && !generateRootIU) {
System.out.println(Messages.exception_baseLocationNotSpecified);
return new Integer(-1);
}
System.out.println(NLS.bind(Messages.message_generatingMetadata, provider.getBaseLocation()));
long before = System.currentTimeMillis();
IStatus result = generate(provider);
long after = System.currentTimeMillis();
if (result.isOK()) {
System.out.println(NLS.bind(Messages.message_generationCompleted, String.valueOf((after - before) / 1000)));
return IApplication.EXIT_OK;
}
System.out.println(result);
return new Integer(1);
}
protected IStatus generate(EclipseInstallGeneratorInfoProvider provider) {
Generator generator = new Generator(provider);
if (incrementalResult != null)
generator.setIncrementalResult(incrementalResult);
generator.setGenerateRootIU(generateRootIU);
IStatus result = generator.generate();
incrementalResult = null;
return result;
}
public Object start(IApplicationContext context) throws Exception {
return run((String[]) context.getArguments().get("application.args")); //$NON-NLS-1$
}
public void stop() {
if (registrationDefaultMetadataManager != null) {
registrationDefaultMetadataManager.unregister();
registrationDefaultMetadataManager = null;
}
if (registrationDefaultArtifactManager != null) {
registrationDefaultArtifactManager.unregister();
registrationDefaultArtifactManager = null;
}
if (registrationBus != null) {
registrationBus.unregister();
registrationBus = null;
}
}
public void setBase(String base) {
this.base = base;
}
public void setArtifactLocation(String location) {
this.artifactLocation = location;
}
public void setBundles(String bundles) {
this.bundles = bundles;
}
public void setOperation(String operation, String argument) {
this.operation = operation;
this.argument = argument;
}
public void setFeatures(String features) {
this.features = features;
}
public void setMetadataLocation(String location) {
this.metadataLocation = location;
}
public void setMetadataRepositoryName(String name) {
this.metadataRepoName = name;
}
public void setArtifactRepositoryName(String name) {
this.artifactRepoName = name;
}
public void setIncrementalResult(Generator.GeneratorResult ius) {
this.incrementalResult = ius;
}
public void setGeneratorRootIU(boolean b) {
this.generateRootIU = b;
}
}
| false | true | private void initialize(EclipseInstallGeneratorInfoProvider provider) throws ProvisionException {
if ("-source".equalsIgnoreCase(operation)) //$NON-NLS-1$
provider.initialize(new File(argument));
else if ("-inplace".equalsIgnoreCase(operation)) { //$NON-NLS-1$
provider.initialize(new File(argument));
initializeForInplace(provider);
} else if ("-config".equalsIgnoreCase(operation)) { //$NON-NLS-1$
provider.initialize(new File(argument), new File(argument, "configuration"), getExecutableName(argument, provider), null, null); //$NON-NLS-1$
} else if ("-updateSite".equalsIgnoreCase(operation)) { //$NON-NLS-1$
provider.setAddDefaultIUs(false);
provider.initialize(new File(argument), null, null, new File[] {new File(argument, "plugins")}, new File(argument, "features")); //$NON-NLS-1$ //$NON-NLS-2$
initializeForInplace(provider);
} else {
// base is set but we expect everything else to have been set using
// explicit args. Note that if we are coming in via an Ant task, we have
// to ensure all the values are passed in
if (base != null) {
File[] bundlesLocation = bundles == null ? null : new File[] {new File(bundles)};
File featuresLocation = features == null ? null : new File(features);
provider.initialize(new File(base), null, null, bundlesLocation, featuresLocation);
}
}
initializeRepositories(provider);
}
private void initializeArtifactRepository(EclipseInstallGeneratorInfoProvider provider) throws ProvisionException {
if (artifactLocation == null)
return;
IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(Activator.context, IArtifactRepositoryManager.class.getName());
URL location;
try {
location = new URL(artifactLocation);
} catch (MalformedURLException e) {
throw new IllegalArgumentException(NLS.bind(Messages.exception_artifactRepoLocationURL, artifactLocation));
}
String repositoryName = artifactRepoName != null ? artifactRepoName : artifactLocation + " - artifacts"; //$NON-NLS-1$
Map properties = new HashMap(1);
properties.put(IRepository.PROP_COMPRESSED, compress);
if (provider.reuseExistingPack200Files())
properties.put(PUBLISH_PACK_FILES_AS_SIBLINGS, Boolean.TRUE.toString());
IArtifactRepository result = null;
try {
result = manager.createRepository(location, repositoryName, IArtifactRepositoryManager.TYPE_SIMPLE_REPOSITORY, properties);
manager.removeRepository(location);
provider.setArtifactRepository(result);
// TODO is this needed?
if (artifactRepoName != null)
result.setName(artifactRepoName);
return;
} catch (ProvisionException e) {
//fall through a load existing repo
}
IArtifactRepository repository = manager.loadRepository(location, null);
if (repository != null) {
manager.removeRepository(location);
if (!repository.isModifiable())
throw new IllegalArgumentException(NLS.bind(Messages.exception_artifactRepoNotWritable, location));
provider.setArtifactRepository(repository);
if (provider.reuseExistingPack200Files())
repository.setProperty(PUBLISH_PACK_FILES_AS_SIBLINGS, "true"); //$NON-NLS-1$
if (!provider.append())
repository.removeAll();
}
return;
}
public void initializeForInplace(EclipseInstallGeneratorInfoProvider provider) {
File location = provider.getBaseLocation();
if (location == null)
location = provider.getBundleLocations()[0];
try {
metadataLocation = location.toURL().toExternalForm();
artifactLocation = location.toURL().toExternalForm();
} catch (MalformedURLException e) {
// ought not happen...
}
provider.setPublishArtifactRepository(true);
provider.setPublishArtifacts(false);
provider.setMappingRules(INPLACE_MAPPING_RULES);
}
private void initializeMetadataRepository(EclipseInstallGeneratorInfoProvider provider) throws ProvisionException {
URL location;
try {
location = new URL(metadataLocation);
} catch (MalformedURLException e) {
throw new IllegalArgumentException(NLS.bind(Messages.exception_metadataRepoLocationURL, artifactLocation));
}
// First try to create a simple repo, this will fail if one already exists
// We try creating a repo first instead of just loading what is there because we don't want a repo based
// on a site.xml if there is one there.
String repositoryName = metadataRepoName == null ? metadataLocation + " - metadata" : metadataRepoName; //$NON-NLS-1$
Map properties = new HashMap(1);
properties.put(IRepository.PROP_COMPRESSED, compress);
IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(Activator.context, IMetadataRepositoryManager.class.getName());
try {
IMetadataRepository result = manager.createRepository(location, repositoryName, IMetadataRepositoryManager.TYPE_SIMPLE_REPOSITORY, properties);
manager.removeRepository(location);
// TODO is this needed?
if (metadataRepoName != null)
result.setName(metadataRepoName);
provider.setMetadataRepository(result);
return;
} catch (ProvisionException e) {
//fall through and load the existing repo
}
IMetadataRepository repository = manager.loadRepository(location, null);
if (repository != null) {
manager.removeRepository(location);
// don't set the compress flag here because we don't want to change the format
// of an already existing repository
if (!repository.isModifiable())
throw new IllegalArgumentException(NLS.bind(Messages.exception_metadataRepoNotWritable, location));
provider.setMetadataRepository(repository);
if (!provider.append())
repository.removeAll();
return;
}
}
private void initializeRepositories(EclipseInstallGeneratorInfoProvider provider) throws ProvisionException {
initializeArtifactRepository(provider);
initializeMetadataRepository(provider);
}
public void setCompress(String value) {
if (Boolean.valueOf(value).booleanValue())
compress = "true"; //$NON-NLS-1$
}
public void processCommandLineArguments(String[] args, EclipseInstallGeneratorInfoProvider provider) throws Exception {
if (args == null)
return;
for (int i = 0; i < args.length; i++) {
// check for args without parameters (i.e., a flag arg)
if (args[i].equalsIgnoreCase("-publishArtifacts") || args[i].equalsIgnoreCase("-pa")) //$NON-NLS-1$ //$NON-NLS-2$
provider.setPublishArtifacts(true);
if (args[i].equalsIgnoreCase("-publishArtifactRepository") || args[i].equalsIgnoreCase("-par")) //$NON-NLS-1$ //$NON-NLS-2$
provider.setPublishArtifactRepository(true);
if (args[i].equalsIgnoreCase("-append")) //$NON-NLS-1$
provider.setAppend(true);
if (args[i].equalsIgnoreCase("-noDefaultIUs")) //$NON-NLS-1$
provider.setAddDefaultIUs(false);
if (args[i].equalsIgnoreCase("-compress")) //$NON-NLS-1$
compress = "true"; //$NON-NLS-1$
if (args[i].equalsIgnoreCase("-reusePack200Files")) //$NON-NLS-1$
provider.reuseExistingPack200Files(true);
// check for args with parameters. If we are at the last argument or if the next one
// has a '-' as the first character, then we can't have an arg with a parm so continue.
if (i == args.length - 1 || args[i + 1].startsWith("-")) //$NON-NLS-1$
continue;
String arg = args[++i];
if (args[i - 1].equalsIgnoreCase("-source")) { //$NON-NLS-1$
operation = args[i - 1];
argument = arg;
}
if (args[i - 1].equalsIgnoreCase("-inplace")) { //$NON-NLS-1$
operation = args[i - 1];
argument = arg;
}
if (args[i - 1].equalsIgnoreCase("-config")) { //$NON-NLS-1$
operation = args[i - 1];
argument = arg;
}
if (args[i - 1].equalsIgnoreCase("-updateSite")) { //$NON-NLS-1$
operation = args[i - 1];
argument = arg;
}
if (args[i - 1].equalsIgnoreCase("-exe")) //$NON-NLS-1$
provider.setExecutableLocation(arg);
if (args[i - 1].equalsIgnoreCase("-launcherConfig")) //$NON-NLS-1$
provider.setLauncherConfig(arg);
if (args[i - 1].equalsIgnoreCase("-metadataRepository") || args[i - 1].equalsIgnoreCase("-mr")) //$NON-NLS-1$ //$NON-NLS-2$
metadataLocation = arg;
if (args[i - 1].equalsIgnoreCase("-metadataRepositoryName")) //$NON-NLS-1$
metadataRepoName = arg;
if (args[i - 1].equalsIgnoreCase("-artifactRepository") | args[i - 1].equalsIgnoreCase("-ar")) //$NON-NLS-1$ //$NON-NLS-2$
artifactLocation = arg;
if (args[i - 1].equalsIgnoreCase("-artifactRepositoryName")) //$NON-NLS-1$
artifactRepoName = arg;
if (args[i - 1].equalsIgnoreCase("-flavor")) //$NON-NLS-1$
provider.setFlavor(arg);
if (args[i - 1].equalsIgnoreCase("-productFile")) //$NON-NLS-1$
provider.setProductFile(arg);
if (args[i - 1].equalsIgnoreCase("-features")) //$NON-NLS-1$
features = arg;
if (args[i - 1].equalsIgnoreCase("-bundles")) //$NON-NLS-1$
bundles = arg;
if (args[i - 1].equalsIgnoreCase("-base")) //$NON-NLS-1$
base = arg;
if (args[i - 1].equalsIgnoreCase("-root")) //$NON-NLS-1$
provider.setRootId(arg);
if (args[i - 1].equalsIgnoreCase("-rootVersion")) //$NON-NLS-1$
provider.setRootVersion(arg);
if (args[i - 1].equalsIgnoreCase("-p2.os")) //$NON-NLS-1$
provider.setOS(arg);
if (args[i - 1].equalsIgnoreCase("-site")) //$NON-NLS-1$
provider.setSiteLocation(new URL(arg));
}
}
private void registerDefaultArtifactRepoManager() {
if (ServiceHelper.getService(Activator.getContext(), IArtifactRepositoryManager.class.getName()) == null) {
defaultArtifactManager = new ArtifactRepositoryManager();
registrationDefaultArtifactManager = Activator.getContext().registerService(IArtifactRepositoryManager.class.getName(), defaultArtifactManager, null);
}
}
private void registerDefaultMetadataRepoManager() {
if (ServiceHelper.getService(Activator.getContext(), IMetadataRepositoryManager.class.getName()) == null) {
defaultMetadataManager = new MetadataRepositoryManager();
registrationDefaultMetadataManager = Activator.getContext().registerService(IMetadataRepositoryManager.class.getName(), defaultMetadataManager, null);
}
}
private void registerEventBus() {
if (ServiceHelper.getService(Activator.getContext(), IProvisioningEventBus.SERVICE_NAME) == null) {
bus = new ProvisioningEventBus();
registrationBus = Activator.getContext().registerService(IProvisioningEventBus.SERVICE_NAME, bus, null);
}
}
public Object run(String args[]) throws Exception {
EclipseInstallGeneratorInfoProvider provider = new EclipseInstallGeneratorInfoProvider();
processCommandLineArguments(args, provider);
Object result = run(provider);
if (result != IApplication.EXIT_OK)
for (int i = 0; i < args.length; i++)
System.out.println(args[i]);
return result;
}
public Object run(EclipseInstallGeneratorInfoProvider provider) throws Exception {
registerEventBus();
registerDefaultMetadataRepoManager();
registerDefaultArtifactRepoManager();
initialize(provider);
if (provider.getBaseLocation() == null && provider.getProductFile() == null && !generateRootIU) {
System.out.println(Messages.exception_baseLocationNotSpecified);
return new Integer(-1);
}
System.out.println(NLS.bind(Messages.message_generatingMetadata, provider.getBaseLocation()));
long before = System.currentTimeMillis();
IStatus result = generate(provider);
long after = System.currentTimeMillis();
if (result.isOK()) {
System.out.println(NLS.bind(Messages.message_generationCompleted, String.valueOf((after - before) / 1000)));
return IApplication.EXIT_OK;
}
System.out.println(result);
return new Integer(1);
}
protected IStatus generate(EclipseInstallGeneratorInfoProvider provider) {
Generator generator = new Generator(provider);
if (incrementalResult != null)
generator.setIncrementalResult(incrementalResult);
generator.setGenerateRootIU(generateRootIU);
IStatus result = generator.generate();
incrementalResult = null;
return result;
}
public Object start(IApplicationContext context) throws Exception {
return run((String[]) context.getArguments().get("application.args")); //$NON-NLS-1$
}
public void stop() {
if (registrationDefaultMetadataManager != null) {
registrationDefaultMetadataManager.unregister();
registrationDefaultMetadataManager = null;
}
if (registrationDefaultArtifactManager != null) {
registrationDefaultArtifactManager.unregister();
registrationDefaultArtifactManager = null;
}
if (registrationBus != null) {
registrationBus.unregister();
registrationBus = null;
}
}
public void setBase(String base) {
this.base = base;
}
public void setArtifactLocation(String location) {
this.artifactLocation = location;
}
public void setBundles(String bundles) {
this.bundles = bundles;
}
public void setOperation(String operation, String argument) {
this.operation = operation;
this.argument = argument;
}
public void setFeatures(String features) {
this.features = features;
}
public void setMetadataLocation(String location) {
this.metadataLocation = location;
}
public void setMetadataRepositoryName(String name) {
this.metadataRepoName = name;
}
public void setArtifactRepositoryName(String name) {
this.artifactRepoName = name;
}
public void setIncrementalResult(Generator.GeneratorResult ius) {
this.incrementalResult = ius;
}
public void setGeneratorRootIU(boolean b) {
this.generateRootIU = b;
}
}
| private void initialize(EclipseInstallGeneratorInfoProvider provider) throws ProvisionException {
if ("-source".equalsIgnoreCase(operation)) //$NON-NLS-1$
provider.initialize(new File(argument));
else if ("-inplace".equalsIgnoreCase(operation)) { //$NON-NLS-1$
provider.initialize(new File(argument));
initializeForInplace(provider);
} else if ("-config".equalsIgnoreCase(operation)) { //$NON-NLS-1$
provider.initialize(new File(argument), new File(argument, "configuration"), getExecutableName(argument, provider), null, null); //$NON-NLS-1$
} else if ("-updateSite".equalsIgnoreCase(operation)) { //$NON-NLS-1$
provider.setAddDefaultIUs(false);
provider.initialize(new File(argument), null, null, new File[] {new File(argument, "plugins")}, new File(argument, "features")); //$NON-NLS-1$ //$NON-NLS-2$
initializeForInplace(provider);
} else {
// base is set but we expect everything else to have been set using
// explicit args. Note that if we are coming in via an Ant task, we have
// to ensure all the values are passed in
if (base != null) {
File[] bundlesLocation = bundles == null ? null : new File[] {new File(bundles)};
File featuresLocation = features == null ? null : new File(features);
provider.initialize(new File(base), null, null, bundlesLocation, featuresLocation);
}
}
initializeRepositories(provider);
}
private void initializeArtifactRepository(EclipseInstallGeneratorInfoProvider provider) throws ProvisionException {
if (artifactLocation == null)
return;
IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(Activator.context, IArtifactRepositoryManager.class.getName());
URL location;
try {
location = new URL(artifactLocation);
} catch (MalformedURLException e) {
throw new IllegalArgumentException(NLS.bind(Messages.exception_artifactRepoLocationURL, artifactLocation));
}
String repositoryName = (artifactRepoName != null && artifactRepoName.length() > 0) ? artifactRepoName : artifactLocation + " - artifacts"; //$NON-NLS-1$
Map properties = new HashMap(1);
properties.put(IRepository.PROP_COMPRESSED, compress);
if (provider.reuseExistingPack200Files())
properties.put(PUBLISH_PACK_FILES_AS_SIBLINGS, Boolean.TRUE.toString());
IArtifactRepository result = null;
try {
result = manager.createRepository(location, repositoryName, IArtifactRepositoryManager.TYPE_SIMPLE_REPOSITORY, properties);
manager.removeRepository(location);
provider.setArtifactRepository(result);
return;
} catch (ProvisionException e) {
//fall through a load existing repo
}
IArtifactRepository repository = manager.loadRepository(location, null);
if (repository != null) {
manager.removeRepository(location);
if (!repository.isModifiable())
throw new IllegalArgumentException(NLS.bind(Messages.exception_artifactRepoNotWritable, location));
provider.setArtifactRepository(repository);
if (provider.reuseExistingPack200Files())
repository.setProperty(PUBLISH_PACK_FILES_AS_SIBLINGS, "true"); //$NON-NLS-1$
if (!provider.append())
repository.removeAll();
}
return;
}
public void initializeForInplace(EclipseInstallGeneratorInfoProvider provider) {
File location = provider.getBaseLocation();
if (location == null)
location = provider.getBundleLocations()[0];
try {
metadataLocation = location.toURL().toExternalForm();
artifactLocation = location.toURL().toExternalForm();
} catch (MalformedURLException e) {
// ought not happen...
}
provider.setPublishArtifactRepository(true);
provider.setPublishArtifacts(false);
provider.setMappingRules(INPLACE_MAPPING_RULES);
}
private void initializeMetadataRepository(EclipseInstallGeneratorInfoProvider provider) throws ProvisionException {
URL location;
try {
location = new URL(metadataLocation);
} catch (MalformedURLException e) {
throw new IllegalArgumentException(NLS.bind(Messages.exception_metadataRepoLocationURL, artifactLocation));
}
// First try to create a simple repo, this will fail if one already exists
// We try creating a repo first instead of just loading what is there because we don't want a repo based
// on a site.xml if there is one there.
String repositoryName = (metadataRepoName == null || metadataRepoName.length() == 0) ? metadataLocation + " - metadata" : metadataRepoName; //$NON-NLS-1$
Map properties = new HashMap(1);
properties.put(IRepository.PROP_COMPRESSED, compress);
IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(Activator.context, IMetadataRepositoryManager.class.getName());
try {
IMetadataRepository result = manager.createRepository(location, repositoryName, IMetadataRepositoryManager.TYPE_SIMPLE_REPOSITORY, properties);
manager.removeRepository(location);
provider.setMetadataRepository(result);
return;
} catch (ProvisionException e) {
//fall through and load the existing repo
}
IMetadataRepository repository = manager.loadRepository(location, null);
if (repository != null) {
manager.removeRepository(location);
// don't set the compress flag here because we don't want to change the format
// of an already existing repository
if (!repository.isModifiable())
throw new IllegalArgumentException(NLS.bind(Messages.exception_metadataRepoNotWritable, location));
provider.setMetadataRepository(repository);
if (!provider.append())
repository.removeAll();
return;
}
}
private void initializeRepositories(EclipseInstallGeneratorInfoProvider provider) throws ProvisionException {
initializeArtifactRepository(provider);
initializeMetadataRepository(provider);
}
public void setCompress(String value) {
if (Boolean.valueOf(value).booleanValue())
compress = "true"; //$NON-NLS-1$
}
public void processCommandLineArguments(String[] args, EclipseInstallGeneratorInfoProvider provider) throws Exception {
if (args == null)
return;
for (int i = 0; i < args.length; i++) {
// check for args without parameters (i.e., a flag arg)
if (args[i].equalsIgnoreCase("-publishArtifacts") || args[i].equalsIgnoreCase("-pa")) //$NON-NLS-1$ //$NON-NLS-2$
provider.setPublishArtifacts(true);
if (args[i].equalsIgnoreCase("-publishArtifactRepository") || args[i].equalsIgnoreCase("-par")) //$NON-NLS-1$ //$NON-NLS-2$
provider.setPublishArtifactRepository(true);
if (args[i].equalsIgnoreCase("-append")) //$NON-NLS-1$
provider.setAppend(true);
if (args[i].equalsIgnoreCase("-noDefaultIUs")) //$NON-NLS-1$
provider.setAddDefaultIUs(false);
if (args[i].equalsIgnoreCase("-compress")) //$NON-NLS-1$
compress = "true"; //$NON-NLS-1$
if (args[i].equalsIgnoreCase("-reusePack200Files")) //$NON-NLS-1$
provider.reuseExistingPack200Files(true);
// check for args with parameters. If we are at the last argument or if the next one
// has a '-' as the first character, then we can't have an arg with a parm so continue.
if (i == args.length - 1 || args[i + 1].startsWith("-")) //$NON-NLS-1$
continue;
String arg = args[++i];
if (args[i - 1].equalsIgnoreCase("-source")) { //$NON-NLS-1$
operation = args[i - 1];
argument = arg;
}
if (args[i - 1].equalsIgnoreCase("-inplace")) { //$NON-NLS-1$
operation = args[i - 1];
argument = arg;
}
if (args[i - 1].equalsIgnoreCase("-config")) { //$NON-NLS-1$
operation = args[i - 1];
argument = arg;
}
if (args[i - 1].equalsIgnoreCase("-updateSite")) { //$NON-NLS-1$
operation = args[i - 1];
argument = arg;
}
if (args[i - 1].equalsIgnoreCase("-exe")) //$NON-NLS-1$
provider.setExecutableLocation(arg);
if (args[i - 1].equalsIgnoreCase("-launcherConfig")) //$NON-NLS-1$
provider.setLauncherConfig(arg);
if (args[i - 1].equalsIgnoreCase("-metadataRepository") || args[i - 1].equalsIgnoreCase("-mr")) //$NON-NLS-1$ //$NON-NLS-2$
metadataLocation = arg;
if (args[i - 1].equalsIgnoreCase("-metadataRepositoryName")) //$NON-NLS-1$
metadataRepoName = arg;
if (args[i - 1].equalsIgnoreCase("-artifactRepository") | args[i - 1].equalsIgnoreCase("-ar")) //$NON-NLS-1$ //$NON-NLS-2$
artifactLocation = arg;
if (args[i - 1].equalsIgnoreCase("-artifactRepositoryName")) //$NON-NLS-1$
artifactRepoName = arg;
if (args[i - 1].equalsIgnoreCase("-flavor")) //$NON-NLS-1$
provider.setFlavor(arg);
if (args[i - 1].equalsIgnoreCase("-productFile")) //$NON-NLS-1$
provider.setProductFile(arg);
if (args[i - 1].equalsIgnoreCase("-features")) //$NON-NLS-1$
features = arg;
if (args[i - 1].equalsIgnoreCase("-bundles")) //$NON-NLS-1$
bundles = arg;
if (args[i - 1].equalsIgnoreCase("-base")) //$NON-NLS-1$
base = arg;
if (args[i - 1].equalsIgnoreCase("-root")) //$NON-NLS-1$
provider.setRootId(arg);
if (args[i - 1].equalsIgnoreCase("-rootVersion")) //$NON-NLS-1$
provider.setRootVersion(arg);
if (args[i - 1].equalsIgnoreCase("-p2.os")) //$NON-NLS-1$
provider.setOS(arg);
if (args[i - 1].equalsIgnoreCase("-site")) //$NON-NLS-1$
provider.setSiteLocation(new URL(arg));
}
}
private void registerDefaultArtifactRepoManager() {
if (ServiceHelper.getService(Activator.getContext(), IArtifactRepositoryManager.class.getName()) == null) {
defaultArtifactManager = new ArtifactRepositoryManager();
registrationDefaultArtifactManager = Activator.getContext().registerService(IArtifactRepositoryManager.class.getName(), defaultArtifactManager, null);
}
}
private void registerDefaultMetadataRepoManager() {
if (ServiceHelper.getService(Activator.getContext(), IMetadataRepositoryManager.class.getName()) == null) {
defaultMetadataManager = new MetadataRepositoryManager();
registrationDefaultMetadataManager = Activator.getContext().registerService(IMetadataRepositoryManager.class.getName(), defaultMetadataManager, null);
}
}
private void registerEventBus() {
if (ServiceHelper.getService(Activator.getContext(), IProvisioningEventBus.SERVICE_NAME) == null) {
bus = new ProvisioningEventBus();
registrationBus = Activator.getContext().registerService(IProvisioningEventBus.SERVICE_NAME, bus, null);
}
}
public Object run(String args[]) throws Exception {
EclipseInstallGeneratorInfoProvider provider = new EclipseInstallGeneratorInfoProvider();
processCommandLineArguments(args, provider);
Object result = run(provider);
if (result != IApplication.EXIT_OK)
for (int i = 0; i < args.length; i++)
System.out.println(args[i]);
return result;
}
public Object run(EclipseInstallGeneratorInfoProvider provider) throws Exception {
registerEventBus();
registerDefaultMetadataRepoManager();
registerDefaultArtifactRepoManager();
initialize(provider);
if (provider.getBaseLocation() == null && provider.getProductFile() == null && !generateRootIU) {
System.out.println(Messages.exception_baseLocationNotSpecified);
return new Integer(-1);
}
System.out.println(NLS.bind(Messages.message_generatingMetadata, provider.getBaseLocation()));
long before = System.currentTimeMillis();
IStatus result = generate(provider);
long after = System.currentTimeMillis();
if (result.isOK()) {
System.out.println(NLS.bind(Messages.message_generationCompleted, String.valueOf((after - before) / 1000)));
return IApplication.EXIT_OK;
}
System.out.println(result);
return new Integer(1);
}
protected IStatus generate(EclipseInstallGeneratorInfoProvider provider) {
Generator generator = new Generator(provider);
if (incrementalResult != null)
generator.setIncrementalResult(incrementalResult);
generator.setGenerateRootIU(generateRootIU);
IStatus result = generator.generate();
incrementalResult = null;
return result;
}
public Object start(IApplicationContext context) throws Exception {
return run((String[]) context.getArguments().get("application.args")); //$NON-NLS-1$
}
public void stop() {
if (registrationDefaultMetadataManager != null) {
registrationDefaultMetadataManager.unregister();
registrationDefaultMetadataManager = null;
}
if (registrationDefaultArtifactManager != null) {
registrationDefaultArtifactManager.unregister();
registrationDefaultArtifactManager = null;
}
if (registrationBus != null) {
registrationBus.unregister();
registrationBus = null;
}
}
public void setBase(String base) {
this.base = base;
}
public void setArtifactLocation(String location) {
this.artifactLocation = location;
}
public void setBundles(String bundles) {
this.bundles = bundles;
}
public void setOperation(String operation, String argument) {
this.operation = operation;
this.argument = argument;
}
public void setFeatures(String features) {
this.features = features;
}
public void setMetadataLocation(String location) {
this.metadataLocation = location;
}
public void setMetadataRepositoryName(String name) {
this.metadataRepoName = name;
}
public void setArtifactRepositoryName(String name) {
this.artifactRepoName = name;
}
public void setIncrementalResult(Generator.GeneratorResult ius) {
this.incrementalResult = ius;
}
public void setGeneratorRootIU(boolean b) {
this.generateRootIU = b;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.