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/test/java/org/encog/ml/factory/TestMLMethodFactory.java b/src/test/java/org/encog/ml/factory/TestMLMethodFactory.java index 9d2110d46..6bec243d6 100644 --- a/src/test/java/org/encog/ml/factory/TestMLMethodFactory.java +++ b/src/test/java/org/encog/ml/factory/TestMLMethodFactory.java @@ -1,79 +1,79 @@ package org.encog.ml.factory; import org.encog.EncogError; import org.encog.ml.svm.SVM; import org.encog.neural.activation.ActivationLinear; import org.encog.neural.activation.ActivationTANH; import org.encog.neural.networks.BasicNetwork; import org.encog.neural.rbf.RBFNetwork; import junit.framework.Assert; import junit.framework.TestCase; public class TestMLMethodFactory extends TestCase { public static final String TYPE_FEEDFORWARD = "feedforward"; public static final String TYPE_RBFNETWORK = "rbfnetwork"; public static final String TYPE_SVM = "svm"; public static final String TYPE_SOM = "som"; public void testFactoryFeedforward() { String architecture = "?:B->TANH->3->LINEAR->?:B"; MLMethodFactory factory = new MLMethodFactory(); BasicNetwork network = (BasicNetwork)factory.create(MLMethodFactory.TYPE_FEEDFORWARD, architecture, 1, 4); Assert.assertTrue(network.isLayerBiased(0)); Assert.assertFalse(network.isLayerBiased(1)); Assert.assertTrue(network.isLayerBiased(2)); Assert.assertEquals(3, network.getLayerCount()); - Assert.assertTrue(network.getActivation(0) instanceof ActivationTANH ); - Assert.assertTrue(network.getActivation(1) instanceof ActivationLinear ); + Assert.assertTrue(network.getActivation(0) instanceof ActivationLinear ); + Assert.assertTrue(network.getActivation(1) instanceof ActivationTANH ); Assert.assertTrue(network.getActivation(2) instanceof ActivationLinear ); Assert.assertEquals(18,network.encodedArrayLength()); Assert.assertEquals(1,network.getLayerNeuronCount(0)); Assert.assertEquals(3,network.getLayerNeuronCount(1)); Assert.assertEquals(4,network.getLayerNeuronCount(2)); } private void expectError(String t, String a) { MLMethodFactory factory = new MLMethodFactory(); try { factory.create(t, a, 2, 1); Assert.assertTrue(false); } catch(EncogError e) { // good } } public void testFactoryFeedforwardError() { String ARC1 = "?->3->ERROR->?"; String ARC2 = "?->?->?"; String ARC3 = "?->3->0->?"; expectError(MLMethodFactory.TYPE_FEEDFORWARD, ARC1); expectError(MLMethodFactory.TYPE_FEEDFORWARD, ARC2); expectError(MLMethodFactory.TYPE_FEEDFORWARD, ARC3); } public void testFactoryRBF() { String architecture = "?->GAUSSIAN(c=4)->?"; MLMethodFactory factory = new MLMethodFactory(); RBFNetwork network = (RBFNetwork)factory.create(MLMethodFactory.TYPE_RBFNETWORK, architecture, 1, 4); Assert.assertEquals(1,network.getInputCount()); Assert.assertEquals(4,network.getOutputCount()); Assert.assertEquals(4,network.getRBF().length); } public void testFactorySVM() { String architecture = "?->C(KERNEL=RBF,TYPE=NEW)->?"; MLMethodFactory factory = new MLMethodFactory(); SVM network = (SVM)factory.create(MLMethodFactory.TYPE_SVM, architecture, 4, 1); Assert.assertEquals(4,network.getInputCount()); Assert.assertEquals(1,network.getOutputCount()); } public void testFactorySOM() { } }
true
true
public void testFactoryFeedforward() { String architecture = "?:B->TANH->3->LINEAR->?:B"; MLMethodFactory factory = new MLMethodFactory(); BasicNetwork network = (BasicNetwork)factory.create(MLMethodFactory.TYPE_FEEDFORWARD, architecture, 1, 4); Assert.assertTrue(network.isLayerBiased(0)); Assert.assertFalse(network.isLayerBiased(1)); Assert.assertTrue(network.isLayerBiased(2)); Assert.assertEquals(3, network.getLayerCount()); Assert.assertTrue(network.getActivation(0) instanceof ActivationTANH ); Assert.assertTrue(network.getActivation(1) instanceof ActivationLinear ); Assert.assertTrue(network.getActivation(2) instanceof ActivationLinear ); Assert.assertEquals(18,network.encodedArrayLength()); Assert.assertEquals(1,network.getLayerNeuronCount(0)); Assert.assertEquals(3,network.getLayerNeuronCount(1)); Assert.assertEquals(4,network.getLayerNeuronCount(2)); }
public void testFactoryFeedforward() { String architecture = "?:B->TANH->3->LINEAR->?:B"; MLMethodFactory factory = new MLMethodFactory(); BasicNetwork network = (BasicNetwork)factory.create(MLMethodFactory.TYPE_FEEDFORWARD, architecture, 1, 4); Assert.assertTrue(network.isLayerBiased(0)); Assert.assertFalse(network.isLayerBiased(1)); Assert.assertTrue(network.isLayerBiased(2)); Assert.assertEquals(3, network.getLayerCount()); Assert.assertTrue(network.getActivation(0) instanceof ActivationLinear ); Assert.assertTrue(network.getActivation(1) instanceof ActivationTANH ); Assert.assertTrue(network.getActivation(2) instanceof ActivationLinear ); Assert.assertEquals(18,network.encodedArrayLength()); Assert.assertEquals(1,network.getLayerNeuronCount(0)); Assert.assertEquals(3,network.getLayerNeuronCount(1)); Assert.assertEquals(4,network.getLayerNeuronCount(2)); }
diff --git a/grails/src/java/org/codehaus/groovy/grails/compiler/injection/GlobalPluginAwareEntityASTTransformation.java b/grails/src/java/org/codehaus/groovy/grails/compiler/injection/GlobalPluginAwareEntityASTTransformation.java index 0f8eb2604..5485b5da2 100644 --- a/grails/src/java/org/codehaus/groovy/grails/compiler/injection/GlobalPluginAwareEntityASTTransformation.java +++ b/grails/src/java/org/codehaus/groovy/grails/compiler/injection/GlobalPluginAwareEntityASTTransformation.java @@ -1,88 +1,89 @@ /* Copyright 2004-2005 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.grails.compiler.injection; import grails.util.PluginBuildSettings; import org.codehaus.groovy.ast.ASTNode; import org.codehaus.groovy.ast.AnnotationNode; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.ModuleNode; import org.codehaus.groovy.ast.expr.ConstantExpression; import org.codehaus.groovy.control.CompilePhase; import org.codehaus.groovy.control.SourceUnit; import org.codehaus.groovy.grails.plugins.GrailsPluginUtils; import org.codehaus.groovy.grails.plugins.PluginInfo; import org.codehaus.groovy.grails.plugins.metadata.GrailsPlugin; import org.codehaus.groovy.transform.ASTTransformation; import org.codehaus.groovy.transform.GroovyASTTransformation; import java.io.File; import java.io.IOException; import java.util.List; /** * This AST transformation automatically annotates any class * with @Plugin(name="foo") if it is a plugin resource * * @author Graeme Rocher * @since 1.2 */ @GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION) public class GlobalPluginAwareEntityASTTransformation implements ASTTransformation { private boolean disableTransformation = Boolean.getBoolean("disable.grails.plugin.transform"); public void visit(ASTNode[] astNodes, SourceUnit sourceUnit) { if(disableTransformation) return; ASTNode astNode = astNodes[0]; if(astNode instanceof ModuleNode) { ModuleNode moduleNode = (ModuleNode) astNode; List classes = moduleNode.getClasses(); if(classes.size()>0) { ClassNode classNode = (ClassNode) classes.get(0); + if(classNode.isAnnotationDefinition()) return; File sourcePath = new File(sourceUnit.getName()); try { String absolutePath = sourcePath.getCanonicalPath(); PluginBuildSettings pluginBuildSettings = GrailsPluginUtils.getPluginBuildSettings(); if(pluginBuildSettings!=null) { PluginInfo info = pluginBuildSettings.getPluginInfoForSource(absolutePath); if(info!=null) { final ClassNode annotation = new ClassNode(GrailsPlugin.class); final List list = classNode.getAnnotations(annotation); if(list.size()==0) { final AnnotationNode annotationNode = new AnnotationNode(annotation); annotationNode.addMember(org.codehaus.groovy.grails.plugins.GrailsPlugin.NAME, new ConstantExpression(info.getName())); annotationNode.addMember(org.codehaus.groovy.grails.plugins.GrailsPlugin.VERSION, new ConstantExpression(info.getVersion())); annotationNode.setRuntimeRetention(true); annotationNode.setClassRetention(true); classNode.addAnnotation(annotationNode); } } } } catch (IOException e) { // ignore } } } } }
true
true
public void visit(ASTNode[] astNodes, SourceUnit sourceUnit) { if(disableTransformation) return; ASTNode astNode = astNodes[0]; if(astNode instanceof ModuleNode) { ModuleNode moduleNode = (ModuleNode) astNode; List classes = moduleNode.getClasses(); if(classes.size()>0) { ClassNode classNode = (ClassNode) classes.get(0); File sourcePath = new File(sourceUnit.getName()); try { String absolutePath = sourcePath.getCanonicalPath(); PluginBuildSettings pluginBuildSettings = GrailsPluginUtils.getPluginBuildSettings(); if(pluginBuildSettings!=null) { PluginInfo info = pluginBuildSettings.getPluginInfoForSource(absolutePath); if(info!=null) { final ClassNode annotation = new ClassNode(GrailsPlugin.class); final List list = classNode.getAnnotations(annotation); if(list.size()==0) { final AnnotationNode annotationNode = new AnnotationNode(annotation); annotationNode.addMember(org.codehaus.groovy.grails.plugins.GrailsPlugin.NAME, new ConstantExpression(info.getName())); annotationNode.addMember(org.codehaus.groovy.grails.plugins.GrailsPlugin.VERSION, new ConstantExpression(info.getVersion())); annotationNode.setRuntimeRetention(true); annotationNode.setClassRetention(true); classNode.addAnnotation(annotationNode); } } } } catch (IOException e) { // ignore } } } }
public void visit(ASTNode[] astNodes, SourceUnit sourceUnit) { if(disableTransformation) return; ASTNode astNode = astNodes[0]; if(astNode instanceof ModuleNode) { ModuleNode moduleNode = (ModuleNode) astNode; List classes = moduleNode.getClasses(); if(classes.size()>0) { ClassNode classNode = (ClassNode) classes.get(0); if(classNode.isAnnotationDefinition()) return; File sourcePath = new File(sourceUnit.getName()); try { String absolutePath = sourcePath.getCanonicalPath(); PluginBuildSettings pluginBuildSettings = GrailsPluginUtils.getPluginBuildSettings(); if(pluginBuildSettings!=null) { PluginInfo info = pluginBuildSettings.getPluginInfoForSource(absolutePath); if(info!=null) { final ClassNode annotation = new ClassNode(GrailsPlugin.class); final List list = classNode.getAnnotations(annotation); if(list.size()==0) { final AnnotationNode annotationNode = new AnnotationNode(annotation); annotationNode.addMember(org.codehaus.groovy.grails.plugins.GrailsPlugin.NAME, new ConstantExpression(info.getName())); annotationNode.addMember(org.codehaus.groovy.grails.plugins.GrailsPlugin.VERSION, new ConstantExpression(info.getVersion())); annotationNode.setRuntimeRetention(true); annotationNode.setClassRetention(true); classNode.addAnnotation(annotationNode); } } } } catch (IOException e) { // ignore } } } }
diff --git a/src/main/java/me/eccentric_nz/TARDIS/utility/TARDISHostileDisplacement.java b/src/main/java/me/eccentric_nz/TARDIS/utility/TARDISHostileDisplacement.java index 42f4da81e..c5355b042 100644 --- a/src/main/java/me/eccentric_nz/TARDIS/utility/TARDISHostileDisplacement.java +++ b/src/main/java/me/eccentric_nz/TARDIS/utility/TARDISHostileDisplacement.java @@ -1,180 +1,180 @@ /* * Copyright (C) 2013 eccentric_nz * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If ChatColor.RESET, see <http://www.gnu.org/licenses/>. */ package me.eccentric_nz.TARDIS.utility; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import me.eccentric_nz.TARDIS.TARDIS; import me.eccentric_nz.TARDIS.TARDISConstants; import me.eccentric_nz.TARDIS.database.QueryFactory; import me.eccentric_nz.TARDIS.database.ResultSetPlayerPrefs; import me.eccentric_nz.TARDIS.database.ResultSetTardis; import me.eccentric_nz.TARDIS.travel.TARDISPluginRespect; import me.eccentric_nz.TARDIS.travel.TARDISTimeTravel; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.World.Environment; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.entity.Player; /** * The Hostile Action Displacement System, or HADS, was one of the defence * mechanisms of the Doctor's TARDIS. When the outer shell of the vessel came * under attack, the unit dematerialised the TARDIS and re-materialised it a * short distance away after the attacker had gone, in a safer locale. The HADS * had to be manually set, and the Doctor often forgot to do so. * * @author eccentric_nz */ public class TARDISHostileDisplacement { private final TARDIS plugin; private List<Integer> angles = Arrays.asList(new Integer[]{0, 45, 90, 135, 180, 225, 270, 315}); public TARDISHostileDisplacement(TARDIS plugin) { this.plugin = plugin; } public void moveTARDIS(final int id, Player hostile) { HashMap<String, Object> where = new HashMap<String, Object>(); where.put("tardis_id", id); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (rs.resultSet()) { String current = rs.getCurrent(); String owner = rs.getOwner(); final TARDISConstants.COMPASS d = rs.getDirection(); final boolean cham = rs.isChamele_on(); HashMap<String, Object> wherep = new HashMap<String, Object>(); wherep.put("player", owner); ResultSetPlayerPrefs rsp = new ResultSetPlayerPrefs(plugin, wherep); if (rsp.resultSet()) { if (rsp.isHads_on()) { TARDISTimeTravel tt = new TARDISTimeTravel(plugin); int r = plugin.getConfig().getInt("hads_distance"); final Location loc = plugin.utils.getLocationFromDB(current, 0, 0); Location l = loc.clone(); // randomise the direction Collections.shuffle(angles); for (Integer a : angles) { int wx = (int) (l.getX() + r * Math.cos(a)); // x = cx + r * cos(a) int wz = (int) (l.getZ() + r * Math.sin(a)); // z = cz + r * sin(a) l.setX(wx); l.setZ(wz); boolean bool = true; int y; if (l.getWorld().getEnvironment().equals(Environment.NETHER)) { y = getHighestNetherBlock(l.getWorld(), wx, wz); } else { y = l.getWorld().getHighestBlockAt(l).getY(); } l.setY(y); if (l.getBlock().getRelative(BlockFace.DOWN).isLiquid() && !plugin.getConfig().getBoolean("land_on_water") && !plugin.trackSubmarine.contains(id)) { plugin.debug("bool: false"); bool = false; } final Player player = plugin.getServer().getPlayer(owner); if (bool) { Location sub = null; boolean safe; if (plugin.trackSubmarine.contains(id)) { sub = tt.submarine(l.getBlock(), d); safe = (sub != null); } else { int[] start = tt.getStartLocation(l, d); safe = (tt.safeLocation(start[0], y, start[2], start[1], start[3], l.getWorld(), d) < 1); if (plugin.trackSubmarine.contains(id)) { plugin.trackSubmarine.remove(id); } } if (safe) { final Location fl = (plugin.trackSubmarine.contains(id)) ? sub : l; TARDISPluginRespect pr = new TARDISPluginRespect(plugin); - if (pr.getRespect(player, l, false)) { + if (pr.getRespect(player, fl, false)) { // move TARDIS - String hads = l.getWorld().getName() + ":" + l.getBlockX() + ":" + l.getBlockY() + ":" + l.getBlockZ(); + String hads = fl.getWorld().getName() + ":" + fl.getBlockX() + ":" + fl.getBlockY() + ":" + fl.getBlockZ(); QueryFactory qf = new QueryFactory(plugin); HashMap<String, Object> tid = new HashMap<String, Object>(); HashMap<String, Object> set = new HashMap<String, Object>(); tid.put("tardis_id", id); set.put("save", hads); set.put("current", hads); qf.doUpdate("tardis", set, tid); plugin.trackDamage.remove(Integer.valueOf(id)); final boolean mat = plugin.getConfig().getBoolean("materialise"); long delay = (mat) ? 1L : 180L; plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { plugin.tardisDematerialising.add(id); plugin.destroyPB.destroyPoliceBox(loc, d, id, false, mat, cham, player); } }, delay); plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { plugin.buildPB.buildPoliceBox(id, fl, d, cham, player, false, false); } }, delay * 2); // message time lord String message = plugin.pluginName + ChatColor.RED + "H" + ChatColor.RESET + "ostile " + ChatColor.RED + "A" + ChatColor.RESET + "ction " + ChatColor.RED + "D" + ChatColor.RESET + "isplacement " + ChatColor.RED + "S" + ChatColor.RESET + "ystem engaged, moving TARDIS!"; player.sendMessage(message); player.sendMessage(plugin.pluginName + "TARDIS moved to " + hads); if (player != hostile) { hostile.sendMessage(message); } break; } else { player.sendMessage(plugin.pluginName + "HADS could not be engaged because the area is protected!"); if (player != hostile) { hostile.sendMessage(plugin.pluginName + "HADS could not be engaged because the area is protected!"); } } } else { player.sendMessage(plugin.pluginName + "HADS could not be engaged because the we couldn't find a safe area!"); } } else { plugin.trackDamage.remove(Integer.valueOf(id)); player.sendMessage(plugin.pluginName + "HADS could not be engaged because the TARDIS cannot land on water!"); } } } } } } private int getHighestNetherBlock(World w, int wherex, int wherez) { int y = 100; Block startBlock = w.getBlockAt(wherex, y, wherez); while (startBlock.getTypeId() != 0) { startBlock = startBlock.getRelative(BlockFace.DOWN); } int air = 0; while (startBlock.getTypeId() == 0 && startBlock.getLocation().getBlockY() > 30) { startBlock = startBlock.getRelative(BlockFace.DOWN); air++; } int id = startBlock.getTypeId(); if ((id == 87 || id == 88 || id == 89 || id == 112 || id == 113 || id == 114) && air >= 4) { y = startBlock.getLocation().getBlockY() + 1; } return y; } }
false
true
public void moveTARDIS(final int id, Player hostile) { HashMap<String, Object> where = new HashMap<String, Object>(); where.put("tardis_id", id); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (rs.resultSet()) { String current = rs.getCurrent(); String owner = rs.getOwner(); final TARDISConstants.COMPASS d = rs.getDirection(); final boolean cham = rs.isChamele_on(); HashMap<String, Object> wherep = new HashMap<String, Object>(); wherep.put("player", owner); ResultSetPlayerPrefs rsp = new ResultSetPlayerPrefs(plugin, wherep); if (rsp.resultSet()) { if (rsp.isHads_on()) { TARDISTimeTravel tt = new TARDISTimeTravel(plugin); int r = plugin.getConfig().getInt("hads_distance"); final Location loc = plugin.utils.getLocationFromDB(current, 0, 0); Location l = loc.clone(); // randomise the direction Collections.shuffle(angles); for (Integer a : angles) { int wx = (int) (l.getX() + r * Math.cos(a)); // x = cx + r * cos(a) int wz = (int) (l.getZ() + r * Math.sin(a)); // z = cz + r * sin(a) l.setX(wx); l.setZ(wz); boolean bool = true; int y; if (l.getWorld().getEnvironment().equals(Environment.NETHER)) { y = getHighestNetherBlock(l.getWorld(), wx, wz); } else { y = l.getWorld().getHighestBlockAt(l).getY(); } l.setY(y); if (l.getBlock().getRelative(BlockFace.DOWN).isLiquid() && !plugin.getConfig().getBoolean("land_on_water") && !plugin.trackSubmarine.contains(id)) { plugin.debug("bool: false"); bool = false; } final Player player = plugin.getServer().getPlayer(owner); if (bool) { Location sub = null; boolean safe; if (plugin.trackSubmarine.contains(id)) { sub = tt.submarine(l.getBlock(), d); safe = (sub != null); } else { int[] start = tt.getStartLocation(l, d); safe = (tt.safeLocation(start[0], y, start[2], start[1], start[3], l.getWorld(), d) < 1); if (plugin.trackSubmarine.contains(id)) { plugin.trackSubmarine.remove(id); } } if (safe) { final Location fl = (plugin.trackSubmarine.contains(id)) ? sub : l; TARDISPluginRespect pr = new TARDISPluginRespect(plugin); if (pr.getRespect(player, l, false)) { // move TARDIS String hads = l.getWorld().getName() + ":" + l.getBlockX() + ":" + l.getBlockY() + ":" + l.getBlockZ(); QueryFactory qf = new QueryFactory(plugin); HashMap<String, Object> tid = new HashMap<String, Object>(); HashMap<String, Object> set = new HashMap<String, Object>(); tid.put("tardis_id", id); set.put("save", hads); set.put("current", hads); qf.doUpdate("tardis", set, tid); plugin.trackDamage.remove(Integer.valueOf(id)); final boolean mat = plugin.getConfig().getBoolean("materialise"); long delay = (mat) ? 1L : 180L; plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { plugin.tardisDematerialising.add(id); plugin.destroyPB.destroyPoliceBox(loc, d, id, false, mat, cham, player); } }, delay); plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { plugin.buildPB.buildPoliceBox(id, fl, d, cham, player, false, false); } }, delay * 2); // message time lord String message = plugin.pluginName + ChatColor.RED + "H" + ChatColor.RESET + "ostile " + ChatColor.RED + "A" + ChatColor.RESET + "ction " + ChatColor.RED + "D" + ChatColor.RESET + "isplacement " + ChatColor.RED + "S" + ChatColor.RESET + "ystem engaged, moving TARDIS!"; player.sendMessage(message); player.sendMessage(plugin.pluginName + "TARDIS moved to " + hads); if (player != hostile) { hostile.sendMessage(message); } break; } else { player.sendMessage(plugin.pluginName + "HADS could not be engaged because the area is protected!"); if (player != hostile) { hostile.sendMessage(plugin.pluginName + "HADS could not be engaged because the area is protected!"); } } } else { player.sendMessage(plugin.pluginName + "HADS could not be engaged because the we couldn't find a safe area!"); } } else { plugin.trackDamage.remove(Integer.valueOf(id)); player.sendMessage(plugin.pluginName + "HADS could not be engaged because the TARDIS cannot land on water!"); } } } } } }
public void moveTARDIS(final int id, Player hostile) { HashMap<String, Object> where = new HashMap<String, Object>(); where.put("tardis_id", id); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (rs.resultSet()) { String current = rs.getCurrent(); String owner = rs.getOwner(); final TARDISConstants.COMPASS d = rs.getDirection(); final boolean cham = rs.isChamele_on(); HashMap<String, Object> wherep = new HashMap<String, Object>(); wherep.put("player", owner); ResultSetPlayerPrefs rsp = new ResultSetPlayerPrefs(plugin, wherep); if (rsp.resultSet()) { if (rsp.isHads_on()) { TARDISTimeTravel tt = new TARDISTimeTravel(plugin); int r = plugin.getConfig().getInt("hads_distance"); final Location loc = plugin.utils.getLocationFromDB(current, 0, 0); Location l = loc.clone(); // randomise the direction Collections.shuffle(angles); for (Integer a : angles) { int wx = (int) (l.getX() + r * Math.cos(a)); // x = cx + r * cos(a) int wz = (int) (l.getZ() + r * Math.sin(a)); // z = cz + r * sin(a) l.setX(wx); l.setZ(wz); boolean bool = true; int y; if (l.getWorld().getEnvironment().equals(Environment.NETHER)) { y = getHighestNetherBlock(l.getWorld(), wx, wz); } else { y = l.getWorld().getHighestBlockAt(l).getY(); } l.setY(y); if (l.getBlock().getRelative(BlockFace.DOWN).isLiquid() && !plugin.getConfig().getBoolean("land_on_water") && !plugin.trackSubmarine.contains(id)) { plugin.debug("bool: false"); bool = false; } final Player player = plugin.getServer().getPlayer(owner); if (bool) { Location sub = null; boolean safe; if (plugin.trackSubmarine.contains(id)) { sub = tt.submarine(l.getBlock(), d); safe = (sub != null); } else { int[] start = tt.getStartLocation(l, d); safe = (tt.safeLocation(start[0], y, start[2], start[1], start[3], l.getWorld(), d) < 1); if (plugin.trackSubmarine.contains(id)) { plugin.trackSubmarine.remove(id); } } if (safe) { final Location fl = (plugin.trackSubmarine.contains(id)) ? sub : l; TARDISPluginRespect pr = new TARDISPluginRespect(plugin); if (pr.getRespect(player, fl, false)) { // move TARDIS String hads = fl.getWorld().getName() + ":" + fl.getBlockX() + ":" + fl.getBlockY() + ":" + fl.getBlockZ(); QueryFactory qf = new QueryFactory(plugin); HashMap<String, Object> tid = new HashMap<String, Object>(); HashMap<String, Object> set = new HashMap<String, Object>(); tid.put("tardis_id", id); set.put("save", hads); set.put("current", hads); qf.doUpdate("tardis", set, tid); plugin.trackDamage.remove(Integer.valueOf(id)); final boolean mat = plugin.getConfig().getBoolean("materialise"); long delay = (mat) ? 1L : 180L; plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { plugin.tardisDematerialising.add(id); plugin.destroyPB.destroyPoliceBox(loc, d, id, false, mat, cham, player); } }, delay); plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { plugin.buildPB.buildPoliceBox(id, fl, d, cham, player, false, false); } }, delay * 2); // message time lord String message = plugin.pluginName + ChatColor.RED + "H" + ChatColor.RESET + "ostile " + ChatColor.RED + "A" + ChatColor.RESET + "ction " + ChatColor.RED + "D" + ChatColor.RESET + "isplacement " + ChatColor.RED + "S" + ChatColor.RESET + "ystem engaged, moving TARDIS!"; player.sendMessage(message); player.sendMessage(plugin.pluginName + "TARDIS moved to " + hads); if (player != hostile) { hostile.sendMessage(message); } break; } else { player.sendMessage(plugin.pluginName + "HADS could not be engaged because the area is protected!"); if (player != hostile) { hostile.sendMessage(plugin.pluginName + "HADS could not be engaged because the area is protected!"); } } } else { player.sendMessage(plugin.pluginName + "HADS could not be engaged because the we couldn't find a safe area!"); } } else { plugin.trackDamage.remove(Integer.valueOf(id)); player.sendMessage(plugin.pluginName + "HADS could not be engaged because the TARDIS cannot land on water!"); } } } } } }
diff --git a/bikeshed/src/com/google/gwt/valuestore/shared/impl/RecordJsoImpl.java b/bikeshed/src/com/google/gwt/valuestore/shared/impl/RecordJsoImpl.java index 60af25ef8..0395a602e 100644 --- a/bikeshed/src/com/google/gwt/valuestore/shared/impl/RecordJsoImpl.java +++ b/bikeshed/src/com/google/gwt/valuestore/shared/impl/RecordJsoImpl.java @@ -1,186 +1,187 @@ /* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.gwt.valuestore.shared.impl; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.core.client.JsArray; import com.google.gwt.valuestore.shared.Property; import com.google.gwt.valuestore.shared.PropertyReference; import com.google.gwt.valuestore.shared.Record; import java.util.Date; /** * JSO implementation of {@link Record}, used to back subclasses of * {@link RecordImpl}. */ public class RecordJsoImpl extends JavaScriptObject implements Record { public static native JsArray<RecordJsoImpl> arrayFromJson(String json) /*-{ return eval(json); }-*/; public static RecordJsoImpl emptyCopy(RecordImpl from) { RecordJsoImpl copy = create(); final RecordSchema<?> schema = from.getSchema(); copy.setSchema(schema); copy.set(Record.id, from.get(Record.id)); copy.set(Record.version, from.get(Record.version)); return copy; } private static native RecordJsoImpl create() /*-{ return {}; }-*/; protected RecordJsoImpl() { } public final native void delete(String name)/*-{ delete this[name]; }-*/; @SuppressWarnings("unchecked") public final <V> V get(Property<V> property) { assert isDefined(property.getName()) : "Cannot ask for a property before setting it: " + property.getName(); if (Integer.class.equals(property.getType())) { return (V) Integer.valueOf(getInt(property.getName())); } if (Date.class.equals(property.getType())) { double millis = getDouble(property.getName()); if (GWT.isScript()) { return (V) dateForDouble(millis); } else { // In dev mode, we're using real JRE dates return (V) new Date((long) millis); } } - return get(property.getName()); + // Sun JDK compile fails without this cast + return (V) get(property.getName()); } public final native <T> T get(String propertyName) /*-{ return this[propertyName]; }-*/; public final String getId() { return this.get(id); } public final <V> PropertyReference<V> getRef(Property<V> property) { return new PropertyReference<V>(this, property); } public final native RecordSchema<?> getSchema() /*-{ return this['__key']; }-*/; public final String getVersion() { return this.get(version); } /** * @param name */ public final native boolean isDefined(String name)/*-{ return this[name] !== undefined; }-*/; public final boolean isEmpty() { for (Property<?> property : getSchema().allProperties()) { if ((property != Record.id) && (property != Record.version) && (isDefined(property.getName()))) { return false; } } return true; } public final boolean merge(RecordJsoImpl from) { assert getSchema() == from.getSchema(); boolean changed = false; for (Property<?> property : getSchema().allProperties()) { if (from.isDefined(property.getName())) { changed |= copyPropertyIfDifferent(property.getName(), from); } } return changed; } public final <V> void set(Property<V> property, V value) { if (value instanceof String) { setString(property.getName(), (String) value); return; } if (value instanceof Integer) { setInt(property.getName(), (Integer) value); return; } throw new UnsupportedOperationException("Can't yet set properties of type " + value.getClass().getName()); } public final native void setSchema(RecordSchema<?> schema) /*-{ this['__key'] = schema; }-*/; /** * Return JSON representation using org.json library. * * @return returned string. */ public final native String toJson() /*-{ var replacer = function(key, value) { if (key == '__key') { return; } return value; } return JSON.stringify(this, replacer); }-*/; private native boolean copyPropertyIfDifferent(String name, RecordJsoImpl from) /*-{ if (this[name] == from[name]) { return false; } this[name] = from[name]; return true; }-*/; private native Date dateForDouble(double millis) /*-{ return @java.util.Date::createFrom(D)(millis); }-*/;; private native double getDouble(String name) /*-{ return this[name]; }-*/; private native int getInt(String name) /*-{ return this[name]; }-*/; private native void setInt(String name, int value) /*-{ this[name] = value; }-*/; private native void setString(String name, String value) /*-{ this[name] = value; }-*/; }
true
true
public final <V> V get(Property<V> property) { assert isDefined(property.getName()) : "Cannot ask for a property before setting it: " + property.getName(); if (Integer.class.equals(property.getType())) { return (V) Integer.valueOf(getInt(property.getName())); } if (Date.class.equals(property.getType())) { double millis = getDouble(property.getName()); if (GWT.isScript()) { return (V) dateForDouble(millis); } else { // In dev mode, we're using real JRE dates return (V) new Date((long) millis); } } return get(property.getName()); }
public final <V> V get(Property<V> property) { assert isDefined(property.getName()) : "Cannot ask for a property before setting it: " + property.getName(); if (Integer.class.equals(property.getType())) { return (V) Integer.valueOf(getInt(property.getName())); } if (Date.class.equals(property.getType())) { double millis = getDouble(property.getName()); if (GWT.isScript()) { return (V) dateForDouble(millis); } else { // In dev mode, we're using real JRE dates return (V) new Date((long) millis); } } // Sun JDK compile fails without this cast return (V) get(property.getName()); }
diff --git a/src/org/geworkbench/parsers/SampleFileParser.java b/src/org/geworkbench/parsers/SampleFileParser.java index e3041443..7d3c3d84 100644 --- a/src/org/geworkbench/parsers/SampleFileParser.java +++ b/src/org/geworkbench/parsers/SampleFileParser.java @@ -1,319 +1,314 @@ package org.geworkbench.parsers; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InterruptedIOException; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.geworkbench.bison.datastructure.biocollections.microarrays.CSMicroarraySet; import org.geworkbench.bison.datastructure.biocollections.microarrays.DSMicroarraySet; import org.geworkbench.bison.datastructure.bioobjects.markers.CSExpressionMarker; import org.geworkbench.bison.datastructure.bioobjects.markers.DSGeneMarker; import org.geworkbench.bison.datastructure.bioobjects.markers.annotationparser.AnnotationParser; import org.geworkbench.bison.datastructure.bioobjects.microarray.CSExpressionMarkerValue; import org.geworkbench.bison.datastructure.bioobjects.microarray.CSMicroarray; import org.geworkbench.bison.datastructure.bioobjects.microarray.DSMicroarray; import org.geworkbench.util.AffyAnnotationUtil; /** * @author Nikhil */ public class SampleFileParser { static Log log = LogFactory.getLog(SOFTFileFormat.class); private static final String commentSign1 = "#"; private static final String commentSign2 = "!"; private static final String commentSign3 = "^"; static final char ABSENT = 'A'; static final char PRESENT = 'P'; static final char MARGINAL = 'M'; static final char UNDEFINED = '\0'; char detectionStatus = UNDEFINED; CSMicroarraySet maSet = new CSMicroarraySet(); private int possibleMarkers = 0; /* * (non-Javadoc) * * @see org.geworkbench.components.parsers.FileFormat#getMArraySet(java.io.File) */ public DSMicroarraySet getMArraySet(File file) throws InputFileFormatException, InterruptedIOException { BufferedReader in = null; - final int extSeperater = '.'; String fileName = file.getName(); - int dotIndex = fileName.lastIndexOf(extSeperater); - if (dotIndex != -1) { - fileName = fileName.substring(0, dotIndex); - } maSet.setLabel(fileName); String arrayName = null; int m = 0; int valueLabel = 0; int call = 0; int detection = 0; List<String> markers = new ArrayList<String>(); try { in = new BufferedReader(new FileReader(file)); if(in != null){ try { String tempName = null; String header = null; while ((header = in.readLine()) != null) { /* * Adding comments to Experiment Information tab. *We will ignore the line which start with '!platform_table_end', '!platform_table_begin', '!sample_table_begin' *and '!sample_table_end' */ if (header.startsWith(commentSign1) || header.startsWith(commentSign2)) { if(!header.equalsIgnoreCase("!sample_table_end") && !header.equalsIgnoreCase("!sample_table_begin")){ // to be consistent, this detailed information should be used else where instead of as "description" field // maSet.setDescription(header.substring(1)); } } String[] temp = null; if(header.startsWith(commentSign3)){ temp = header.split("="); String temP = temp[0].trim(); if(temP.equals("^SAMPLE")){ tempName = temp[1].trim(); header = in.readLine(); if(!header.startsWith(commentSign2)){ arrayName = tempName; } } } if(header.startsWith(commentSign2)){ temp = header.split("="); String temP1 = temp[0].trim(); if(temP1.equals("!Sample_title")){ String temp1 = tempName + " (" +temp[1].trim() +")"; arrayName = temp1; } } if(!header.startsWith(commentSign1) && !header.startsWith(commentSign2) && !header.startsWith(commentSign3)){ if(header.subSequence(0, 6).equals("ID_REF")){ String[] valueLabels = null; valueLabels = header.split("\t"); for(int p=0; p < valueLabels.length; p++){ if(valueLabels[p].equals("VALUE")){ valueLabel = p; } if(valueLabels[p].equals("DETECTION_CALL") || valueLabels[p].equals("ABS_CALL")){ call = p; } if(valueLabels[p].equals("DETECTION P-VALUE") || valueLabels[p].equals("DETECTION_P")){ detection = p; } } } if(!header.subSequence(0, 6).equals("ID_REF")){ String[] mark = header.split("\t"); markers.add(mark[0]); String markerName = new String(mark[0].trim()); CSExpressionMarker marker = new CSExpressionMarker(m); marker.setLabel(markerName); maSet.getMarkers().add(m, marker); m++; } } } } catch (IOException e) { e.printStackTrace(); } } } catch (FileNotFoundException e) { e.printStackTrace(); } //Getting the markers size to include in a loop possibleMarkers = markers.size(); int i = 0; CSMicroarray array = new CSMicroarray(i, possibleMarkers, arrayName, DSMicroarraySet.affyTxtType); maSet.add(array); //This buffered reader is used to put insert marker values for one sample at a time from the Series file boolean absCallFound = false; boolean pValueFound = false; BufferedReader out = null; try { int j = 0; out = new BufferedReader(new FileReader(file)); try { String line = out.readLine(); while (line != null) { if(!line.startsWith(commentSign1) && !line.startsWith(commentSign2) && !line.startsWith(commentSign3)){ if(!line.subSequence(0, 6).equals("ID_REF")){ String[] values = line.split("\t"); char C; String ca = null; String valString = null; valString = values[valueLabel].trim(); if(valString == null){ Float v = Float.NaN; CSExpressionMarkerValue markerValue = new CSExpressionMarkerValue(v); DSMicroarray microarray = (DSMicroarray)maSet.get(0); microarray.setMarkerValue(j, markerValue); if (v.isNaN()) { markerValue.setMissing(true); } else { markerValue.setPresent(); } if(detection !=0 || call != 0) { if(detection != 0){ String token = null; token = values[detection].trim(); Object value = null; value = Double.valueOf(token); markerValue.setConfidence(( (Double) value).doubleValue()); pValueFound = true; } if(call != 0){ ca = values[call].trim(); C = ca.charAt(0); char Call = Character.toUpperCase(C); if (Call == PRESENT || Call == ABSENT || Call == MARGINAL){ this.detectionStatus = Call; absCallFound = true; if (!pValueFound){ switch (Call){ case PRESENT: markerValue.setPresent(); break; case ABSENT: markerValue.setAbsent(); break; case MARGINAL: markerValue.setMarginal(); break; } } } } if (!absCallFound && !pValueFound){ markerValue.setPresent(); } } }else { float value = Float.NaN; try { value = Float.parseFloat(valString); } catch (NumberFormatException nfe) { } // put values directly into CSMicroarray inside of // maSet Float v = value; CSExpressionMarkerValue markerValue = new CSExpressionMarkerValue( v); DSMicroarray microarray = (DSMicroarray)maSet.get(0); microarray.setMarkerValue(j, markerValue); if (v.isNaN()) { markerValue.setMissing(true); } else { markerValue.setPresent(); } if(detection !=0 || call != 0){ if(detection != 0){ String token = null; token = values[detection].trim(); Object value1 = null; value1 = Double.valueOf(token); markerValue.setConfidence(( (Double) value1).doubleValue()); pValueFound = true; } if(call != 0){ ca = values[call].trim(); C = ca.charAt(0); char Call = Character.toUpperCase(C); if (Call == PRESENT || Call == ABSENT || Call == MARGINAL){ this.detectionStatus = Call; absCallFound = true; if (!pValueFound){ switch (Call){ case PRESENT: markerValue.setPresent(); break; case ABSENT: markerValue.setAbsent(); break; case MARGINAL: markerValue.setMarginal(); break; } } } } if (!absCallFound && !pValueFound){ markerValue.setPresent(); } } } j++; } } line = out.readLine(); } String result = null; for (int n = 0; n < possibleMarkers; n++) { result = AffyAnnotationUtil.matchAffyAnnotationFile(maSet); if (result != null) { break; } } if (result == null) { AffyAnnotationUtil.matchAffyAnnotationFile(maSet); } else { maSet.setCompatibilityLabel(result); } for (DSGeneMarker marker : maSet.getMarkers()) { String token = marker.getLabel(); String[] locusResult = AnnotationParser.getInfo(token, AnnotationParser.LOCUSLINK); String locus = ""; if ((locusResult != null) && (!locusResult[0].trim().equals(""))) { locus = locusResult[0].trim(); } if (locus.compareTo("") != 0) { try { marker.setGeneId(Integer.parseInt(locus)); } catch (NumberFormatException e) { log.info("Couldn't parse locus id: " + locus); } } String[] geneNames = AnnotationParser.getInfo(token, AnnotationParser.ABREV); if (geneNames != null) { marker.setGeneName(geneNames[0]); } marker.getUnigene().set(token); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return maSet; } }
false
true
public DSMicroarraySet getMArraySet(File file) throws InputFileFormatException, InterruptedIOException { BufferedReader in = null; final int extSeperater = '.'; String fileName = file.getName(); int dotIndex = fileName.lastIndexOf(extSeperater); if (dotIndex != -1) { fileName = fileName.substring(0, dotIndex); } maSet.setLabel(fileName); String arrayName = null; int m = 0; int valueLabel = 0; int call = 0; int detection = 0; List<String> markers = new ArrayList<String>(); try { in = new BufferedReader(new FileReader(file)); if(in != null){ try { String tempName = null; String header = null; while ((header = in.readLine()) != null) { /* * Adding comments to Experiment Information tab. *We will ignore the line which start with '!platform_table_end', '!platform_table_begin', '!sample_table_begin' *and '!sample_table_end' */ if (header.startsWith(commentSign1) || header.startsWith(commentSign2)) { if(!header.equalsIgnoreCase("!sample_table_end") && !header.equalsIgnoreCase("!sample_table_begin")){ // to be consistent, this detailed information should be used else where instead of as "description" field // maSet.setDescription(header.substring(1)); } } String[] temp = null; if(header.startsWith(commentSign3)){ temp = header.split("="); String temP = temp[0].trim(); if(temP.equals("^SAMPLE")){ tempName = temp[1].trim(); header = in.readLine(); if(!header.startsWith(commentSign2)){ arrayName = tempName; } } } if(header.startsWith(commentSign2)){ temp = header.split("="); String temP1 = temp[0].trim(); if(temP1.equals("!Sample_title")){ String temp1 = tempName + " (" +temp[1].trim() +")"; arrayName = temp1; } } if(!header.startsWith(commentSign1) && !header.startsWith(commentSign2) && !header.startsWith(commentSign3)){ if(header.subSequence(0, 6).equals("ID_REF")){ String[] valueLabels = null; valueLabels = header.split("\t"); for(int p=0; p < valueLabels.length; p++){ if(valueLabels[p].equals("VALUE")){ valueLabel = p; } if(valueLabels[p].equals("DETECTION_CALL") || valueLabels[p].equals("ABS_CALL")){ call = p; } if(valueLabels[p].equals("DETECTION P-VALUE") || valueLabels[p].equals("DETECTION_P")){ detection = p; } } } if(!header.subSequence(0, 6).equals("ID_REF")){ String[] mark = header.split("\t"); markers.add(mark[0]); String markerName = new String(mark[0].trim()); CSExpressionMarker marker = new CSExpressionMarker(m); marker.setLabel(markerName); maSet.getMarkers().add(m, marker); m++; } } } } catch (IOException e) { e.printStackTrace(); } } } catch (FileNotFoundException e) { e.printStackTrace(); } //Getting the markers size to include in a loop possibleMarkers = markers.size(); int i = 0; CSMicroarray array = new CSMicroarray(i, possibleMarkers, arrayName, DSMicroarraySet.affyTxtType); maSet.add(array); //This buffered reader is used to put insert marker values for one sample at a time from the Series file boolean absCallFound = false; boolean pValueFound = false; BufferedReader out = null; try { int j = 0; out = new BufferedReader(new FileReader(file)); try { String line = out.readLine(); while (line != null) { if(!line.startsWith(commentSign1) && !line.startsWith(commentSign2) && !line.startsWith(commentSign3)){ if(!line.subSequence(0, 6).equals("ID_REF")){ String[] values = line.split("\t"); char C; String ca = null; String valString = null; valString = values[valueLabel].trim(); if(valString == null){ Float v = Float.NaN; CSExpressionMarkerValue markerValue = new CSExpressionMarkerValue(v); DSMicroarray microarray = (DSMicroarray)maSet.get(0); microarray.setMarkerValue(j, markerValue); if (v.isNaN()) { markerValue.setMissing(true); } else { markerValue.setPresent(); } if(detection !=0 || call != 0) { if(detection != 0){ String token = null; token = values[detection].trim(); Object value = null; value = Double.valueOf(token); markerValue.setConfidence(( (Double) value).doubleValue()); pValueFound = true; } if(call != 0){ ca = values[call].trim(); C = ca.charAt(0); char Call = Character.toUpperCase(C); if (Call == PRESENT || Call == ABSENT || Call == MARGINAL){ this.detectionStatus = Call; absCallFound = true; if (!pValueFound){ switch (Call){ case PRESENT: markerValue.setPresent(); break; case ABSENT: markerValue.setAbsent(); break; case MARGINAL: markerValue.setMarginal(); break; } } } } if (!absCallFound && !pValueFound){ markerValue.setPresent(); } } }else { float value = Float.NaN; try { value = Float.parseFloat(valString); } catch (NumberFormatException nfe) { } // put values directly into CSMicroarray inside of // maSet Float v = value; CSExpressionMarkerValue markerValue = new CSExpressionMarkerValue( v); DSMicroarray microarray = (DSMicroarray)maSet.get(0); microarray.setMarkerValue(j, markerValue); if (v.isNaN()) { markerValue.setMissing(true); } else { markerValue.setPresent(); } if(detection !=0 || call != 0){ if(detection != 0){ String token = null; token = values[detection].trim(); Object value1 = null; value1 = Double.valueOf(token); markerValue.setConfidence(( (Double) value1).doubleValue()); pValueFound = true; } if(call != 0){ ca = values[call].trim(); C = ca.charAt(0); char Call = Character.toUpperCase(C); if (Call == PRESENT || Call == ABSENT || Call == MARGINAL){ this.detectionStatus = Call; absCallFound = true; if (!pValueFound){ switch (Call){ case PRESENT: markerValue.setPresent(); break; case ABSENT: markerValue.setAbsent(); break; case MARGINAL: markerValue.setMarginal(); break; } } } } if (!absCallFound && !pValueFound){ markerValue.setPresent(); } } } j++; } } line = out.readLine(); } String result = null; for (int n = 0; n < possibleMarkers; n++) { result = AffyAnnotationUtil.matchAffyAnnotationFile(maSet); if (result != null) { break; } } if (result == null) { AffyAnnotationUtil.matchAffyAnnotationFile(maSet); } else { maSet.setCompatibilityLabel(result); } for (DSGeneMarker marker : maSet.getMarkers()) { String token = marker.getLabel(); String[] locusResult = AnnotationParser.getInfo(token, AnnotationParser.LOCUSLINK); String locus = ""; if ((locusResult != null) && (!locusResult[0].trim().equals(""))) { locus = locusResult[0].trim(); } if (locus.compareTo("") != 0) { try { marker.setGeneId(Integer.parseInt(locus)); } catch (NumberFormatException e) { log.info("Couldn't parse locus id: " + locus); } } String[] geneNames = AnnotationParser.getInfo(token, AnnotationParser.ABREV); if (geneNames != null) { marker.setGeneName(geneNames[0]); } marker.getUnigene().set(token); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return maSet; }
public DSMicroarraySet getMArraySet(File file) throws InputFileFormatException, InterruptedIOException { BufferedReader in = null; String fileName = file.getName(); maSet.setLabel(fileName); String arrayName = null; int m = 0; int valueLabel = 0; int call = 0; int detection = 0; List<String> markers = new ArrayList<String>(); try { in = new BufferedReader(new FileReader(file)); if(in != null){ try { String tempName = null; String header = null; while ((header = in.readLine()) != null) { /* * Adding comments to Experiment Information tab. *We will ignore the line which start with '!platform_table_end', '!platform_table_begin', '!sample_table_begin' *and '!sample_table_end' */ if (header.startsWith(commentSign1) || header.startsWith(commentSign2)) { if(!header.equalsIgnoreCase("!sample_table_end") && !header.equalsIgnoreCase("!sample_table_begin")){ // to be consistent, this detailed information should be used else where instead of as "description" field // maSet.setDescription(header.substring(1)); } } String[] temp = null; if(header.startsWith(commentSign3)){ temp = header.split("="); String temP = temp[0].trim(); if(temP.equals("^SAMPLE")){ tempName = temp[1].trim(); header = in.readLine(); if(!header.startsWith(commentSign2)){ arrayName = tempName; } } } if(header.startsWith(commentSign2)){ temp = header.split("="); String temP1 = temp[0].trim(); if(temP1.equals("!Sample_title")){ String temp1 = tempName + " (" +temp[1].trim() +")"; arrayName = temp1; } } if(!header.startsWith(commentSign1) && !header.startsWith(commentSign2) && !header.startsWith(commentSign3)){ if(header.subSequence(0, 6).equals("ID_REF")){ String[] valueLabels = null; valueLabels = header.split("\t"); for(int p=0; p < valueLabels.length; p++){ if(valueLabels[p].equals("VALUE")){ valueLabel = p; } if(valueLabels[p].equals("DETECTION_CALL") || valueLabels[p].equals("ABS_CALL")){ call = p; } if(valueLabels[p].equals("DETECTION P-VALUE") || valueLabels[p].equals("DETECTION_P")){ detection = p; } } } if(!header.subSequence(0, 6).equals("ID_REF")){ String[] mark = header.split("\t"); markers.add(mark[0]); String markerName = new String(mark[0].trim()); CSExpressionMarker marker = new CSExpressionMarker(m); marker.setLabel(markerName); maSet.getMarkers().add(m, marker); m++; } } } } catch (IOException e) { e.printStackTrace(); } } } catch (FileNotFoundException e) { e.printStackTrace(); } //Getting the markers size to include in a loop possibleMarkers = markers.size(); int i = 0; CSMicroarray array = new CSMicroarray(i, possibleMarkers, arrayName, DSMicroarraySet.affyTxtType); maSet.add(array); //This buffered reader is used to put insert marker values for one sample at a time from the Series file boolean absCallFound = false; boolean pValueFound = false; BufferedReader out = null; try { int j = 0; out = new BufferedReader(new FileReader(file)); try { String line = out.readLine(); while (line != null) { if(!line.startsWith(commentSign1) && !line.startsWith(commentSign2) && !line.startsWith(commentSign3)){ if(!line.subSequence(0, 6).equals("ID_REF")){ String[] values = line.split("\t"); char C; String ca = null; String valString = null; valString = values[valueLabel].trim(); if(valString == null){ Float v = Float.NaN; CSExpressionMarkerValue markerValue = new CSExpressionMarkerValue(v); DSMicroarray microarray = (DSMicroarray)maSet.get(0); microarray.setMarkerValue(j, markerValue); if (v.isNaN()) { markerValue.setMissing(true); } else { markerValue.setPresent(); } if(detection !=0 || call != 0) { if(detection != 0){ String token = null; token = values[detection].trim(); Object value = null; value = Double.valueOf(token); markerValue.setConfidence(( (Double) value).doubleValue()); pValueFound = true; } if(call != 0){ ca = values[call].trim(); C = ca.charAt(0); char Call = Character.toUpperCase(C); if (Call == PRESENT || Call == ABSENT || Call == MARGINAL){ this.detectionStatus = Call; absCallFound = true; if (!pValueFound){ switch (Call){ case PRESENT: markerValue.setPresent(); break; case ABSENT: markerValue.setAbsent(); break; case MARGINAL: markerValue.setMarginal(); break; } } } } if (!absCallFound && !pValueFound){ markerValue.setPresent(); } } }else { float value = Float.NaN; try { value = Float.parseFloat(valString); } catch (NumberFormatException nfe) { } // put values directly into CSMicroarray inside of // maSet Float v = value; CSExpressionMarkerValue markerValue = new CSExpressionMarkerValue( v); DSMicroarray microarray = (DSMicroarray)maSet.get(0); microarray.setMarkerValue(j, markerValue); if (v.isNaN()) { markerValue.setMissing(true); } else { markerValue.setPresent(); } if(detection !=0 || call != 0){ if(detection != 0){ String token = null; token = values[detection].trim(); Object value1 = null; value1 = Double.valueOf(token); markerValue.setConfidence(( (Double) value1).doubleValue()); pValueFound = true; } if(call != 0){ ca = values[call].trim(); C = ca.charAt(0); char Call = Character.toUpperCase(C); if (Call == PRESENT || Call == ABSENT || Call == MARGINAL){ this.detectionStatus = Call; absCallFound = true; if (!pValueFound){ switch (Call){ case PRESENT: markerValue.setPresent(); break; case ABSENT: markerValue.setAbsent(); break; case MARGINAL: markerValue.setMarginal(); break; } } } } if (!absCallFound && !pValueFound){ markerValue.setPresent(); } } } j++; } } line = out.readLine(); } String result = null; for (int n = 0; n < possibleMarkers; n++) { result = AffyAnnotationUtil.matchAffyAnnotationFile(maSet); if (result != null) { break; } } if (result == null) { AffyAnnotationUtil.matchAffyAnnotationFile(maSet); } else { maSet.setCompatibilityLabel(result); } for (DSGeneMarker marker : maSet.getMarkers()) { String token = marker.getLabel(); String[] locusResult = AnnotationParser.getInfo(token, AnnotationParser.LOCUSLINK); String locus = ""; if ((locusResult != null) && (!locusResult[0].trim().equals(""))) { locus = locusResult[0].trim(); } if (locus.compareTo("") != 0) { try { marker.setGeneId(Integer.parseInt(locus)); } catch (NumberFormatException e) { log.info("Couldn't parse locus id: " + locus); } } String[] geneNames = AnnotationParser.getInfo(token, AnnotationParser.ABREV); if (geneNames != null) { marker.setGeneName(geneNames[0]); } marker.getUnigene().set(token); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return maSet; }
diff --git a/main/src/cgeo/geocaching/connector/gc/GCMap.java b/main/src/cgeo/geocaching/connector/gc/GCMap.java index c71b859d6..681a1d73c 100644 --- a/main/src/cgeo/geocaching/connector/gc/GCMap.java +++ b/main/src/cgeo/geocaching/connector/gc/GCMap.java @@ -1,352 +1,355 @@ package cgeo.geocaching.connector.gc; import cgeo.geocaching.SearchResult; import cgeo.geocaching.Settings; import cgeo.geocaching.cgCache; import cgeo.geocaching.cgeoapplication; import cgeo.geocaching.enumerations.CacheSize; import cgeo.geocaching.enumerations.CacheType; import cgeo.geocaching.enumerations.LiveMapStrategy.Strategy; import cgeo.geocaching.enumerations.LiveMapStrategy.StrategyFlag; import cgeo.geocaching.enumerations.StatusCode; import cgeo.geocaching.geopoint.Geopoint; import cgeo.geocaching.geopoint.Units; import cgeo.geocaching.geopoint.Viewport; import cgeo.geocaching.network.Parameters; import cgeo.geocaching.ui.Formatter; import cgeo.geocaching.utils.LeastRecentlyUsedMap; import cgeo.geocaching.utils.Log; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.graphics.Bitmap; import java.text.ParseException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; public class GCMap { private static Viewport lastSearchViewport = null; public static SearchResult searchByGeocodes(Set<String> geocodes) { final SearchResult result = new SearchResult(); final String geocodeList = StringUtils.join(geocodes.toArray(), "|"); final String referer = GCConstants.URL_LIVE_MAP_DETAILS; try { final Parameters params = new Parameters("i", geocodeList, "_", String.valueOf(System.currentTimeMillis())); final String data = StringUtils.defaultString(Tile.requestMapInfo(referer, params, referer)); // Example JSON information // {"status":"success", // "data":[{"name":"Mission: Impossible","gc":"GC1234","g":"34c2e609-5246-4f91-9029-d6c02b0f2a82","available":true,"archived":false,"subrOnly":false,"li":false,"fp":"5","difficulty":{"text":3.5,"value":"3_5"},"terrain":{"text":1.0,"value":"1"},"hidden":"7/23/2001","container":{"text":"Regular","value":"regular.gif"},"type":{"text":"Unknown Cache","value":8},"owner":{"text":"Ca$h_Cacher","value":"2db18e69-6877-402a-848d-6362621424f6"}}, // {"name":"HP: Hannover - Sahlkamp","gc":"GC2Q97X","g":"a09149ca-00e0-4aa2-b332-db2b4dfb18d2","available":true,"archived":false,"subrOnly":false,"li":false,"fp":"0","difficulty":{"text":1.0,"value":"1"},"terrain":{"text":1.5,"value":"1_5"},"hidden":"5/29/2011","container":{"text":"Small","value":"small.gif"},"type":{"text":"Traditional Cache","value":2},"owner":{"text":"GeoM@n","value":"1deaa69e-6bcc-421d-95a1-7d32b468cb82"}}] // } final JSONObject json = new JSONObject(data); final String status = json.getString("status"); if (StringUtils.isBlank(status)) { throw new JSONException("No status inside JSON"); } if ("success".compareTo(status) != 0) { throw new JSONException("Wrong status inside JSON"); } final JSONArray dataArray = json.getJSONArray("data"); if (dataArray == null) { throw new JSONException("No data inside JSON"); } for (int j = 0; j < dataArray.length(); j++) { final cgCache cache = new cgCache(); JSONObject dataObject = dataArray.getJSONObject(j); cache.setName(dataObject.getString("name")); cache.setGeocode(dataObject.getString("gc")); cache.setGuid(dataObject.getString("g")); // 34c2e609-5246-4f91-9029-d6c02b0f2a82" cache.setDisabled(!dataObject.getBoolean("available")); cache.setArchived(dataObject.getBoolean("archived")); cache.setPremiumMembersOnly(dataObject.getBoolean("subrOnly")); // "li" seems to be "false" always cache.setFavoritePoints(Integer.parseInt(dataObject.getString("fp"))); JSONObject difficultyObj = dataObject.getJSONObject("difficulty"); cache.setDifficulty(Float.parseFloat(difficultyObj.getString("text"))); // 3.5 JSONObject terrainObj = dataObject.getJSONObject("terrain"); cache.setTerrain(Float.parseFloat(terrainObj.getString("text"))); // 1.5 cache.setHidden(Login.parseGcCustomDate(dataObject.getString("hidden"), "MM/dd/yyyy")); // 7/23/2001 JSONObject containerObj = dataObject.getJSONObject("container"); cache.setSize(CacheSize.getById(containerObj.getString("text"))); // Regular JSONObject typeObj = dataObject.getJSONObject("type"); cache.setType(CacheType.getByPattern(typeObj.getString("text"))); // Traditional Cache JSONObject ownerObj = dataObject.getJSONObject("owner"); cache.setOwnerDisplayName(ownerObj.getString("text")); result.addCache(cache); } } catch (JSONException e) { result.setError(StatusCode.UNKNOWN_ERROR); } catch (ParseException e) { result.setError(StatusCode.UNKNOWN_ERROR); } catch (NumberFormatException e) { result.setError(StatusCode.UNKNOWN_ERROR); } return result; } /** * @param data * Retrieved data. * @return SearchResult. Never null. */ public static SearchResult parseMapJSON(final String data, Tile tile, Bitmap bitmap, final Strategy strategy) { final SearchResult searchResult = new SearchResult(); try { final LeastRecentlyUsedMap<String, String> nameCache = new LeastRecentlyUsedMap.LruCache<String, String>(2000); // JSON id, cache name if (StringUtils.isEmpty(data)) { throw new JSONException("No page given"); } // Example JSON information // {"grid":[....], // "keys":["","55_55","55_54","17_25","55_53","17_27","17_26","57_53","57_55","3_62","3_61","57_54","3_60","15_27","15_26","15_25","4_60","4_61","4_62","16_25","16_26","16_27","2_62","2_60","2_61","56_53","56_54","56_55"], // "data":{"55_55":[{"i":"gEaR","n":"Spiel & Sport"}],"55_54":[{"i":"gEaR","n":"Spiel & Sport"}],"17_25":[{"i":"Rkzt","n":"EDSSW: Rathaus "}],"55_53":[{"i":"gEaR","n":"Spiel & Sport"}],"17_27":[{"i":"Rkzt","n":"EDSSW: Rathaus "}],"17_26":[{"i":"Rkzt","n":"EDSSW: Rathaus "}],"57_53":[{"i":"gEaR","n":"Spiel & Sport"}],"57_55":[{"i":"gEaR","n":"Spiel & Sport"}],"3_62":[{"i":"gOWz","n":"Baumarktserie - Wer Wo Was -"}],"3_61":[{"i":"gOWz","n":"Baumarktserie - Wer Wo Was -"}],"57_54":[{"i":"gEaR","n":"Spiel & Sport"}],"3_60":[{"i":"gOWz","n":"Baumarktserie - Wer Wo Was -"}],"15_27":[{"i":"Rkzt","n":"EDSSW: Rathaus "}],"15_26":[{"i":"Rkzt","n":"EDSSW: Rathaus "}],"15_25":[{"i":"Rkzt","n":"EDSSW: Rathaus "}],"4_60":[{"i":"gOWz","n":"Baumarktserie - Wer Wo Was -"}],"4_61":[{"i":"gOWz","n":"Baumarktserie - Wer Wo Was -"}],"4_62":[{"i":"gOWz","n":"Baumarktserie - Wer Wo Was -"}],"16_25":[{"i":"Rkzt","n":"EDSSW: Rathaus "}],"16_26":[{"i":"Rkzt","n":"EDSSW: Rathaus "}],"16_27":[{"i":"Rkzt","n":"EDSSW: Rathaus "}],"2_62":[{"i":"gOWz","n":"Baumarktserie - Wer Wo Was -"}],"2_60":[{"i":"gOWz","n":"Baumarktserie - Wer Wo Was -"}],"2_61":[{"i":"gOWz","n":"Baumarktserie - Wer Wo Was -"}],"56_53":[{"i":"gEaR","n":"Spiel & Sport"}],"56_54":[{"i":"gEaR","n":"Spiel & Sport"}],"56_55":[{"i":"gEaR","n":"Spiel & Sport"}]} // } final JSONObject json = new JSONObject(data); final JSONArray grid = json.getJSONArray("grid"); if (grid == null || grid.length() != (UTFGrid.GRID_MAXY + 1)) { throw new JSONException("No grid inside JSON"); } final JSONArray keys = json.getJSONArray("keys"); if (keys == null) { throw new JSONException("No keys inside JSON"); } final JSONObject dataObject = json.getJSONObject("data"); if (dataObject == null) { throw new JSONException("No data inside JSON"); } /* * Optimization: the grid can get ignored. The keys are the grid position in the format x_y * It's not used at the moment due to optimizations * But maybe we need it some day... * * // attach all keys with the cache positions in the tile * Map<String, UTFGridPosition> keyPositions = new HashMap<String, UTFGridPosition>(); // JSON key, (x/y) in * grid * for (int y = 0; y < grid.length(); y++) { * String rowUTF8 = grid.getString(y); * if (rowUTF8.length() != (UTFGrid.GRID_MAXX + 1)) { * throw new JSONException("Grid has wrong size"); * } * * for (int x = 0; x < UTFGrid.GRID_MAXX; x++) { * char c = rowUTF8.charAt(x); * if (c != ' ') { * short id = UTFGrid.getUTFGridId(c); * keyPositions.put(keys.getString(id), new UTFGridPosition(x, y)); * } * } * } */ // iterate over the data and construct all caches in this tile Map<String, List<UTFGridPosition>> positions = new HashMap<String, List<UTFGridPosition>>(); // JSON id as key for (int i = 1; i < keys.length(); i++) { // index 0 is empty String key = keys.getString(i); if (StringUtils.isNotBlank(key)) { UTFGridPosition pos = UTFGridPosition.fromString(key); JSONArray dataForKey = dataObject.getJSONArray(key); for (int j = 0; j < dataForKey.length(); j++) { JSONObject cacheInfo = dataForKey.getJSONObject(j); String id = cacheInfo.getString("i"); nameCache.put(id, cacheInfo.getString("n")); List<UTFGridPosition> listOfPositions = positions.get(id); if (listOfPositions == null) { listOfPositions = new ArrayList<UTFGridPosition>(); positions.put(id, listOfPositions); } listOfPositions.add(pos); } } } for (Entry<String, List<UTFGridPosition>> entry : positions.entrySet()) { String id = entry.getKey(); List<UTFGridPosition> pos = entry.getValue(); UTFGridPosition xy = UTFGrid.getPositionInGrid(pos); cgCache cache = new cgCache(); cache.setDetailed(false); cache.setReliableLatLon(false); cache.setGeocode(id); cache.setName(nameCache.get(id)); cache.setZoomlevel(tile.getZoomlevel()); cache.setCoords(tile.getCoord(xy)); if (strategy.flags.contains(StrategyFlag.PARSE_TILES) && positions.size() < 64 && bitmap != null) { // don't parse if there are too many caches. The decoding would return too much wrong results IconDecoder.parseMapPNG(cache, bitmap, xy, tile.getZoomlevel()); } else { cache.setType(CacheType.UNKNOWN); } boolean exclude = false; if (Settings.isExcludeMyCaches() && (cache.isFound() || cache.isOwn())) { // workaround for BM exclude = true; } if (Settings.isExcludeDisabledCaches() && cache.isDisabled()) { exclude = true; } + if (Settings.getCacheType() != CacheType.ALL && Settings.getCacheType() != cache.getType() && cache.getType() != CacheType.UNKNOWN) { // workaround for BM + exclude = true; + } if (!exclude) { searchResult.addCache(cache); } } Log.d("Retrieved " + searchResult.getCount() + " caches for tile " + tile.toString()); } catch (Exception e) { Log.e("GCBase.parseMapJSON", e); } return searchResult; } /** * Searches the view port on the live map with Strategy.AUTO * * @param viewport * Area to search * @param tokens * Live map tokens * @return */ public static SearchResult searchByViewport(final Viewport viewport, final String[] tokens) { int speed = (int) cgeoapplication.getInstance().currentGeo().getSpeed() * 60 * 60 / 1000; // in km/h Strategy strategy = Settings.getLiveMapStrategy(); if (strategy == Strategy.AUTO) { strategy = speed >= 30 ? Strategy.FAST : Strategy.DETAILED; } SearchResult result = searchByViewport(viewport, tokens, strategy); if (Settings.isDebug()) { StringBuilder text = new StringBuilder(Formatter.SEPARATOR).append(strategy.getL10n()).append(Formatter.SEPARATOR).append(Units.getSpeed(speed)); result.setUrl(result.getUrl() + text); } return result; } /** * Searches the view port on the live map for caches. * The strategy dictates if only live map information is used or if an additional * searchByCoordinates query is issued. * * @param viewport * Area to search * @param tokens * Live map tokens * @param strategy * Strategy for data retrieval and parsing, @see Strategy * @return */ private static SearchResult searchByViewport(final Viewport viewport, final String[] tokens, Strategy strategy) { Log.d("GCBase.searchByViewport" + viewport.toString()); final SearchResult searchResult = new SearchResult(); searchResult.setUrl(GCConstants.URL_LIVE_MAP + "?ll=" + viewport.getCenter().getLatitude() + "," + viewport.getCenter().getLongitude()); if (strategy.flags.contains(StrategyFlag.LOAD_TILES)) { final Set<Tile> tiles = Tile.getTilesForViewport(viewport); for (Tile tile : tiles) { if (!Tile.Cache.contains(tile)) { final Parameters params = new Parameters( "x", String.valueOf(tile.getX()), "y", String.valueOf(tile.getY()), "z", String.valueOf(tile.getZoomlevel()), "ep", "1"); if (tokens != null) { params.put("k", tokens[0], "st", tokens[1]); } if (Settings.isExcludeMyCaches()) { // works only for PM params.put("hf", "1", "hh", "1"); // hide found, hide hidden } if (Settings.getCacheType() == CacheType.TRADITIONAL) { params.put("ect", "9,5,3,6,453,13,1304,137,11,4,8,1858"); // 2 = tradi 3 = multi 8 = mystery } else if (Settings.getCacheType() == CacheType.MULTI) { params.put("ect", "9,5,2,6,453,13,1304,137,11,4,8,1858"); } else if (Settings.getCacheType() == CacheType.MYSTERY) { params.put("ect", "9,5,3,6,453,13,1304,137,11,4,2,1858"); } if (tile.getZoomlevel() != 14) { params.put("_", String.valueOf(System.currentTimeMillis())); } // TODO: other types t.b.d // The PNG must be requested first, otherwise the following request would always return with 204 - No Content Bitmap bitmap = Tile.requestMapTile(params); // Check bitmap size if (bitmap != null && (bitmap.getWidth() != Tile.TILE_SIZE || bitmap.getHeight() != Tile.TILE_SIZE)) { bitmap.recycle(); bitmap = null; } String data = Tile.requestMapInfo(GCConstants.URL_MAP_INFO, params, GCConstants.URL_LIVE_MAP); if (StringUtils.isEmpty(data)) { Log.e("GCBase.searchByViewport: No data from server for tile (" + tile.getX() + "/" + tile.getY() + ")"); } else { final SearchResult search = GCMap.parseMapJSON(data, tile, bitmap, strategy); if (search == null || CollectionUtils.isEmpty(search.getGeocodes())) { Log.e("GCBase.searchByViewport: No cache parsed for viewport " + viewport); } else { searchResult.addGeocodes(search.getGeocodes()); } Tile.Cache.add(tile); } // release native bitmap memory if (bitmap != null) { bitmap.recycle(); } } } } if (strategy.flags.contains(StrategyFlag.SEARCH_NEARBY)) { final Geopoint center = viewport.getCenter(); if ((lastSearchViewport == null) || !lastSearchViewport.contains(center)) { SearchResult search = GCParser.searchByCoords(center, Settings.getCacheType(), false); if (search != null && !search.isEmpty()) { final Set<String> geocodes = search.getGeocodes(); if (Settings.isPremiumMember()) { lastSearchViewport = cgeoapplication.getInstance().getBounds(geocodes); } else { lastSearchViewport = new Viewport(center, center); } searchResult.addGeocodes(geocodes); } } } return searchResult; } }
true
true
public static SearchResult parseMapJSON(final String data, Tile tile, Bitmap bitmap, final Strategy strategy) { final SearchResult searchResult = new SearchResult(); try { final LeastRecentlyUsedMap<String, String> nameCache = new LeastRecentlyUsedMap.LruCache<String, String>(2000); // JSON id, cache name if (StringUtils.isEmpty(data)) { throw new JSONException("No page given"); } // Example JSON information // {"grid":[....], // "keys":["","55_55","55_54","17_25","55_53","17_27","17_26","57_53","57_55","3_62","3_61","57_54","3_60","15_27","15_26","15_25","4_60","4_61","4_62","16_25","16_26","16_27","2_62","2_60","2_61","56_53","56_54","56_55"], // "data":{"55_55":[{"i":"gEaR","n":"Spiel & Sport"}],"55_54":[{"i":"gEaR","n":"Spiel & Sport"}],"17_25":[{"i":"Rkzt","n":"EDSSW: Rathaus "}],"55_53":[{"i":"gEaR","n":"Spiel & Sport"}],"17_27":[{"i":"Rkzt","n":"EDSSW: Rathaus "}],"17_26":[{"i":"Rkzt","n":"EDSSW: Rathaus "}],"57_53":[{"i":"gEaR","n":"Spiel & Sport"}],"57_55":[{"i":"gEaR","n":"Spiel & Sport"}],"3_62":[{"i":"gOWz","n":"Baumarktserie - Wer Wo Was -"}],"3_61":[{"i":"gOWz","n":"Baumarktserie - Wer Wo Was -"}],"57_54":[{"i":"gEaR","n":"Spiel & Sport"}],"3_60":[{"i":"gOWz","n":"Baumarktserie - Wer Wo Was -"}],"15_27":[{"i":"Rkzt","n":"EDSSW: Rathaus "}],"15_26":[{"i":"Rkzt","n":"EDSSW: Rathaus "}],"15_25":[{"i":"Rkzt","n":"EDSSW: Rathaus "}],"4_60":[{"i":"gOWz","n":"Baumarktserie - Wer Wo Was -"}],"4_61":[{"i":"gOWz","n":"Baumarktserie - Wer Wo Was -"}],"4_62":[{"i":"gOWz","n":"Baumarktserie - Wer Wo Was -"}],"16_25":[{"i":"Rkzt","n":"EDSSW: Rathaus "}],"16_26":[{"i":"Rkzt","n":"EDSSW: Rathaus "}],"16_27":[{"i":"Rkzt","n":"EDSSW: Rathaus "}],"2_62":[{"i":"gOWz","n":"Baumarktserie - Wer Wo Was -"}],"2_60":[{"i":"gOWz","n":"Baumarktserie - Wer Wo Was -"}],"2_61":[{"i":"gOWz","n":"Baumarktserie - Wer Wo Was -"}],"56_53":[{"i":"gEaR","n":"Spiel & Sport"}],"56_54":[{"i":"gEaR","n":"Spiel & Sport"}],"56_55":[{"i":"gEaR","n":"Spiel & Sport"}]} // } final JSONObject json = new JSONObject(data); final JSONArray grid = json.getJSONArray("grid"); if (grid == null || grid.length() != (UTFGrid.GRID_MAXY + 1)) { throw new JSONException("No grid inside JSON"); } final JSONArray keys = json.getJSONArray("keys"); if (keys == null) { throw new JSONException("No keys inside JSON"); } final JSONObject dataObject = json.getJSONObject("data"); if (dataObject == null) { throw new JSONException("No data inside JSON"); } /* * Optimization: the grid can get ignored. The keys are the grid position in the format x_y * It's not used at the moment due to optimizations * But maybe we need it some day... * * // attach all keys with the cache positions in the tile * Map<String, UTFGridPosition> keyPositions = new HashMap<String, UTFGridPosition>(); // JSON key, (x/y) in * grid * for (int y = 0; y < grid.length(); y++) { * String rowUTF8 = grid.getString(y); * if (rowUTF8.length() != (UTFGrid.GRID_MAXX + 1)) { * throw new JSONException("Grid has wrong size"); * } * * for (int x = 0; x < UTFGrid.GRID_MAXX; x++) { * char c = rowUTF8.charAt(x); * if (c != ' ') { * short id = UTFGrid.getUTFGridId(c); * keyPositions.put(keys.getString(id), new UTFGridPosition(x, y)); * } * } * } */ // iterate over the data and construct all caches in this tile Map<String, List<UTFGridPosition>> positions = new HashMap<String, List<UTFGridPosition>>(); // JSON id as key for (int i = 1; i < keys.length(); i++) { // index 0 is empty String key = keys.getString(i); if (StringUtils.isNotBlank(key)) { UTFGridPosition pos = UTFGridPosition.fromString(key); JSONArray dataForKey = dataObject.getJSONArray(key); for (int j = 0; j < dataForKey.length(); j++) { JSONObject cacheInfo = dataForKey.getJSONObject(j); String id = cacheInfo.getString("i"); nameCache.put(id, cacheInfo.getString("n")); List<UTFGridPosition> listOfPositions = positions.get(id); if (listOfPositions == null) { listOfPositions = new ArrayList<UTFGridPosition>(); positions.put(id, listOfPositions); } listOfPositions.add(pos); } } } for (Entry<String, List<UTFGridPosition>> entry : positions.entrySet()) { String id = entry.getKey(); List<UTFGridPosition> pos = entry.getValue(); UTFGridPosition xy = UTFGrid.getPositionInGrid(pos); cgCache cache = new cgCache(); cache.setDetailed(false); cache.setReliableLatLon(false); cache.setGeocode(id); cache.setName(nameCache.get(id)); cache.setZoomlevel(tile.getZoomlevel()); cache.setCoords(tile.getCoord(xy)); if (strategy.flags.contains(StrategyFlag.PARSE_TILES) && positions.size() < 64 && bitmap != null) { // don't parse if there are too many caches. The decoding would return too much wrong results IconDecoder.parseMapPNG(cache, bitmap, xy, tile.getZoomlevel()); } else { cache.setType(CacheType.UNKNOWN); } boolean exclude = false; if (Settings.isExcludeMyCaches() && (cache.isFound() || cache.isOwn())) { // workaround for BM exclude = true; } if (Settings.isExcludeDisabledCaches() && cache.isDisabled()) { exclude = true; } if (!exclude) { searchResult.addCache(cache); } } Log.d("Retrieved " + searchResult.getCount() + " caches for tile " + tile.toString()); } catch (Exception e) { Log.e("GCBase.parseMapJSON", e); } return searchResult; }
public static SearchResult parseMapJSON(final String data, Tile tile, Bitmap bitmap, final Strategy strategy) { final SearchResult searchResult = new SearchResult(); try { final LeastRecentlyUsedMap<String, String> nameCache = new LeastRecentlyUsedMap.LruCache<String, String>(2000); // JSON id, cache name if (StringUtils.isEmpty(data)) { throw new JSONException("No page given"); } // Example JSON information // {"grid":[....], // "keys":["","55_55","55_54","17_25","55_53","17_27","17_26","57_53","57_55","3_62","3_61","57_54","3_60","15_27","15_26","15_25","4_60","4_61","4_62","16_25","16_26","16_27","2_62","2_60","2_61","56_53","56_54","56_55"], // "data":{"55_55":[{"i":"gEaR","n":"Spiel & Sport"}],"55_54":[{"i":"gEaR","n":"Spiel & Sport"}],"17_25":[{"i":"Rkzt","n":"EDSSW: Rathaus "}],"55_53":[{"i":"gEaR","n":"Spiel & Sport"}],"17_27":[{"i":"Rkzt","n":"EDSSW: Rathaus "}],"17_26":[{"i":"Rkzt","n":"EDSSW: Rathaus "}],"57_53":[{"i":"gEaR","n":"Spiel & Sport"}],"57_55":[{"i":"gEaR","n":"Spiel & Sport"}],"3_62":[{"i":"gOWz","n":"Baumarktserie - Wer Wo Was -"}],"3_61":[{"i":"gOWz","n":"Baumarktserie - Wer Wo Was -"}],"57_54":[{"i":"gEaR","n":"Spiel & Sport"}],"3_60":[{"i":"gOWz","n":"Baumarktserie - Wer Wo Was -"}],"15_27":[{"i":"Rkzt","n":"EDSSW: Rathaus "}],"15_26":[{"i":"Rkzt","n":"EDSSW: Rathaus "}],"15_25":[{"i":"Rkzt","n":"EDSSW: Rathaus "}],"4_60":[{"i":"gOWz","n":"Baumarktserie - Wer Wo Was -"}],"4_61":[{"i":"gOWz","n":"Baumarktserie - Wer Wo Was -"}],"4_62":[{"i":"gOWz","n":"Baumarktserie - Wer Wo Was -"}],"16_25":[{"i":"Rkzt","n":"EDSSW: Rathaus "}],"16_26":[{"i":"Rkzt","n":"EDSSW: Rathaus "}],"16_27":[{"i":"Rkzt","n":"EDSSW: Rathaus "}],"2_62":[{"i":"gOWz","n":"Baumarktserie - Wer Wo Was -"}],"2_60":[{"i":"gOWz","n":"Baumarktserie - Wer Wo Was -"}],"2_61":[{"i":"gOWz","n":"Baumarktserie - Wer Wo Was -"}],"56_53":[{"i":"gEaR","n":"Spiel & Sport"}],"56_54":[{"i":"gEaR","n":"Spiel & Sport"}],"56_55":[{"i":"gEaR","n":"Spiel & Sport"}]} // } final JSONObject json = new JSONObject(data); final JSONArray grid = json.getJSONArray("grid"); if (grid == null || grid.length() != (UTFGrid.GRID_MAXY + 1)) { throw new JSONException("No grid inside JSON"); } final JSONArray keys = json.getJSONArray("keys"); if (keys == null) { throw new JSONException("No keys inside JSON"); } final JSONObject dataObject = json.getJSONObject("data"); if (dataObject == null) { throw new JSONException("No data inside JSON"); } /* * Optimization: the grid can get ignored. The keys are the grid position in the format x_y * It's not used at the moment due to optimizations * But maybe we need it some day... * * // attach all keys with the cache positions in the tile * Map<String, UTFGridPosition> keyPositions = new HashMap<String, UTFGridPosition>(); // JSON key, (x/y) in * grid * for (int y = 0; y < grid.length(); y++) { * String rowUTF8 = grid.getString(y); * if (rowUTF8.length() != (UTFGrid.GRID_MAXX + 1)) { * throw new JSONException("Grid has wrong size"); * } * * for (int x = 0; x < UTFGrid.GRID_MAXX; x++) { * char c = rowUTF8.charAt(x); * if (c != ' ') { * short id = UTFGrid.getUTFGridId(c); * keyPositions.put(keys.getString(id), new UTFGridPosition(x, y)); * } * } * } */ // iterate over the data and construct all caches in this tile Map<String, List<UTFGridPosition>> positions = new HashMap<String, List<UTFGridPosition>>(); // JSON id as key for (int i = 1; i < keys.length(); i++) { // index 0 is empty String key = keys.getString(i); if (StringUtils.isNotBlank(key)) { UTFGridPosition pos = UTFGridPosition.fromString(key); JSONArray dataForKey = dataObject.getJSONArray(key); for (int j = 0; j < dataForKey.length(); j++) { JSONObject cacheInfo = dataForKey.getJSONObject(j); String id = cacheInfo.getString("i"); nameCache.put(id, cacheInfo.getString("n")); List<UTFGridPosition> listOfPositions = positions.get(id); if (listOfPositions == null) { listOfPositions = new ArrayList<UTFGridPosition>(); positions.put(id, listOfPositions); } listOfPositions.add(pos); } } } for (Entry<String, List<UTFGridPosition>> entry : positions.entrySet()) { String id = entry.getKey(); List<UTFGridPosition> pos = entry.getValue(); UTFGridPosition xy = UTFGrid.getPositionInGrid(pos); cgCache cache = new cgCache(); cache.setDetailed(false); cache.setReliableLatLon(false); cache.setGeocode(id); cache.setName(nameCache.get(id)); cache.setZoomlevel(tile.getZoomlevel()); cache.setCoords(tile.getCoord(xy)); if (strategy.flags.contains(StrategyFlag.PARSE_TILES) && positions.size() < 64 && bitmap != null) { // don't parse if there are too many caches. The decoding would return too much wrong results IconDecoder.parseMapPNG(cache, bitmap, xy, tile.getZoomlevel()); } else { cache.setType(CacheType.UNKNOWN); } boolean exclude = false; if (Settings.isExcludeMyCaches() && (cache.isFound() || cache.isOwn())) { // workaround for BM exclude = true; } if (Settings.isExcludeDisabledCaches() && cache.isDisabled()) { exclude = true; } if (Settings.getCacheType() != CacheType.ALL && Settings.getCacheType() != cache.getType() && cache.getType() != CacheType.UNKNOWN) { // workaround for BM exclude = true; } if (!exclude) { searchResult.addCache(cache); } } Log.d("Retrieved " + searchResult.getCount() + " caches for tile " + tile.toString()); } catch (Exception e) { Log.e("GCBase.parseMapJSON", e); } return searchResult; }
diff --git a/src/main/java/com/ardublock/translator/block/MessageBlock.java b/src/main/java/com/ardublock/translator/block/MessageBlock.java index 98512d4..cc5971e 100644 --- a/src/main/java/com/ardublock/translator/block/MessageBlock.java +++ b/src/main/java/com/ardublock/translator/block/MessageBlock.java @@ -1,34 +1,36 @@ package com.ardublock.translator.block; import com.ardublock.translator.Translator; import com.ardublock.translator.block.exception.SocketNullException; import com.ardublock.translator.block.exception.SubroutineNotDeclaredException; public class MessageBlock extends TranslatorBlock { public MessageBlock(Long blockId, Translator translator, String codePrefix, String codeSuffix, String label) { super(blockId, translator, codePrefix, codeSuffix, label); } @Override public String toCode() throws SocketNullException, SubroutineNotDeclaredException { //TODO take out special character String ret; ret = label.replaceAll("\\\\", "\\\\\\\\"); ret = ret.replaceAll("\"", "\\\\\""); //A way to have 'space' at start or end of message ret = ret.replaceAll("<&space>", " "); //A way to have other block settings applied but no message sent ret = ret.replaceAll("<&nothing>", ""); + // A way to add \t to messages + ret = ret.replaceAll("<&tab>", "\\\\t"); ret = codePrefix + "\"" + ret + "\"" + codeSuffix; TranslatorBlock translatorBlock = this.getTranslatorBlockAtSocket(0, codePrefix, codeSuffix); if (translatorBlock != null) { ret = ret + translatorBlock.toCode(); } return ret; } }
true
true
public String toCode() throws SocketNullException, SubroutineNotDeclaredException { //TODO take out special character String ret; ret = label.replaceAll("\\\\", "\\\\\\\\"); ret = ret.replaceAll("\"", "\\\\\""); //A way to have 'space' at start or end of message ret = ret.replaceAll("<&space>", " "); //A way to have other block settings applied but no message sent ret = ret.replaceAll("<&nothing>", ""); ret = codePrefix + "\"" + ret + "\"" + codeSuffix; TranslatorBlock translatorBlock = this.getTranslatorBlockAtSocket(0, codePrefix, codeSuffix); if (translatorBlock != null) { ret = ret + translatorBlock.toCode(); } return ret; }
public String toCode() throws SocketNullException, SubroutineNotDeclaredException { //TODO take out special character String ret; ret = label.replaceAll("\\\\", "\\\\\\\\"); ret = ret.replaceAll("\"", "\\\\\""); //A way to have 'space' at start or end of message ret = ret.replaceAll("<&space>", " "); //A way to have other block settings applied but no message sent ret = ret.replaceAll("<&nothing>", ""); // A way to add \t to messages ret = ret.replaceAll("<&tab>", "\\\\t"); ret = codePrefix + "\"" + ret + "\"" + codeSuffix; TranslatorBlock translatorBlock = this.getTranslatorBlockAtSocket(0, codePrefix, codeSuffix); if (translatorBlock != null) { ret = ret + translatorBlock.toCode(); } return ret; }
diff --git a/Freerider/src/no/ntnu/idi/socialhitchhiking/service/JourneyReminder.java b/Freerider/src/no/ntnu/idi/socialhitchhiking/service/JourneyReminder.java index 03a8c63..318f5d4 100644 --- a/Freerider/src/no/ntnu/idi/socialhitchhiking/service/JourneyReminder.java +++ b/Freerider/src/no/ntnu/idi/socialhitchhiking/service/JourneyReminder.java @@ -1,95 +1,96 @@ /******************************************************************************* * @contributor(s): Freerider Team (Group 4, IT2901 Fall 2012, NTNU) * @contributor(s): Freerider Team 2 (Group 3, IT2901 Spring 2013, NTNU) * @version: 2.0 * * Copyright 2013 Freerider Team 2 * * 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. ******************************************************************************/ /** * @contributor(s): Freerider Team (Group 4, IT2901 Fall 2012, NTNU) * @version: 1.0 * * Copyright (C) 2012 Freerider Team. * * Licensed under the Apache License, Version 2.0. * 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 no.ntnu.idi.socialhitchhiking.service; import java.util.Calendar; import java.util.List; import java.util.concurrent.ExecutionException; import no.ntnu.idi.freerider.model.Journey; import no.ntnu.idi.socialhitchhiking.SocialHitchhikingApplication; import no.ntnu.idi.socialhitchhiking.utility.SendNotification; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; public class JourneyReminder extends BroadcastReceiver{ SocialHitchhikingApplication app; @Override public void onReceive(Context con, Intent intent) { app = (SocialHitchhikingApplication) con.getApplicationContext(); List<Journey> jour; if(app.getSettings().isPullNotifications()){ try { jour = app.sendJourneysRequest(); } catch (InterruptedException e) { // TODO Auto-generated catch block jour = app.getJourneys(); } catch (ExecutionException e) { // TODO Auto-generated catch block jour = app.getJourneys(); } } else jour = app.getJourneys(); Calendar nextHour = Calendar.getInstance(); nextHour.add(Calendar.HOUR_OF_DAY, 1); + Calendar now = Calendar.getInstance(); if(jour == null || jour.size() == 0) return; int count = 0; for (Journey j : jour) { - if(j.getStart().before(nextHour)){ + if(j.getStart().before(nextHour) && j.getStart().after(now)){ if(!app.isKey("journeyreminder"+j.getSerial())){ app.setKeyState("journeyreminder"+j.getSerial(), true); count++; } } } if(count > 1)SendNotification.create(app, SendNotification.LIST_JOURNEY, "Reminder, Upcoming trips", "You have "+count+" scheduled trips in less than one hour from now", "Scheduled Journey"); else if(count > 0)SendNotification.create(app, SendNotification.LIST_JOURNEY, "Reminder, Upcoming trip", "You have a scheduled trip in less than one hour from now", "Scheduled Journey"); } }
false
true
public void onReceive(Context con, Intent intent) { app = (SocialHitchhikingApplication) con.getApplicationContext(); List<Journey> jour; if(app.getSettings().isPullNotifications()){ try { jour = app.sendJourneysRequest(); } catch (InterruptedException e) { // TODO Auto-generated catch block jour = app.getJourneys(); } catch (ExecutionException e) { // TODO Auto-generated catch block jour = app.getJourneys(); } } else jour = app.getJourneys(); Calendar nextHour = Calendar.getInstance(); nextHour.add(Calendar.HOUR_OF_DAY, 1); if(jour == null || jour.size() == 0) return; int count = 0; for (Journey j : jour) { if(j.getStart().before(nextHour)){ if(!app.isKey("journeyreminder"+j.getSerial())){ app.setKeyState("journeyreminder"+j.getSerial(), true); count++; } } } if(count > 1)SendNotification.create(app, SendNotification.LIST_JOURNEY, "Reminder, Upcoming trips", "You have "+count+" scheduled trips in less than one hour from now", "Scheduled Journey"); else if(count > 0)SendNotification.create(app, SendNotification.LIST_JOURNEY, "Reminder, Upcoming trip", "You have a scheduled trip in less than one hour from now", "Scheduled Journey"); }
public void onReceive(Context con, Intent intent) { app = (SocialHitchhikingApplication) con.getApplicationContext(); List<Journey> jour; if(app.getSettings().isPullNotifications()){ try { jour = app.sendJourneysRequest(); } catch (InterruptedException e) { // TODO Auto-generated catch block jour = app.getJourneys(); } catch (ExecutionException e) { // TODO Auto-generated catch block jour = app.getJourneys(); } } else jour = app.getJourneys(); Calendar nextHour = Calendar.getInstance(); nextHour.add(Calendar.HOUR_OF_DAY, 1); Calendar now = Calendar.getInstance(); if(jour == null || jour.size() == 0) return; int count = 0; for (Journey j : jour) { if(j.getStart().before(nextHour) && j.getStart().after(now)){ if(!app.isKey("journeyreminder"+j.getSerial())){ app.setKeyState("journeyreminder"+j.getSerial(), true); count++; } } } if(count > 1)SendNotification.create(app, SendNotification.LIST_JOURNEY, "Reminder, Upcoming trips", "You have "+count+" scheduled trips in less than one hour from now", "Scheduled Journey"); else if(count > 0)SendNotification.create(app, SendNotification.LIST_JOURNEY, "Reminder, Upcoming trip", "You have a scheduled trip in less than one hour from now", "Scheduled Journey"); }
diff --git a/srcj/com/sun/electric/plugins/j3d/J3DKeyBehavior.java b/srcj/com/sun/electric/plugins/j3d/J3DKeyBehavior.java index 0c423eafa..78f189319 100644 --- a/srcj/com/sun/electric/plugins/j3d/J3DKeyBehavior.java +++ b/srcj/com/sun/electric/plugins/j3d/J3DKeyBehavior.java @@ -1,272 +1,273 @@ /* -*- tab-width: 4 -*- * * Electric(tm) VLSI Design System * * File: J3DKeyBehavior.java * Written by Gilda Garreton, Sun Microsystems. * * Copyright (c) 2005 Sun Microsystems and Static Free Software * * Electric(tm) 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. * * Electric(tm) 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 Electric(tm); see the file COPYING. If not, write to * the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, Mass 02111-1307, USA. */ package com.sun.electric.plugins.j3d; import java.awt.AWTEvent; import java.awt.event.*; import java.util.Enumeration; import java.util.Arrays; import javax.media.j3d.*; import javax.vecmath.*; /** Inspired in example found in Daniel Selman's book "Java 3D Programming" * For more information about the original example, contact Daniel Selman: [email protected] * Free Software Foundation, Inc., * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * @author Gilda Garreton * @version 0.1 */ public class J3DKeyBehavior extends Behavior { protected static final double FAST_SPEED = 10.0; protected static final double NORMAL_SPEED = 1.0; protected TransformGroup tGroup; /* Contains main scene*/ protected Transform3D transform; protected WakeupCondition keyCriterion; private double delta = 5; private double rotateAmount = Math.PI / 10.0; private double speed = NORMAL_SPEED; private int forwardKey = KeyEvent.VK_UP; private int backKey = KeyEvent.VK_DOWN; private int leftKey = KeyEvent.VK_LEFT; private int rightKey = KeyEvent.VK_RIGHT; public J3DKeyBehavior(TransformGroup tg) { super(); tGroup = tg; transform = new Transform3D(); } public void initialize() { WakeupCriterion[] keyEvents = new WakeupCriterion[2]; keyEvents[0] = new WakeupOnAWTEvent(KeyEvent.KEY_PRESSED); keyEvents[1] = new WakeupOnAWTEvent(KeyEvent.KEY_RELEASED); keyCriterion = new WakeupOr(keyEvents); wakeupOn(keyCriterion); } public void processStimulus(Enumeration criteria) { WakeupCriterion wakeup; AWTEvent[] event; while(criteria.hasMoreElements( )) { wakeup = (WakeupCriterion) criteria.nextElement( ); if( !(wakeup instanceof WakeupOnAWTEvent) ) continue; event = ((WakeupOnAWTEvent)wakeup).getAWTEvent( ); for( int i = 0; i < event.length; i++ ) { - if( event[i].getID( ) == KeyEvent.KEY_PRESSED ) + if( event[i].getID( ) == KeyEvent.KEY_PRESSED || + event[i].getID( ) == KeyEvent.KEY_RELEASED ) processKeyEvent((KeyEvent)event[i]); } } wakeupOn( keyCriterion ); } protected void processKeyEvent(KeyEvent event) { int keycode = event.getKeyCode(); if(event.isShiftDown()) speed = FAST_SPEED; else speed = NORMAL_SPEED; if( event.isAltDown()) altMove(keycode); else if(event.isControlDown()) controlMove(keycode ); else standardMove(keycode); } //moves forward backward or rotates left right private void standardMove(int keycode) { if(keycode == forwardKey) moveAlongAxis(Z, 1); else if(keycode == backKey) moveAlongAxis(Z, -1); else if(keycode == leftKey) rotateAlongAxis(Y, 1); else if(keycode == rightKey) rotateAlongAxis(Y, -1); } //moves left right, rotate up down protected void altMove(int keycode) { if(keycode == forwardKey) rotateAlongAxis(X, 1); else if(keycode == backKey) rotateAlongAxis(X, -1); else if(keycode == leftKey) moveAlongAxis(X, -1); else if(keycode == rightKey) moveAlongAxis(X, 1); } //move up down, rot left right protected void controlMove(int keycode) { if(keycode == forwardKey) moveAlongAxis(Y, 1); else if(keycode == backKey) moveAlongAxis(Y, -1); else if(keycode == leftKey) rotateAlongAxis(Z, 1); else if(keycode == rightKey) rotateAlongAxis(Z, -1); } private static double[] values = new double[3]; private static Vector3d move = new Vector3d(); /** * Method to shift along axis in direction provided * @param axis * @param dir */ public void moveAlongAxis(int axis, int dir) { Arrays.fill(values, 0); values[axis] = dir * getMovementRate(); move.set(values); // If move gets a collision, then move back if (!doMove(move, false)) { values[axis] = -dir * getMovementRate(); move.set(values); doMove(move, true); } } /** * Method to rotate along given axis and direction provided * @param axis * @param dir */ protected void rotateAlongAxis(int axis, int dir) { double radian = rotateAmount * speed; // in case of collision, move the opposite direction if (!rotate(axis, dir * radian, false)) rotate(axis, -dir * radian, true); } protected boolean updateTransform(boolean force) { tGroup.setTransform(transform); return true; } private static final int X = 0; private static final int Y = 1; private static final int Z = 2; /** * Method to set the original rotation * @param rotVals */ public void setHomeRotation(double[] rotVals) { for (int i = 0; i < rotVals.length; i++) rotate(i, rotVals[i], true); } /** * Method that rotates along given axis * @param axis * @param radians * @return True if there was no collision */ protected boolean rotate(int axis, double radians, boolean force) { tGroup.getTransform(transform); Transform3D toMove = new Transform3D(); switch(axis) { case X: toMove.rotX(radians); break; case Y: toMove.rotY(radians); break; case Z: toMove.rotZ(radians); break; } transform.mul(toMove); // Need to move in opposite direction to avoid collision boolean noCollision = updateTransform(force); return (noCollision); } void zoomInOut(boolean out) { double z_factor = 0.7;//Math.abs(0.7); //double factor = (out) ? (0.5/z_factor) : (2*z_factor); double factor = (out) ? (1/z_factor) : (z_factor); // Remember old matrix tGroup.getTransform(transform); Matrix4d mat = new Matrix4d(); transform.get(mat); double dy = transform.getScale() * factor; transform.setScale(dy); tGroup.setTransform(transform); } private static Transform3D toMove = new Transform3D(); private boolean doMove(Vector3d theMove, boolean force) { tGroup.getTransform(transform); toMove.setIdentity(); toMove.setTranslation(theMove); transform.mul(toMove); return updateTransform(force); } protected double getMovementRate() { return delta * speed; } }
true
true
public void processStimulus(Enumeration criteria) { WakeupCriterion wakeup; AWTEvent[] event; while(criteria.hasMoreElements( )) { wakeup = (WakeupCriterion) criteria.nextElement( ); if( !(wakeup instanceof WakeupOnAWTEvent) ) continue; event = ((WakeupOnAWTEvent)wakeup).getAWTEvent( ); for( int i = 0; i < event.length; i++ ) { if( event[i].getID( ) == KeyEvent.KEY_PRESSED ) processKeyEvent((KeyEvent)event[i]); } } wakeupOn( keyCriterion ); }
public void processStimulus(Enumeration criteria) { WakeupCriterion wakeup; AWTEvent[] event; while(criteria.hasMoreElements( )) { wakeup = (WakeupCriterion) criteria.nextElement( ); if( !(wakeup instanceof WakeupOnAWTEvent) ) continue; event = ((WakeupOnAWTEvent)wakeup).getAWTEvent( ); for( int i = 0; i < event.length; i++ ) { if( event[i].getID( ) == KeyEvent.KEY_PRESSED || event[i].getID( ) == KeyEvent.KEY_RELEASED ) processKeyEvent((KeyEvent)event[i]); } } wakeupOn( keyCriterion ); }
diff --git a/src/test/novelang/benchmark/Nhovestone.java b/src/test/novelang/benchmark/Nhovestone.java index 9ddb9b3d..9cab85cd 100644 --- a/src/test/novelang/benchmark/Nhovestone.java +++ b/src/test/novelang/benchmark/Nhovestone.java @@ -1,219 +1,219 @@ /* * Copyright (C) 2010 Laurent Caillette * * 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 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 novelang.benchmark; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.io.Writer; import java.net.URISyntaxException; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Random; import java.util.regex.Pattern; import com.google.common.collect.ImmutableList; import javax.imageio.ImageIO; import novelang.Version; import novelang.VersionFormatException; import novelang.benchmark.report.Grapher; import novelang.benchmark.scenario.MeasurementBundle; import novelang.benchmark.scenario.Scenario; import novelang.benchmark.scenario.ScenarioLibrary; import novelang.benchmark.scenario.TimeMeasurement; import novelang.benchmark.scenario.TimeMeasurer; import novelang.common.FileTools; import novelang.system.DefaultCharset; import novelang.system.EnvironmentTools; import novelang.system.Husk; import novelang.system.Log; import novelang.system.LogFactory; import novelang.system.StartupTools; import org.apache.commons.io.output.FileWriterWithEncoding; import static novelang.benchmark.KnownVersions.VERSION_0_35_0; import static novelang.benchmark.KnownVersions.VERSION_0_38_1; import static novelang.benchmark.KnownVersions.VERSION_0_41_0; /** * Main class generating the Nhovestone report. * * @author Laurent Caillette */ public class Nhovestone { private static final Log LOG = LogFactory.getLog( Nhovestone.class ) ; public static void main( final String[] args ) throws IOException, URISyntaxException, ProcessDriver.ProcessCreationFailedException, VersionFormatException, InterruptedException { EnvironmentTools.logSystemProperties() ; final File scenariiDirectory ; final File versionsDirectory ; final Iterable< Version > versions ; if( args.length == 3 ) { scenariiDirectory = FileTools.createFreshDirectory( args[ 0 ] ) ; versionsDirectory = new File( args[ 1 ] ) ; versions = parseVersions( args[ 2 ] ) ; } else { if( args.length != 0 ) { throw new IllegalArgumentException( "Usage: " + Nhovestone.class.getSimpleName() + " [ < scenarii-dir > < distrib-dir > < comma-separated-versions > ]" ) ; } scenariiDirectory = FileTools.createFreshDirectory( "_nhovestone" ) ; versionsDirectory = new File( "distrib" ) ; versions = Arrays.asList( VERSION_0_41_0, VERSION_0_38_1, VERSION_0_35_0 ) ; } final ScenarioLibrary.ConfigurationForTimeMeasurement baseConfiguration = Husk.create( ScenarioLibrary.ConfigurationForTimeMeasurement.class ) - .withWarmupIterationCount( 1 ) - .withMaximumIterations( 2 ) + .withWarmupIterationCount( 1000 ) + .withMaximumIterations( 10000 ) .withScenariiDirectory( scenariiDirectory ) .withInstallationsDirectory( versionsDirectory ) .withVersions( versions ) .withFirstTcpPort( 9900 ) .withJvmHeapSizeMegabytes( 32 ) .withMeasurer( new TimeMeasurer() ) ; runScenario( baseConfiguration .withScenarioName( "Single ever-growing Novella" ) .withUpsizerFactory( ScenarioLibrary.createNovellaLengthUpsizerFactory( new Random( 0L ) ) ) , false ) ; runScenario( baseConfiguration .withScenarioName( "Increasing Novella count" ) .withUpsizerFactory( ScenarioLibrary.createNovellaCountUpsizerFactory( new Random( 0L ) ) ) , true ) ; writeNhovestoneParameters( new File( scenariiDirectory, "report-parameters.nlp" ), baseConfiguration ) ; System.exit( 0 ) ; } private static final Pattern COMMASEPARATEDVERSIONSSPLIT_PATTERN = Pattern.compile( "," ); private static Iterable< Version > parseVersions( final String commaSeparatedVersions ) throws VersionFormatException { final String[] versionsAsStrings = COMMASEPARATEDVERSIONSSPLIT_PATTERN.split( commaSeparatedVersions ) ; final ImmutableList.Builder< Version > versionsBuilder = new ImmutableList.Builder< Version >() ; for( final String versionsAsString : versionsAsStrings ) { versionsBuilder.add( Version.parse( versionsAsString ) ) ; } return versionsBuilder.build() ; } private static void writeNhovestoneParameters( final File parametersFile, final Scenario.Configuration< ?, ?, ? > configuration ) throws IOException { final Writer writer = new FileWriterWithEncoding( parametersFile, DefaultCharset.SOURCE ) ; final PrintWriter printWriter = new PrintWriter( writer ) ; try { printWriter.println( "== VERSIONS" ) ; printWriter.println( "" ) ; for( final Version version : configuration.getVersions() ) { printWriter.println( "- `" + version.getName() + "`" ) ; } printWriter.println( "" ) ; printWriter.println( "== NHOVESTONEPARAMETERS" ) ; printWriter.println( "" ) ; printRow( printWriter, "Warmup iterations", configuration.getWarmupIterationCount() ) ; printRow( printWriter, "Maximum iterations", configuration.getMaximumIterations() ) ; printRow( printWriter, "JVM heap size (MB)", configuration.getJvmHeapSizeMegabytes() ) ; printWriter.println( "" ) ; printWriter.println( "== JVMCHARACTERISTICS" ) ; printWriter.println( "" ) ; printRow( printWriter, "java.version" ) ; printRow( printWriter, "java.vm.name" ) ; printRow( printWriter, "os.arch" ) ; printRow( printWriter, "os.name" ) ; printRow( printWriter, "os.version" ) ; printRow( printWriter, "Available processors", Runtime.getRuntime().availableProcessors() ) ; } finally { printWriter.close() ; } } private static void printRow( final PrintWriter printWriter, final String systemPropertyName ) { final String systemPropertyValue = System.getProperty( systemPropertyName ) ; if( systemPropertyValue != null ) { printRow( printWriter, systemPropertyName, systemPropertyValue ) ; } } private static void printRow( final PrintWriter printWriter, final String cell1, final int cell2 ) { printRow( printWriter, cell1, "" + cell2 ) ; } private static void printRow( final PrintWriter printWriter, final String cell1, final String cell2 ) { printWriter.println( "| `" + cell1 + "` | `" + cell2 + "` | " ) ; } private static void runScenario( final ScenarioLibrary.ConfigurationForTimeMeasurement configuration, final boolean showUpsizingCount ) throws IOException, ProcessDriver.ProcessCreationFailedException, InterruptedException { final Scenario< Long, TimeMeasurement > scenario = new Scenario< Long, TimeMeasurement >( configuration ) ; scenario.run() ; final Map< Version, MeasurementBundle< TimeMeasurement > > measurements = scenario.getMeasurements() ; final List< Long > upsizings = scenario.getUpsizings() ; final BufferedImage image = Grapher.create( upsizings, measurements, showUpsizingCount ) ; final File imageDestinationFile = new File( configuration.getScenariiDirectory(), FileTools.sanitizeFileName( configuration.getScenarioName() ) + ".png" ) ; ImageIO.write( image, "png", imageDestinationFile ) ; LOG.info( "Wrote " + imageDestinationFile.getAbsolutePath() ) ; } }
true
true
public static void main( final String[] args ) throws IOException, URISyntaxException, ProcessDriver.ProcessCreationFailedException, VersionFormatException, InterruptedException { EnvironmentTools.logSystemProperties() ; final File scenariiDirectory ; final File versionsDirectory ; final Iterable< Version > versions ; if( args.length == 3 ) { scenariiDirectory = FileTools.createFreshDirectory( args[ 0 ] ) ; versionsDirectory = new File( args[ 1 ] ) ; versions = parseVersions( args[ 2 ] ) ; } else { if( args.length != 0 ) { throw new IllegalArgumentException( "Usage: " + Nhovestone.class.getSimpleName() + " [ < scenarii-dir > < distrib-dir > < comma-separated-versions > ]" ) ; } scenariiDirectory = FileTools.createFreshDirectory( "_nhovestone" ) ; versionsDirectory = new File( "distrib" ) ; versions = Arrays.asList( VERSION_0_41_0, VERSION_0_38_1, VERSION_0_35_0 ) ; } final ScenarioLibrary.ConfigurationForTimeMeasurement baseConfiguration = Husk.create( ScenarioLibrary.ConfigurationForTimeMeasurement.class ) .withWarmupIterationCount( 1 ) .withMaximumIterations( 2 ) .withScenariiDirectory( scenariiDirectory ) .withInstallationsDirectory( versionsDirectory ) .withVersions( versions ) .withFirstTcpPort( 9900 ) .withJvmHeapSizeMegabytes( 32 ) .withMeasurer( new TimeMeasurer() ) ; runScenario( baseConfiguration .withScenarioName( "Single ever-growing Novella" ) .withUpsizerFactory( ScenarioLibrary.createNovellaLengthUpsizerFactory( new Random( 0L ) ) ) , false ) ; runScenario( baseConfiguration .withScenarioName( "Increasing Novella count" ) .withUpsizerFactory( ScenarioLibrary.createNovellaCountUpsizerFactory( new Random( 0L ) ) ) , true ) ; writeNhovestoneParameters( new File( scenariiDirectory, "report-parameters.nlp" ), baseConfiguration ) ; System.exit( 0 ) ; }
public static void main( final String[] args ) throws IOException, URISyntaxException, ProcessDriver.ProcessCreationFailedException, VersionFormatException, InterruptedException { EnvironmentTools.logSystemProperties() ; final File scenariiDirectory ; final File versionsDirectory ; final Iterable< Version > versions ; if( args.length == 3 ) { scenariiDirectory = FileTools.createFreshDirectory( args[ 0 ] ) ; versionsDirectory = new File( args[ 1 ] ) ; versions = parseVersions( args[ 2 ] ) ; } else { if( args.length != 0 ) { throw new IllegalArgumentException( "Usage: " + Nhovestone.class.getSimpleName() + " [ < scenarii-dir > < distrib-dir > < comma-separated-versions > ]" ) ; } scenariiDirectory = FileTools.createFreshDirectory( "_nhovestone" ) ; versionsDirectory = new File( "distrib" ) ; versions = Arrays.asList( VERSION_0_41_0, VERSION_0_38_1, VERSION_0_35_0 ) ; } final ScenarioLibrary.ConfigurationForTimeMeasurement baseConfiguration = Husk.create( ScenarioLibrary.ConfigurationForTimeMeasurement.class ) .withWarmupIterationCount( 1000 ) .withMaximumIterations( 10000 ) .withScenariiDirectory( scenariiDirectory ) .withInstallationsDirectory( versionsDirectory ) .withVersions( versions ) .withFirstTcpPort( 9900 ) .withJvmHeapSizeMegabytes( 32 ) .withMeasurer( new TimeMeasurer() ) ; runScenario( baseConfiguration .withScenarioName( "Single ever-growing Novella" ) .withUpsizerFactory( ScenarioLibrary.createNovellaLengthUpsizerFactory( new Random( 0L ) ) ) , false ) ; runScenario( baseConfiguration .withScenarioName( "Increasing Novella count" ) .withUpsizerFactory( ScenarioLibrary.createNovellaCountUpsizerFactory( new Random( 0L ) ) ) , true ) ; writeNhovestoneParameters( new File( scenariiDirectory, "report-parameters.nlp" ), baseConfiguration ) ; System.exit( 0 ) ; }
diff --git a/apps/animaldb/org/molgenis/animaldb/plugins/breeding/Breedingnew.java b/apps/animaldb/org/molgenis/animaldb/plugins/breeding/Breedingnew.java index 25b889870..c39d99032 100644 --- a/apps/animaldb/org/molgenis/animaldb/plugins/breeding/Breedingnew.java +++ b/apps/animaldb/org/molgenis/animaldb/plugins/breeding/Breedingnew.java @@ -1,2305 +1,2305 @@ /* Date: November 15, 2010 * Template: PluginScreenJavaTemplateGen.java.ftl * generator: org.molgenis.generators.ui.PluginScreenJavaTemplateGen 3.3.3 * * THIS FILE IS A TEMPLATE. PLEASE EDIT :-) */ package org.molgenis.animaldb.plugins.breeding; import java.io.File; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map.Entry; import java.util.Set; import org.molgenis.animaldb.commonservice.CommonService; import org.molgenis.animaldb.plugins.administration.LabelGenerator; import org.molgenis.animaldb.plugins.administration.LabelGeneratorException; import org.molgenis.framework.db.Database; import org.molgenis.framework.db.DatabaseException; import org.molgenis.framework.db.Query; import org.molgenis.framework.db.QueryRule; import org.molgenis.framework.db.QueryRule.Operator; import org.molgenis.framework.ui.PluginModel; import org.molgenis.framework.ui.ScreenController; import org.molgenis.framework.ui.ScreenMessage; import org.molgenis.framework.ui.html.DateInput; import org.molgenis.framework.ui.html.HtmlInput; import org.molgenis.framework.ui.html.SelectInput; import org.molgenis.framework.ui.html.Table; import org.molgenis.matrix.component.MatrixViewer; import org.molgenis.matrix.component.SliceablePhenoMatrix; import org.molgenis.matrix.component.general.MatrixQueryRule; import org.molgenis.matrix.component.interfaces.DatabaseMatrix; import org.molgenis.pheno.Category; import org.molgenis.pheno.Individual; import org.molgenis.pheno.Location; import org.molgenis.pheno.Measurement; import org.molgenis.pheno.ObservationElement; import org.molgenis.pheno.ObservationTarget; import org.molgenis.pheno.ObservedValue; import org.molgenis.pheno.Panel; import org.molgenis.protocol.ProtocolApplication; import org.molgenis.util.Entity; import org.molgenis.util.Tuple; public class Breedingnew extends PluginModel<Entity> { private static final long serialVersionUID = 203412348106990472L; private CommonService ct = CommonService.getInstance(); //private SimpleDateFormat dateOnlyFormat = new SimpleDateFormat("MMMM d, yyyy", Locale.US); private SimpleDateFormat dbFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.US); private String startdate = null; private List<ObservationTarget> lineList; private String line = null; private String litterRemarks = null; //private String pgStatus = null; MatrixViewer motherMatrixViewer = null; MatrixViewer fatherMatrixViewer = null; MatrixViewer pgMatrixViewer = null; MatrixViewer litterMatrixViewer = null; private static String MOTHERMATRIX = "mothermatrix"; private static String FATHERMATRIX = "fathermatrix"; private static String PGMATRIX = "pgmatrix"; private static String LITTERMATRIX = "littermatrix"; private String action = "init"; private String userName = null; private String motherMatrixViewerString; private String fatherMatrixViewerString; private String pgMatrixViewerString; private String litterMatrixViewerString; private String entity = "Parentgroups"; private String birthdate = null; private SimpleDateFormat newDateOnlyFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.US); private String remarks = null; private String selectedParentgroup = null; private int litterSize; private boolean litterSizeApproximate; private String locName = null; private String respres = null; private int weanSizeFemale; private int weanSizeMale; private int weanSizeUnknown; private String weandate = null; private String nameBase = null; private int startNumber = -1; private String litter; private String prefix = ""; private List<String> bases; private List<ObservationTarget> backgroundList; private List<ObservationTarget> sexList; private List<String> geneNameList; private List<String> geneStateList; private List<String> colorList; private List<Category> earmarkList; private List<Location> locationList; private int nrOfGenotypes = 1; private Table genotypeTable = null; private boolean wean = false; private String parentInfo = ""; private String labelDownloadLink; Integer numberOfPG = -1; List<String> pgName = new ArrayList<String>(); String sex = "not selected"; boolean stillToWeanYN = true; boolean stillToGenotypeYN = true; //HashMap<String,List<String>> hashMothers = new HashMap<String,List<String>>(); HashMap<Integer,List<String>> hashMothers = new HashMap<Integer,List<String>>(); HashMap<Integer,List<String>> hashFathers = new HashMap<Integer,List<String>>(); public Breedingnew(String name, ScreenController<?> parent) { super(name, parent); } public String getCustomHtmlHeaders() { return "<script type=\"text/javascript\" src=\"res/jquery-plugins/datatables/js/jquery.dataTables.js\"></script>\n" + "<script src=\"res/jquery-plugins/ctnotify/lib/jquery.ctNotify.js\" language=\"javascript\"></script>\n" + "<script src=\"res/scripts/custom/addingajax.js\" language=\"javascript\"></script>\n" + "<script src=\"res/scripts/custom/litters.js\" language=\"javascript\"></script>\n" + "<link rel=\"stylesheet\" style=\"text/css\" href=\"res/jquery-plugins/datatables/css/demo_table_jui.css\">\n" + "<link rel=\"stylesheet\" style=\"text/css\" href=\"res/jquery-plugins/ctnotify/lib/jquery.ctNotify.css\">"; } public String getAnimalName(Integer id) { try { return ct.getObservationTargetLabel(id); } catch (Exception e) { return id.toString(); } } public String getStartdate() { return startdate; } public void setStartdate(String startdate) { this.startdate = startdate; } public void setLine(String line) { this.line = line; } public String getLine() { return line; } public List<ObservationTarget> getLineList() { return lineList; } public void setLineList(List<ObservationTarget> lineList) { this.lineList = lineList; } public String getRemarks() { return remarks; } public void setRemarks(String remarks) { this.remarks = remarks; } public String getAction() { return action; } public void setAction(String action) { this.action = action; } public String getEntity() { return entity; } public void setEntity(String entity) { this.entity = entity; } public String getMotherMatrixViewer() { if (motherMatrixViewerString != null) { return motherMatrixViewerString; } return "Mother matrix not loaded"; } public void loadMotherMatrixViewer(Database db) { try { List<String> investigationNames = ct.getAllUserInvestigationNames(this.getLogin().getUserName()); List<String> measurementsToShow = new ArrayList<String>(); measurementsToShow.add("Sex"); measurementsToShow.add("Active"); measurementsToShow.add("Line"); measurementsToShow.add("Background"); measurementsToShow.add("GeneModification"); measurementsToShow.add("GeneState"); measurementsToShow.add("Species"); // Mother matrix viewer List<MatrixQueryRule> motherFilterRules = new ArrayList<MatrixQueryRule>(); motherFilterRules.add(new MatrixQueryRule(MatrixQueryRule.Type.rowHeader, Individual.INVESTIGATION_NAME, Operator.IN, investigationNames)); //MOTHER IS DISABLED /*motherFilterRules.add(new MatrixQueryRule(MatrixQueryRule.Type.colValueProperty, ct.getMeasurementId("Sex"), ObservedValue.RELATION_NAME, Operator.EQUALS, "Female"));*/ motherFilterRules.add(new MatrixQueryRule(MatrixQueryRule.Type.colValueProperty, ct.getMeasurementId("Active"), ObservedValue.VALUE, Operator.EQUALS, "Alive")); if (line != null) { motherFilterRules.add(new MatrixQueryRule(MatrixQueryRule.Type.colValueProperty, ct.getMeasurementId("Line"), ObservedValue.RELATION_NAME, Operator.EQUALS, line)); // Setting filter on the RELATION field with value = line would be more efficient, // but gives a very un-userfriendly toString value when shown in the MatrixViewer UI String speciesName = ct.getMostRecentValueAsXrefName(line, "Species"); motherFilterRules.add(new MatrixQueryRule(MatrixQueryRule.Type.colValueProperty, ct.getMeasurementId("Species"), ObservedValue.RELATION_NAME, Operator.EQUALS, speciesName)); } SliceablePhenoMatrix<Individual, Measurement> SPMM = new SliceablePhenoMatrix<Individual, Measurement>(Individual.class, Measurement.class); SPMM.setDatabase(db); motherMatrixViewer = new MatrixViewer(this, MOTHERMATRIX, SPMM, true, 2, false, false, motherFilterRules, new MatrixQueryRule(MatrixQueryRule.Type.colHeader, Measurement.NAME, Operator.IN, measurementsToShow)); } catch (Exception e) { String message = "Something went wrong while loading mother matrix viewer"; if (e.getMessage() != null) { message += (": " + e.getMessage()); } this.getMessages().add(new ScreenMessage(message, false)); e.printStackTrace(); } } public String getFatherMatrixViewer() { if (fatherMatrixViewerString != null) { return fatherMatrixViewerString; } return "Father matrix not loaded"; } public void loadFatherMatrixViewer(Database db) { try { List<String> investigationNames = ct.getAllUserInvestigationNames(this.getLogin().getUserName()); List<String> measurementsToShow = new ArrayList<String>(); measurementsToShow.add("Sex"); measurementsToShow.add("Active"); measurementsToShow.add("Line"); measurementsToShow.add("Background"); measurementsToShow.add("GeneModification"); measurementsToShow.add("GeneState"); measurementsToShow.add("Species"); // Father matrix viewer List<MatrixQueryRule> fatherFilterRules = new ArrayList<MatrixQueryRule>(); fatherFilterRules.add(new MatrixQueryRule(MatrixQueryRule.Type.rowHeader, Individual.INVESTIGATION_NAME, Operator.IN, investigationNames)); fatherFilterRules.add(new MatrixQueryRule(MatrixQueryRule.Type.colValueProperty, ct.getMeasurementId("Sex"), ObservedValue.RELATION_NAME, Operator.EQUALS, "Male")); fatherFilterRules.add(new MatrixQueryRule(MatrixQueryRule.Type.colValueProperty, ct.getMeasurementId("Active"), ObservedValue.VALUE, Operator.EQUALS, "Alive")); if (line != null) { fatherFilterRules.add(new MatrixQueryRule(MatrixQueryRule.Type.colValueProperty, ct.getMeasurementId("Line"), ObservedValue.RELATION_NAME, Operator.EQUALS, line)); // Setting filter on the RELATION field with value = line would be more efficient, // but gives a very un-userfriendly toString value when shown in the MatrixViewer UI String speciesName = ct.getMostRecentValueAsXrefName(line, "Species"); fatherFilterRules.add(new MatrixQueryRule(MatrixQueryRule.Type.colValueProperty, ct.getMeasurementId("Species"), ObservedValue.RELATION_NAME, Operator.EQUALS, speciesName)); } SliceablePhenoMatrix<Individual, Measurement> SPMF = new SliceablePhenoMatrix<Individual, Measurement>(Individual.class, Measurement.class); SPMF.setDatabase(db); fatherMatrixViewer = new MatrixViewer(this, FATHERMATRIX, SPMF, true, 2, false, false, fatherFilterRules, new MatrixQueryRule(MatrixQueryRule.Type.colHeader, Measurement.NAME, Operator.IN, measurementsToShow)); } catch (Exception e) { String message = "Something went wrong while loading father matrix viewer"; if (e.getMessage() != null) { message += (": " + e.getMessage()); } this.getMessages().add(new ScreenMessage(message, false)); e.printStackTrace(); } } public String getPgMatrixViewer() { return pgMatrixViewerString; } public void loadPgMatrixViewer(Database db) { try { List<String> investigationNames = ct.getAllUserInvestigationNames(this.getLogin().getUserName()); List<String> measurementsToShow = new ArrayList<String>(); measurementsToShow.add("Active"); measurementsToShow.add("StartDate"); measurementsToShow.add("Remark"); measurementsToShow.add("Line"); measurementsToShow.add("ParentgroupMother"); measurementsToShow.add("ParentgroupFather"); List<MatrixQueryRule> filterRules = new ArrayList<MatrixQueryRule>(); filterRules.add(new MatrixQueryRule(MatrixQueryRule.Type.rowHeader, Panel.INVESTIGATION_NAME, Operator.IN, investigationNames)); filterRules.add(new MatrixQueryRule(MatrixQueryRule.Type.colValueProperty, ct.getMeasurementId("TypeOfGroup"), ObservedValue.VALUE, Operator.EQUALS, "Parentgroup")); filterRules.add(new MatrixQueryRule(MatrixQueryRule.Type.colValueProperty, ct.getMeasurementId("Active"), ObservedValue.VALUE, Operator.EQUALS, "Active")); filterRules.add(new MatrixQueryRule(MatrixQueryRule.Type.colValueProperty, ct.getMeasurementId("Line"), ObservedValue.RELATION_NAME, Operator.EQUALS, this.line)); pgMatrixViewer = new MatrixViewer(this, PGMATRIX, new SliceablePhenoMatrix<Panel, Measurement>(Panel.class, Measurement.class), true, 1, false, false, filterRules, new MatrixQueryRule(MatrixQueryRule.Type.colHeader, Measurement.NAME, Operator.IN, measurementsToShow)); } catch (Exception e) { String message = "Something went wrong while loading parentgroup matrix"; if (e.getMessage() != null) { message += (": " + e.getMessage()); } this.getMessages().add(new ScreenMessage(message, false)); e.printStackTrace(); } } public String getLitterMatrixViewer() { return litterMatrixViewerString; } public void loadLitterMatrixViewer(Database db) { try { List<String> investigationNames = ct.getAllUserInvestigationNames(this.getLogin().getUserName()); List<String> measurementsToShow = new ArrayList<String>(); measurementsToShow.add("Active"); measurementsToShow.add("Parentgroup"); measurementsToShow.add("Line"); measurementsToShow.add("DateOfBirth"); measurementsToShow.add("WeanDate"); measurementsToShow.add("Size"); measurementsToShow.add("WeanSize"); measurementsToShow.add("GenotypeDate"); measurementsToShow.add("Remark"); List<MatrixQueryRule> filterRules = new ArrayList<MatrixQueryRule>(); filterRules.add(new MatrixQueryRule(MatrixQueryRule.Type.rowHeader, Panel.INVESTIGATION_NAME, Operator.IN, investigationNames)); filterRules.add(new MatrixQueryRule(MatrixQueryRule.Type.colValueProperty, ct.getMeasurementId("TypeOfGroup"), ObservedValue.VALUE, Operator.EQUALS, "Litter")); filterRules.add(new MatrixQueryRule(MatrixQueryRule.Type.colValueProperty, ct.getMeasurementId("Active"), ObservedValue.VALUE, Operator.EQUALS, "Active")); filterRules.add(new MatrixQueryRule(MatrixQueryRule.Type.colValueProperty, ct.getMeasurementId("Line"), ObservedValue.RELATION_NAME, Operator.EQUALS, this.line)); litterMatrixViewer = new MatrixViewer(this, LITTERMATRIX, new SliceablePhenoMatrix<Panel, Measurement>(Panel.class, Measurement.class), true, 1, false, false, filterRules, new MatrixQueryRule(MatrixQueryRule.Type.colHeader, Measurement.NAME, Operator.IN, measurementsToShow)); } catch (Exception e) { String message = "Something went wrong while loading litter matrix"; if (e.getMessage() != null) { message += (": " + e.getMessage()); } this.getMessages().add(new ScreenMessage(message, false)); e.printStackTrace(); } } @Override public String getViewName() { return "org_molgenis_animaldb_plugins_breeding_Breedingnew"; } @Override public String getViewTemplate() { return "org/molgenis/animaldb/plugins/breeding/Breedingnew.ftl"; } private void AddParents(Database db, List<String> parentNameList, String protocolName, String featureName, String parentgroupName, Date eventDate) throws DatabaseException, ParseException, IOException { String invName = ct.getOwnUserInvestigationNames(this.getLogin().getUserName()).get(0); // Init lists that we can later add to the DB at once List<ObservedValue> valuesToAddList = new ArrayList<ObservedValue>(); for (String parentName : parentNameList) { if(parentName!=null){ // Find the 'SetParentgroupMother'/'SetParentgroupFather' event type // TODO: SetParentgroupMother/SetParentgroupFather are now plain event types with only the ParentgroupMother/ParentgroupFather feature // and no longer the Certain feature. Solve this! // Make the event ProtocolApplication app = ct.createProtocolApplication(invName, protocolName); db.add(app); // Make 'ParentgroupMother'/'ParentgroupFather' feature-value pair and link to event valuesToAddList.add(ct.createObservedValue(invName, app.getName(), eventDate, null, featureName, parentgroupName, null, parentName)); // Make 'Certain' feature-value pair and link to event String valueString; if (parentNameList.size() == 1) { valueString = "1"; // if there's only one parent of this gender, it's certain } else { valueString = "0"; // ... otherwise, not } valuesToAddList.add(ct.createObservedValue(invName, app.getName(), eventDate, null, "Certain", parentName, valueString, null)); } else{ } } // Add everything to DB db.add(valuesToAddList); } @Override public void handleRequest(Database db, Tuple request) { ct.setDatabase(db); action = request.getString("__action"); try { if (motherMatrixViewer != null && action.startsWith(motherMatrixViewer.getName())) { motherMatrixViewer.setDatabase(db); motherMatrixViewer.handleRequest(db, request); motherMatrixViewerString = motherMatrixViewer.render(); this.action = "selectParents"; // return to mother selection screen return; } if (fatherMatrixViewer != null && action.startsWith(fatherMatrixViewer.getName())) { fatherMatrixViewer.setDatabase(db); fatherMatrixViewer.handleRequest(db, request); fatherMatrixViewerString = fatherMatrixViewer.render(); this.action = "addParentgroupScreen3"; // return to father selection screen //this.action = "selectParents"; return; } if (pgMatrixViewer != null && action.startsWith(pgMatrixViewer.getName())) { pgMatrixViewer.setDatabase(db); pgMatrixViewer.handleRequest(db, request); pgMatrixViewerString = pgMatrixViewer.render(); this.action = "init"; // return to start screen this.entity = "Parentgroups"; return; } if (litterMatrixViewer != null && action.startsWith(litterMatrixViewer.getName())) { litterMatrixViewer.setDatabase(db); litterMatrixViewer.handleRequest(db, request); litterMatrixViewerString = litterMatrixViewer.render(); this.action = "init"; // return to start screen this.entity = "Litters"; return; } if (action.equals("init")) { // do nothing here } if (action.equals("selectParents")) { hashFathers.clear(); hashMothers.clear(); List<String> lis = new ArrayList<String>(); lis.add(""); numberOfPG = request.getInt("numberPG"); if(numberOfPG == null) { numberOfPG = -1; } for(int i = 0; i < numberOfPG; i++){ hashMothers.put(i, lis); hashFathers.put(i, lis); pgName.add(i+""); } } if(pgName.size()!=0){ for(int i= 0; i < pgName.size(); i++){ if(action.equals("selectParentsM"+(i))){ List<String> selectedFatherNameList = new ArrayList<String>(); @SuppressWarnings("unchecked") List<ObservationElement> rows = (List<ObservationElement>) motherMatrixViewer.getSelection(db); int rowCnt = 0; sex = "not selected"; for (ObservationElement row : rows) { if (request.getBool(MOTHERMATRIX + "_selected_" + rowCnt) != null) { String fatherName = row.getName(); sex = ct.getMostRecentValueAsXrefName(fatherName, "Sex"); if(sex.equals("Male")){ if (!selectedFatherNameList.contains(fatherName)) { selectedFatherNameList.add(fatherName); } }else{ - this.setMessages(new ScreenMessage("Not a Female", false)); + this.setMessages(new ScreenMessage("Not a Male", false)); } } rowCnt++; } hashFathers.put(i, selectedFatherNameList); } if(action.equals("selectParentsF"+(i))){ List<String> selectedMotherNameList = new ArrayList<String>(); @SuppressWarnings("unchecked") List<ObservationElement> rows = (List<ObservationElement>) motherMatrixViewer.getSelection(db); int rowCnt = 0; sex = "not selected"; for (ObservationElement row : rows) { if (request.getBool(MOTHERMATRIX + "_selected_" + rowCnt) != null) { String motherName = row.getName(); sex = ct.getMostRecentValueAsXrefName(motherName, "Sex"); if(sex.equals("Female")){ if (!selectedMotherNameList.contains(motherName)) { selectedMotherNameList.add(motherName); } } else{ this.setMessages(new ScreenMessage("Not a Female", false)); } } rowCnt++; } hashMothers.put(i, selectedMotherNameList); } } } try{ if(action.equals("init")){ hashFathers.clear(); hashMothers.clear(); numberOfPG = null; } if(action.equals("JensonButton")){ boolean papa = false; boolean mama = false; List<String> pgNames = new ArrayList<String>(); for(Entry<Integer,List<String>> entry : hashFathers.entrySet()){ for(String s : entry.getValue()){ if(s.isEmpty()){ papa = true; } } } for(Entry<Integer,List<String>> entry : hashMothers.entrySet()){ for(String s : entry.getValue()){ if(s.isEmpty()){ mama = true; } } } if(papa == false || mama == false){ for(Entry <Integer,List<String>> entry: hashFathers.entrySet()){ String x = ""; String y = ""; if(request.getDate("startdate"+entry.getKey())!=null){ x = request.getString("startdate"+entry.getKey()); } if(request.getString("remarks"+entry.getKey())!=null){ y = request.getString("remarks"+entry.getKey()); } pgNames.add(AddParentgroup2(db, request,entry.getValue(),hashMothers.get(entry.getKey()),x,y)); // Reset matrix and add filter on name of newly added PG: loadPgMatrixViewer(db); pgMatrixViewer.setDatabase(db); //pgMatrixViewer.getMatrix().getRules().add(new MatrixQueryRule(MatrixQueryRule.Type.rowHeader, //Individual.NAME, Operator.EQUALS, pgNames)); pgMatrixViewer.reloadMatrix(db, null); pgMatrixViewerString = pgMatrixViewer.render(); // Reset other fields this.action = "init"; this.startdate = newDateOnlyFormat.format(new Date()); this.remarks = null; motherMatrixViewer = null; this.setSuccess("Parentgroup " + pgNames + " successfully added; adding filter to matrix: name = " + pgNames); } hashFathers.clear(); hashMothers.clear(); numberOfPG = null; } else{ this.setMessages(new ScreenMessage("Not all fathers or mothers are filled in", false)); action = "selectParents"; } } } catch(Exception e){ //this.setMessages(new ScreenMessage("Not all fathers or mothers are filled in", false)); } if (action.equals("createParentgroup")) { numberOfPG = -1; loadMotherMatrixViewer(db); motherMatrixViewer.setDatabase(db); motherMatrixViewerString = motherMatrixViewer.render(); } if (action.equals("changeLine")) { this.line = request.getString("line"); this.setSuccess("Breeding line changed to " + this.line); // Reset matrices and return to main screen loadPgMatrixViewer(db); pgMatrixViewer.setDatabase(db); pgMatrixViewerString = pgMatrixViewer.render(); loadLitterMatrixViewer(db); litterMatrixViewer.setDatabase(db); litterMatrixViewerString = litterMatrixViewer.render(); this.action = "init"; } if (action.equals("switchParentgroups")) { this.entity = "Parentgroups"; this.action = "init"; } if (action.equals("switchLitters")) { this.entity = "Litters"; this.action = "init"; } if (action.equals("deActivate")) { List<?> rows = pgMatrixViewer.getSelection(db); String pgName; try { int row = request.getInt(PGMATRIX + "_selected"); pgName = ((ObservationElement) rows.get(row)).getName(); } catch (Exception e) { this.action = "init"; throw new Exception("No parentgroup selected"); } ObservedValue activeVal = db.query(ObservedValue.class). eq(ObservedValue.TARGET_NAME, pgName). eq(ObservedValue.FEATURE_NAME, "Active"). find().get(0); if (activeVal.getValue().equals("Active")) { activeVal.setValue("Inactive"); } else { activeVal.setValue("Active"); } db.update(activeVal); // Reset matrix and return to main screen loadPgMatrixViewer(db); pgMatrixViewer.setDatabase(db); pgMatrixViewerString = pgMatrixViewer.render(); this.action = "init"; this.entity = "Parentgroups"; } if (action.equals("deActivateLitter")) { List<?> rows = litterMatrixViewer.getSelection(db); String litterName; try { int row = request.getInt(LITTERMATRIX + "_selected"); litterName = ((ObservationElement) rows.get(row)).getName(); } catch (Exception e) { this.action = "init"; throw new Exception("No litter selected"); } ObservedValue activeVal = db.query(ObservedValue.class). eq(ObservedValue.TARGET_NAME, litterName). eq(ObservedValue.FEATURE_NAME, "Active"). find().get(0); if (activeVal.getValue().equals("Active")) { activeVal.setValue("Inactive"); } else { activeVal.setValue("Active"); } db.update(activeVal); // Reset matrix and return to main screen loadLitterMatrixViewer(db); litterMatrixViewer.setDatabase(db); litterMatrixViewerString = litterMatrixViewer.render(); this.action = "init"; this.entity = "Litters"; } if (action.equals("createLitter")) { this.entity = "Litters"; // switch to litter view // Get selected parentgroup from PARENTGROUP matrix List<?> rows = pgMatrixViewer.getSelection(db); try { int row = request.getInt(PGMATRIX + "_selected"); this.selectedParentgroup = ((ObservationElement) rows.get(row)).getName(); } catch (Exception e) { this.action = "init"; throw new Exception("No parentgroup selected"); } } if (action.equals("addLitter")) { String newLitterName = ApplyAddLitter(db, request); // Reload litter matrix and set filter on name of newly added litter loadLitterMatrixViewer(db); litterMatrixViewer.setDatabase(db); litterMatrixViewer.getMatrix().getRules().add(new MatrixQueryRule(MatrixQueryRule.Type.rowHeader, Individual.NAME, Operator.EQUALS, newLitterName)); litterMatrixViewer.reloadMatrix(db, null); litterMatrixViewerString = litterMatrixViewer.render(); // Reset other fields this.birthdate = null; this.litterSize = 0; this.litterRemarks = null; // Return to start screen for litters this.action = "init"; this.entity = "Litters"; this.setSuccess("Litter " + newLitterName + " successfully added; adding filter to matrix: name = " + newLitterName); } if (action.equals("WeanLitter")) { stillToWeanYN = true; // Get selected litter List<?> rows = litterMatrixViewer.getSelection(db); try { int row = request.getInt(LITTERMATRIX + "_selected"); this.litter = ((ObservationElement) rows.get(row)).getName(); } catch (Exception e) { this.action = "init"; this.entity = "Litters"; throw new Exception("No litter selected"); } if(isWeaned(db)){ stillToWeanYN = false; this.setMessages(new ScreenMessage("Already weaned", false)); action="addLitter"; } else{ weanLitter(db); } } if (action.equals("GenotypeLitter")) { // Prepare parent info stillToGenotypeYN = true; List<?> rows = litterMatrixViewer.getSelection(db); try { int row = request.getInt(LITTERMATRIX + "_selected"); this.litter = ((ObservationElement) rows.get(row)).getName(); } catch (Exception e) { this.action = "init"; this.entity = "Litters"; throw new Exception("No litter selected"); } if(!isWeaned(db)){ this.setMessages(new ScreenMessage("The litter is not weaned yet!", false)); action="addLitter"; } else{ if(isGenotyped(db)){ stillToGenotypeYN = false; this.setMessages(new ScreenMessage("Already genotyped", false)); action="addLitter"; } else{ String parentgroupName = ct.getMostRecentValueAsXrefName(this.litter, "Parentgroup"); parentInfo = ""; parentInfo += ("Parentgroup: " + parentgroupName + "<br />"); parentInfo += ("Line: " + getLineInfo(parentgroupName) + "<br />"); String motherName = findParentForParentgroup(parentgroupName, "Mother", db); parentInfo += ("Mother: " + getGenoInfo(motherName, db) + "<br />"); String fatherName = findParentForParentgroup(parentgroupName, "Father", db); parentInfo += ("Father: " + getGenoInfo(fatherName, db) + "<br />"); genotypeLitter(db); } } } if (action.equals("applyWean")) { int weanSize = Wean(db, request); // Update custom label map now new animals have been added ct.makeObservationTargetNameMap(this.getLogin().getUserName(), true); // Reset all values this.wean = false; this.weandate = null; this.weanSizeFemale = 0; this.weanSizeMale = 0; this.weanSizeUnknown = 0; this.remarks = null; this.respres = null; this.selectedParentgroup = null; this.locName = null; // Reload litter matrix and set filter on name of newly weaned litter loadLitterMatrixViewer(db); litterMatrixViewer.setDatabase(db); litterMatrixViewer.getMatrix().getRules().add(new MatrixQueryRule(MatrixQueryRule.Type.rowHeader, Individual.NAME, Operator.EQUALS, this.litter)); litterMatrixViewer.reloadMatrix(db, null); litterMatrixViewerString = litterMatrixViewer.render(); this.action = "init"; this.entity = "Litters"; this.setSuccess("All " + weanSize + " animals successfully weaned; adding filter to matrix: name = " + this.litter); } if (action.equals("applyGenotype")) { int animalCount = Genotype(db, request); // Reload litter matrix and set filter on name of newly weaned litter loadLitterMatrixViewer(db); litterMatrixViewer.setDatabase(db); litterMatrixViewer.getMatrix().getRules().add(new MatrixQueryRule(MatrixQueryRule.Type.rowHeader, Individual.NAME, Operator.EQUALS, this.litter)); litterMatrixViewer.reloadMatrix(db, null); litterMatrixViewerString = litterMatrixViewer.render(); // Reset other fields this.action = "init"; this.entity = "Litters"; this.setSuccess("All " + animalCount + " animals successfully genotyped; adding filter to matrix: name = " + this.litter); } if (action.equals("makeLabels")) { // Get selected litter List<?> rows = litterMatrixViewer.getSelection(db); try { int row = request.getInt(LITTERMATRIX + "_selected"); this.litter = ((ObservationElement) rows.get(row)).getName(); } catch (Exception e) { this.action = "init"; this.entity = "Litters"; throw new Exception("No litter selected"); } if (ct.getMostRecentValueAsString(this.litter, "WeanDate") == null) { this.action = "init"; this.entity = "Litters"; throw new Exception("Cannot make labels for an unweaned litter"); } else if (ct.getMostRecentValueAsString(this.litter, "GenotypeDate") == null) { makeTempCageLabels(db); } else { makeDefCageLabels(db); } } if (action.equals("AddGenoCol")) { storeGenotypeTable(db, request); AddGenoCol(db, request); this.action = "GenotypeLitter"; this.setSuccess("Gene modification + state pair successfully added"); } if (action.equals("RemGenoCol")) { if (nrOfGenotypes > 1) { int currCol = 5 + ((nrOfGenotypes - 1) * 2); genotypeTable.removeColumn(currCol); // NB: nr. of cols is now 1 lower! genotypeTable.removeColumn(currCol); nrOfGenotypes--; this.setSuccess("Gene modification + state pair successfully removed"); } else { this.setError("Cannot remove - at least one Gene modification + state pair has to remain"); } storeGenotypeTable(db, request); this.action = "GenotypeLitter"; } } catch (Exception e) { String message = "Something went wrong"; if (e.getMessage() != null) { message += ": " + e.getMessage(); } this.setError(message); e.printStackTrace(); } } /** * Prepares the genotype editable table * * @param db */ private void genotypeLitter(Database db) { nrOfGenotypes = 1; // Prepare table genotypeTable = new Table("GenoTable", ""); genotypeTable.addColumn("Birth date"); genotypeTable.addColumn("Sex"); genotypeTable.addColumn("Color"); genotypeTable.addColumn("Earmark"); genotypeTable.addColumn("Background"); genotypeTable.addColumn("Gene modification"); genotypeTable.addColumn("Gene state"); int row = 0; for (Individual animal : getAnimalsInLitter(db)) { String animalName = animal.getName(); genotypeTable.addRow(animalName); // Birth date DateInput dateInput = new DateInput("0_" + row); dateInput.setValue(getAnimalBirthDate(animalName)); genotypeTable.setCell(0, row, dateInput); // Sex SelectInput sexInput = new SelectInput("1_" + row); for (ObservationTarget sex : this.sexList) { sexInput.addOption(sex.getName(), sex.getName()); } sexInput.setValue(getAnimalSex(animalName)); sexInput.setWidth(-1); genotypeTable.setCell(1, row, sexInput); // Color SelectInput colorInput = new SelectInput("2_" + row); for (String color : this.colorList) { colorInput.addOption(color, color); } colorInput.setValue(getAnimalColor(animalName)); colorInput.setWidth(-1); genotypeTable.setCell(2, row, colorInput); // Earmark SelectInput earmarkInput = new SelectInput("3_" + row); for (Category earmark : this.earmarkList) { earmarkInput.addOption(earmark.getCode_String(), earmark.getCode_String()); } earmarkInput.setValue(getAnimalEarmark(animalName)); earmarkInput.setWidth(-1); genotypeTable.setCell(3, row, earmarkInput); // Background SelectInput backgroundInput = new SelectInput("4_" + row); for (ObservationTarget background : this.backgroundList) { backgroundInput.addOption(background.getName(), background.getName()); } backgroundInput.setValue(getAnimalBackground(animalName)); backgroundInput.setWidth(-1); genotypeTable.setCell(4, row, backgroundInput); // TODO: show columns and selectboxes for ALL set geno mods // Gene mod name (1) SelectInput geneNameInput = new SelectInput("5_" + row); for (String geneName : this.geneNameList) { geneNameInput.addOption(geneName, geneName); } geneNameInput.setValue(getAnimalGeneInfo("GeneModification", animalName, 0, db)); geneNameInput.setWidth(-1); genotypeTable.setCell(5, row, geneNameInput); // Gene state (1) SelectInput geneStateInput = new SelectInput("6_" + row); for (String geneState : this.geneStateList) { geneStateInput.addOption(geneState, geneState); } geneStateInput.setValue(getAnimalGeneInfo("GeneState", animalName, 0, db)); geneStateInput.setWidth(-1); genotypeTable.setCell(6, row, geneStateInput); row++; } } private void weanLitter(Database db) throws DatabaseException, ParseException { // Find out species of litter user wants to wean, so we can provide the right name prefix String parentgroupName = ct.getMostRecentValueAsXrefName(litter, "Parentgroup"); String motherName = findParentForParentgroup(parentgroupName, "Mother", db); String speciesName = ct.getMostRecentValueAsXrefName(motherName, "Species"); // TODO: get rid of duplication with AddAnimalPlugin // TODO: put this hardcoded info in the database (NamePrefix table) if (speciesName.equals("House mouse")) { this.prefix = "mm_"; } if (speciesName.equals("Brown rat")) { this.prefix = "rn_"; } if (speciesName.equals("Common vole")) { this.prefix = "mar_"; } if (speciesName.equals("Tundra vole")) { this.prefix = "mo_"; } if (speciesName.equals("Syrian hamster")) { this.prefix = "ma_"; } if (speciesName.equals("European groundsquirrel")) { this.prefix = "sc_"; } if (speciesName.equals("Siberian hamster")) { this.prefix = "ps_"; } if (speciesName.equals("Domestic guinea pig")) { this.prefix = "cp_"; } if (speciesName.equals("Fat-tailed dunnart")) { this.prefix = "sg_"; } } private Boolean isWeaned(Database db) throws Exception{ List<QueryRule> filterRules = new ArrayList<QueryRule>(); filterRules.add(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "WeanDate")); filterRules.add(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, this.litter)); List<ObservedValue> listId = db.find(ObservedValue.class, new QueryRule(filterRules)); if(listId.isEmpty()){ return false; }else{ return true; } } private Boolean isGenotyped(Database db) throws Exception{ List<QueryRule> filterRules = new ArrayList<QueryRule>(); filterRules.add(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "GenotypeDate")); filterRules.add(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, this.litter)); List<ObservedValue> listId = db.find(ObservedValue.class, new QueryRule(filterRules)); System.out.println("KIPJES " + listId.size()); if(listId.isEmpty()){ return false; }else{ return true; } } private String AddParentgroup2(Database db, Tuple request,List<String> papa, List<String> mama,String startdate,String remarks) throws Exception{ Date now = new Date(); String invName = ct.getOwnUserInvestigationNames(this.getLogin().getUserName()).get(0); Date eventDate = dbFormat.parse(startdate); // Make parentgroup String groupPrefix = "PG_" + line + "_"; int groupNr = ct.getHighestNumberForPrefix(groupPrefix) + 1; String groupNrPart = "" + groupNr; groupNrPart = ct.prependZeros(groupNrPart, 6); String groupName = groupPrefix + groupNrPart; ct.makePanel(invName, groupName, userName); // Make or update name prefix entry ct.updatePrefix("parentgroup", groupPrefix, groupNr); // Mark group as parent group using a special event db.add(ct.createObservedValueWithProtocolApplication(invName, now, null, "SetTypeOfGroup", "TypeOfGroup", groupName, "Parentgroup", null)); db.add(ct.createObservedValueWithProtocolApplication(invName, now, null, "SetLine", "Line", groupName, null, line)); // Add parent(s) AddParents(db, mama, "SetParentgroupMother", "ParentgroupMother", groupName, eventDate); AddParents(db, papa, "SetParentgroupFather", "ParentgroupFather", groupName, eventDate); // Set line // Set start date db.add(ct.createObservedValueWithProtocolApplication(invName, now, null, "SetStartDate", "StartDate", groupName, dbFormat.format(eventDate), null)); // Set remarks if (remarks != null) { db.add(ct.createObservedValueWithProtocolApplication(invName, now, null, "SetRemark", "Remark", groupName, remarks, null)); } //Add Set Active, with (start)time = entrydate and endtime = null db.add(ct.createObservedValueWithProtocolApplication(invName, now, null, "SetActive", "Active", groupName, "Active", null)); return groupName; } /* private String AddParentgroup(Database db, Tuple request) throws Exception { Date now = new Date(); String invName = ct.getOwnUserInvestigationNames(this.getLogin().getUserName()).get(0); // Save start date and remarks that were set in screen 4 if (request.getString("startdate") != null) { setStartdate(request.getString("startdate")); } if (request.getString("remarks") != null) { setRemarks(request.getString("remarks")); } Date eventDate = dateOnlyFormat.parse(startdate); // Make parentgroup String groupPrefix = "PG_" + line + "_"; int groupNr = ct.getHighestNumberForPrefix(groupPrefix) + 1; String groupNrPart = "" + groupNr; groupNrPart = ct.prependZeros(groupNrPart, 6); String groupName = groupPrefix + groupNrPart; ct.makePanel(invName, groupName, userName); // Make or update name prefix entry ct.updatePrefix("parentgroup", groupPrefix, groupNr); // Mark group as parent group using a special event db.add(ct.createObservedValueWithProtocolApplication(invName, now, null, "SetTypeOfGroup", "TypeOfGroup", groupName, "Parentgroup", null)); // Add parent(s) AddParents(db, this.selectedMotherNameList, "SetParentgroupMother", "ParentgroupMother", groupName, eventDate); AddParents(db, this.selectedFatherNameList, "SetParentgroupFather", "ParentgroupFather", groupName, eventDate); // Set line db.add(ct.createObservedValueWithProtocolApplication(invName, now, null, "SetLine", "Line", groupName, null, line)); // Set start date db.add(ct.createObservedValueWithProtocolApplication(invName, now, null, "SetStartDate", "StartDate", groupName, dbFormat.format(eventDate), null)); // Set remarks if (remarks != null) { db.add(ct.createObservedValueWithProtocolApplication(invName, now, null, "SetRemark", "Remark", groupName, remarks, null)); } //Add Set Active, with (start)time = entrydate and endtime = null db.add(ct.createObservedValueWithProtocolApplication(invName, now, null, "SetActive", "Active", groupName, "Active", null)); return groupName; } */ @Override public void reload(Database db) { ct.setDatabase(db); List<String> investigationNames = ct.getAllUserInvestigationNames(this.getLogin().getUserName()); // Populate lists (do this on every reload so they keep fresh, and do it here // because we need the lineList in the init part that comes after) try { // Populate line list lineList = ct.getAllMarkedPanels("Line", investigationNames); // Default selected is first line if (line == null && lineList.size() > 0) { line = lineList.get(0).getName(); } /*if (selectedMotherNameList == null) { selectedMotherNameList = new ArrayList<String>(); } if (selectedFatherNameList == null) { selectedFatherNameList = new ArrayList<String>(); }*/ } catch (Exception e) { String message = "Something went wrong while loading lists"; if (e.getMessage() != null) { message += (": " + e.getMessage()); } this.setError(message); e.printStackTrace(); } // Some init that only needs to be done once after login if (userName != this.getLogin().getUserName()) { userName = this.getLogin().getUserName(); ct.makeObservationTargetNameMap(userName, false); this.setStartdate(dbFormat.format(new Date())); // Prepare pg matrix if (pgMatrixViewer == null) { loadPgMatrixViewer(db); } pgMatrixViewer.setDatabase(db); pgMatrixViewerString = pgMatrixViewer.render(); // Prepare litter matrix if (litterMatrixViewer == null) { loadLitterMatrixViewer(db); } litterMatrixViewer.setDatabase(db); litterMatrixViewerString = litterMatrixViewer.render(); try { // Populate backgrounds list this.setBackgroundList(ct.getAllMarkedPanels("Background", investigationNames)); // Populate sexes list this.setSexList(ct.getAllMarkedPanels("Sex", investigationNames)); // Populate gene name list this.setGeneNameList(ct.getAllCodesForFeatureAsStrings("GeneModification")); // Populate gene state list this.setGeneStateList(ct.getAllCodesForFeatureAsStrings("GeneState")); // Populate color list this.setColorList(ct.getAllCodesForFeatureAsStrings("Color")); // Populate earmark list this.setEarmarkList(ct.getAllCodesForFeature("Earmark")); // Populate name prefixes list for the animals this.bases = new ArrayList<String>(); List<String> tmpPrefixes = ct.getPrefixes("animal"); for (String tmpPrefix : tmpPrefixes) { if (!tmpPrefix.equals("")) { this.bases.add(tmpPrefix); } } // Populate location list this.setLocationList(ct.getAllLocations()); } catch (Exception e) { String message = "Something went wrong while loading lists"; if (e.getMessage() != null) { message += (": " + e.getMessage()); } this.setError(message); e.printStackTrace(); } } } public String getBirthdate() { if (birthdate != null) { return birthdate; } return newDateOnlyFormat.format(new Date()); } public int getLitterSize() { return litterSize; } public String getLitterRemarks() { return litterRemarks; } public String getSelectedParentgroup() { if (selectedParentgroup != null) { return selectedParentgroup; } return "Error: no parentgoup selected"; } private String ApplyAddLitter(Database db, Tuple request) throws Exception { Date now = new Date(); setUserFields(request, false); Date eventDate = newDateOnlyFormat.parse(birthdate); String userName = this.getLogin().getUserName(); String invName = ct.getOwnUserInvestigationNames(userName).get(0); String lineName = ct.getMostRecentValueAsXrefName(selectedParentgroup, "Line"); // Init lists that we can later add to the DB at once List<ObservedValue> valuesToAddList = new ArrayList<ObservedValue>(); // Make group String litterPrefix = "LT_" + lineName + "_"; int litterNr = ct.getHighestNumberForPrefix(litterPrefix) + 1; String litterNrPart = "" + litterNr; litterNrPart = ct.prependZeros(litterNrPart, 6); String litterName = litterPrefix + litterNrPart; ct.makePanel(invName, litterName, userName); // Make or update name prefix entry ct.updatePrefix("litter", litterPrefix, litterNr); // Mark group as a litter db.add(ct.createObservedValueWithProtocolApplication(invName, now, null, "SetTypeOfGroup", "TypeOfGroup", litterName, "Litter", null)); // Apply other fields using event ProtocolApplication app = ct.createProtocolApplication(invName, "SetLitterSpecs"); db.add(app); String paName = app.getName(); // Parentgroup valuesToAddList.add(ct.createObservedValue(invName, paName, eventDate, null, "Parentgroup", litterName, null, selectedParentgroup)); // Set Line also on Litter if (lineName != null) { valuesToAddList.add(ct.createObservedValue(invName, paName, eventDate, null, "Line", litterName, null, lineName)); } // Date of Birth valuesToAddList.add(ct.createObservedValue(invName, paName, eventDate, null, "DateOfBirth", litterName, newDateOnlyFormat.format(eventDate), null)); // Size valuesToAddList.add(ct.createObservedValue(invName, paName, eventDate, null, "Size", litterName, Integer.toString(litterSize), null)); // Size approximate (certain)? String valueString = "0"; if (litterSizeApproximate == true) { valueString = "1"; } valuesToAddList.add(ct.createObservedValue(invName, paName, eventDate, null, "Certain", litterName, valueString, null)); // Remarks if (litterRemarks != null) { db.add(ct.createObservedValueWithProtocolApplication(invName, now, null, "SetRemark", "Remark", litterName, litterRemarks, null)); } // Try to get Source via Line String sourceName = ct.getMostRecentValueAsXrefName(lineName, "Source"); if (sourceName != null) { valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invName, eventDate, null, "SetSource", "Source", litterName, null, sourceName)); } // Active valuesToAddList.add(ct.createObservedValue(invName, paName, eventDate, null, "Active", litterName, "Active", null)); // Add everything to DB db.add(valuesToAddList); return litterName; } private void setUserFields(Tuple request, boolean wean) throws Exception { if (wean == true) { locName = request.getString("location"); if (locName != null && locName.equals("")) { locName = null; } respres = request.getString("respres"); if (request.getString("weandate") == null || request.getString("weandate").equals("")) { throw new Exception("Wean date cannot be empty"); } weandate = request.getString("weandate"); // in old date format! weanSizeFemale = 0; if (request.getInt("weansizefemale") != null) { weanSizeFemale = request.getInt("weansizefemale"); } weanSizeMale = 0; if (request.getInt("weansizemale") != null) { weanSizeMale = request.getInt("weansizemale"); } weanSizeUnknown = 0; if (request.getInt("weansizeunknown") != null) { weanSizeUnknown = request.getInt("weansizeunknown"); } remarks = request.getString("remarks"); if (request.getString("namebase") != null) { nameBase = request.getString("namebase"); if (nameBase.equals("New")) { if (request.getString("newnamebase") != null) { nameBase = request.getString("newnamebase"); } else { nameBase = ""; } } } else { nameBase = ""; } if (request.getInt("startnumber") != null) { startNumber = request.getInt("startnumber"); } else { startNumber = 1; // standard start at 1 } } else { if (request.getString("birthdate") == null || request.getString("birthdate").equals("")) { throw new Exception("Birth date cannot be empty"); } birthdate = request.getString("birthdate"); // in old date format! this.litterSize = request.getInt("littersize"); if (request.getBool("sizeapp_toggle") != null) { this.litterSizeApproximate = true; } else { this.litterSizeApproximate = false; } this.litterRemarks = request.getString("litterremarks"); } } private String findParentForParentgroup(String parentgroupName, String parentSex, Database db) throws DatabaseException, ParseException { ct.setDatabase(db); Query<ObservedValue> parentQuery = db.query(ObservedValue.class); parentQuery.addRules(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, parentgroupName)); parentQuery.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "Parentgroup" + parentSex)); List<ObservedValue> parentValueList = parentQuery.find(); if (parentValueList.size() > 0) { return parentValueList.get(0).getRelation_Name(); } else { throw new DatabaseException("Fatal error: no " + parentSex + " found for parentgroup " + parentgroupName); } } private int Wean(Database db, Tuple request) throws Exception { Date now = new Date(); String invName = ct.getObservationTargetByName(litter).getInvestigation_Name(); setUserFields(request, true); Date weanDate = newDateOnlyFormat.parse(weandate); String userName = this.getLogin().getUserName(); // Init lists that we can later add to the DB at once List<ObservedValue> valuesToAddList = new ArrayList<ObservedValue>(); List<ObservationTarget> animalsToAddList = new ArrayList<ObservationTarget>(); // Source (take from litter) String sourceName = ct.getMostRecentValueAsXrefName(litter, "Source"); // Get litter birth date String litterBirthDateString = ct.getMostRecentValueAsString(litter, "DateOfBirth"); //Date litterBirthDate = newDateOnlyFormat.parse(litterBirthDateString); // Find Parentgroup for this litter String parentgroupName = ct.getMostRecentValueAsXrefName(litter, "Parentgroup"); // Find Line for this Parentgroup String lineName = ct.getMostRecentValueAsXrefName(parentgroupName, "Line"); // Find first mother, plus her animal type, species, color, background, gene modification and gene state // TODO: find ALL gene info String motherName = findParentForParentgroup(parentgroupName, "Mother", db); String speciesName = ct.getMostRecentValueAsXrefName(motherName, "Species"); String motherAnimalType = ct.getMostRecentValueAsString(motherName, "AnimalType"); String color = ct.getMostRecentValueAsString(motherName, "Color"); String motherBackgroundName = ct.getMostRecentValueAsXrefName(motherName, "Background"); String geneName = ct.getMostRecentValueAsString(motherName, "GeneModification"); String geneState = ct.getMostRecentValueAsString(motherName, "GeneState"); // Find father and his background String fatherName = findParentForParentgroup(parentgroupName, "Father", db); String fatherBackgroundName = ct.getMostRecentValueAsXrefName(fatherName, "Background"); String fatherAnimalType = ct.getMostRecentValueAsString(fatherName, "AnimalType"); // Deduce animal type String animalType = motherAnimalType; // If one of the parents is GMO, animal is GMO if (motherAnimalType.equals("B. Transgeen dier") || fatherAnimalType.equals("B. Transgeen dier")) { animalType = "B. Transgeen dier"; } // Keep normal and transgene types, but set type of child from wild mother to normal if (animalType.equals("C. Wildvang") || animalType.equals("D. Biotoop")) { animalType = "A. Gewoon dier"; } // Set wean sizes int weanSize = weanSizeFemale + weanSizeMale + weanSizeUnknown; valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invName, now, null, "SetWeanSize", "WeanSize", litter, Integer.toString(weanSize), null)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invName, now, null, "SetWeanSizeFemale", "WeanSizeFemale", litter, Integer.toString(weanSizeFemale), null)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invName, now, null, "SetWeanSizeMale", "WeanSizeMale", litter, Integer.toString(weanSizeMale), null)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invName, now, null, "SetWeanSizeUnknown", "WeanSizeUnknown", litter, Integer.toString(weanSizeUnknown), null)); // Set wean date on litter -> this is how we mark a litter as weaned (but not genotyped) valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invName, weanDate, null, "SetWeanDate", "WeanDate", litter, newDateOnlyFormat.format(weanDate), null)); // Set weaning remarks on litter if (remarks != null) { db.add(ct.createObservedValueWithProtocolApplication(invName, now, null, "SetRemark", "Remark", litter, remarks, null)); } // Make animal, link to litter, parents and set wean dates etc. for (int animalNumber = 0; animalNumber < weanSize; animalNumber++) { String nrPart = "" + (startNumber + animalNumber); nrPart = ct.prependZeros(nrPart, 6); ObservationTarget animalToAdd = ct.createIndividual(invName, nameBase + nrPart, userName); animalsToAddList.add(animalToAdd); } db.add(animalsToAddList); // Make or update name prefix entry ct.updatePrefix("animal", nameBase, startNumber + weanSize - 1); int animalNumber = 0; for (ObservationTarget animal : animalsToAddList) { String animalName = animal.getName(); // TODO: link every value to a single Wean protocol application instead of to its own one // Link to litter valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invName, weanDate, null, "SetLitter", "Litter", animalName, null, litter)); // Link to parents using the Mother and Father measurements if (motherName != null) { valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invName, weanDate, null, "SetMother", "Mother", animalName, null, motherName)); } if (fatherName != null) { valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invName, weanDate, null, "SetFather", "Father", animalName, null, fatherName)); } // Set line also on animal itself if (lineName != null) { valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invName, weanDate, null, "SetLine", "Line", animalName, null, lineName)); } // Set responsible researcher if (respres != null) { valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invName, now, null, "SetResponsibleResearcher", "ResponsibleResearcher", animalName, respres, null)); } // Set location if (locName != null) { valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invName, now, null, "SetLocation", "Location", animalName, null, locName)); } // Set sex String sexName = "Female"; if (animalNumber >= weanSizeFemale) { if (animalNumber < weanSizeFemale + weanSizeMale) { sexName = "Male"; } else { sexName = "UnknownSex"; } } valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invName, weanDate, null, "SetSex", "Sex", animalName, null, sexName)); // Set wean date on animal valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invName, weanDate, null, "SetWeanDate", "WeanDate", animalName, newDateOnlyFormat.format(weanDate), null)); // Set 'Active' -> starts at wean date valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invName, weanDate, null, "SetActive", "Active", animalName, "Alive", null)); // Set 'Date of Birth' valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invName, weanDate, null, "SetDateOfBirth", "DateOfBirth", animalName, litterBirthDateString, null)); // Set species if (speciesName != null) { valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invName, weanDate, null, "SetSpecies", "Species", animalName, null, speciesName)); } // Set animal type valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invName, weanDate, null, "SetAnimalType", "AnimalType", animalName, animalType, null)); // Set source valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invName, weanDate, null, "SetSource", "Source", animalName, null, sourceName)); // Set color based on mother's (can be changed during genotyping) if (color != null && !color.equals("")) { valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invName, weanDate, null, "SetColor", "Color", animalName, color, null)); } // Set background based on mother's and father's (can be changed during genotyping) String backgroundName = null; if (motherBackgroundName != null && fatherBackgroundName == null) { backgroundName = motherBackgroundName; } else if (motherBackgroundName == null && fatherBackgroundName != null) { backgroundName = fatherBackgroundName; } else if (motherBackgroundName != null && fatherBackgroundName != null) { // Make new or use existing cross background if (motherBackgroundName.equals(fatherBackgroundName)) { backgroundName = fatherBackgroundName; } else { backgroundName = fatherBackgroundName + " X " + motherBackgroundName; } if (ct.getObservationTargetByName(backgroundName) == null) { // create if not exists ct.makePanel(invName, backgroundName, userName); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invName, weanDate, null, "SetTypeOfGroup", "TypeOfGroup", backgroundName, "Background", null)); } } if (backgroundName != null) { valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invName, weanDate, null, "SetBackground", "Background", animalName, null, backgroundName)); } // Set genotype // TODO: Set based on mother's X father's and ONLY if you can know the outcome if (geneName != null && !geneName.equals("") && geneState != null && !geneState.equals("")) { String paName = ct.makeProtocolApplication(invName, "SetGenotype"); // Set gene mod name based on mother's (can be changed during genotyping) valuesToAddList.add(ct.createObservedValue(invName, paName, weanDate, null, "GeneModification", animalName, geneName, null)); // Set gene state based on mother's (can be changed during genotyping) valuesToAddList.add(ct.createObservedValue(invName, paName, weanDate, null, "GeneState", animalName, geneState, null)); } animalNumber++; } db.add(valuesToAddList); return weanSize; } public String getLitter() { return this.litter; } public String getSpeciesBase() { if (this.prefix != null) { return this.prefix; } return ""; } public List<String> getBases() { return bases; } public List<ObservationTarget> getBackgroundList() { return backgroundList; } public void setBackgroundList(List<ObservationTarget> backgroundList) { this.backgroundList = backgroundList; } public List<String> getGeneNameList() { return geneNameList; } public void setGeneNameList(List<String> geneNameList) { this.geneNameList = geneNameList; } public List<String> getGeneStateList() { return geneStateList; } public void setGeneStateList(List<String> geneStateList) { this.geneStateList = geneStateList; } public List<ObservationTarget> getSexList() { return sexList; } public void setSexList(List<ObservationTarget> sexList) { this.sexList = sexList; } public List<String> getColorList() { return colorList; } public void setColorList(List<String> colorList) { this.colorList = colorList; } public List<Category> getEarmarkList() { return earmarkList; } public void setEarmarkList(List<Category> earmarkList) { this.earmarkList = earmarkList; } public List<Location> getLocationList() { return locationList; } public void setLocationList(List<Location> locationList) { this.locationList = locationList; } public String getStartNumberHelperContent() { try { String helperContents = ""; helperContents += (ct.getHighestNumberForPrefix("") + 1); helperContents += ";1"; for (String base : this.bases) { if (!base.equals("")) { helperContents += (";" + (ct.getHighestNumberForPrefix(base) + 1)); } } return helperContents; } catch (Exception e) { return ""; } } public int getStartNumberForPreselectedBase() { try { return ct.getHighestNumberForPrefix(this.prefix) + 1; } catch (DatabaseException e) { return 1; } } public List<Individual> getAnimalsInLitter(String litterName, Database db) { List<Individual> returnList = new ArrayList<Individual>(); try { Query<ObservedValue> q = db.query(ObservedValue.class); q.addRules(new QueryRule(ObservedValue.RELATION_NAME, Operator.EQUALS, litterName)); q.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "Litter")); List<ObservedValue> valueList = q.find(); for (ObservedValue value : valueList) { int animalId = value.getTarget_Id(); returnList.add(ct.getIndividualById(animalId)); } return returnList; } catch (Exception e) { // On fail, return empty list to UI return new ArrayList<Individual>(); } } public List<Individual> getAnimalsInLitter(Database db) { try { return getAnimalsInLitter(this.litter, db); } catch (Exception e) { // On fail, return empty list to UI return new ArrayList<Individual>(); } } public Date getAnimalBirthDate(String animalName) { try { String birthDateString = ct.getMostRecentValueAsString(animalName, "DateOfBirth"); return newDateOnlyFormat.parse(birthDateString); } catch (Exception e) { return null; } } public String getAnimalSex(String animalName) { try { return ct.getMostRecentValueAsXrefName(animalName, "Sex"); } catch (Exception e) { return null; } } public String getAnimalColor(String animalName) { try { if (ct.getMostRecentValueAsString(animalName, "Color") != null) { return ct.getMostRecentValueAsString(animalName, "Color"); } else { return ""; } } catch (Exception e) { return "unknown"; } } public String getAnimalEarmark(String animalName) { try { if (ct.getMostRecentValueAsString(animalName, "Earmark") != null) { return ct.getMostRecentValueAsString(animalName, "Earmark"); } else { return ""; } } catch (Exception e) { return ""; } } public String getAnimalBackground(String animalName) { try { return ct.getMostRecentValueAsXrefName(animalName, "Background"); } catch (Exception e) { return null; } } public String getAnimalGeneInfo(String measurementName, String animalName, int genoNr, Database db) { Query<ObservedValue> q = db.query(ObservedValue.class); q.addRules(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, animalName)); q.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, measurementName)); List<ObservedValue> valueList; try { valueList = q.find(); } catch (DatabaseException e) { return ""; } if (valueList.size() > genoNr) { return valueList.get(genoNr).getValue(); } else { return ""; } } private int Genotype(Database db, Tuple request) throws Exception { Date now = new Date(); String invName = ct.getObservationTargetByName(this.litter).getInvestigation_Name(); List<String> investigationNames = ct.getAllUserInvestigationNames(this.getLogin().getUserName()); // Set genotype date on litter -> this is how we mark a litter as genotyped if (request.getString("genodate") == null) { throw new Exception("Genotype date not filled in - litter not genotyped"); } Date genoDate = newDateOnlyFormat.parse(request.getString("genodate")); String genodate = dbFormat.format(genoDate); db.add(ct.createObservedValueWithProtocolApplication(invName, now, null, "SetGenotypeDate", "GenotypeDate", this.litter, genodate, null)); // Set genotyping remarks on litter if (request.getString("remarks") != null) { db.add(ct.createObservedValueWithProtocolApplication(invName, now, null, "SetRemark", "Remark", this.litter, request.getString("remarks"), null)); } int animalCount = 0; for (Individual animal : this.getAnimalsInLitter(db)) { // Here we (re)set the values from the genotyping // Set sex String sexName = request.getString("1_" + animalCount); ObservedValue value = ct.getObservedValuesByTargetAndFeature(animal.getName(), "Sex", investigationNames, invName).get(0); value.setRelation_Name(sexName); value.setValue(null); if (value.getProtocolApplication_Id() == null) { String paName = ct.makeProtocolApplication(invName, "SetSex"); value.setProtocolApplication_Name(paName); db.add(value); } else { db.update(value); } // Set birth date String dob = request.getString("0_" + animalCount); // already in new format value = ct.getObservedValuesByTargetAndFeature(animal.getName(), "DateOfBirth", investigationNames, invName).get(0); value.setValue(dob); if (value.getProtocolApplication_Id() == null) { String paName = ct.makeProtocolApplication(invName, "SetDateOfBirth"); value.setProtocolApplication_Name(paName); db.add(value); } else { db.update(value); } // Set color String color = request.getString("2_" + animalCount); value = ct.getObservedValuesByTargetAndFeature(animal.getName(), "Color", investigationNames, invName).get(0); value.setValue(color); if (value.getProtocolApplication_Id() == null) { String paName = ct.makeProtocolApplication(invName, "SetColor"); value.setProtocolApplication_Name(paName); db.add(value); } else { db.update(value); } // Set earmark String earmark = request.getString("3_" + animalCount); value = ct.getObservedValuesByTargetAndFeature(animal.getName(), "Earmark", investigationNames, invName).get(0); value.setValue(earmark); if (value.getProtocolApplication_Id() == null) { String paName = ct.makeProtocolApplication(invName, "SetEarmark"); value.setProtocolApplication_Name(paName); db.add(value); } else { db.update(value); } // Set background String backgroundName = request.getString("4_" + animalCount); value = ct.getObservedValuesByTargetAndFeature(animal.getName(), "Background", investigationNames, invName).get(0); value.setRelation_Name(backgroundName); value.setValue(null); if (value.getProtocolApplication_Id() == null) { String paName = ct.makeProtocolApplication(invName, "SetBackground"); value.setProtocolApplication_Name(paName); db.add(value); } else { db.update(value); } // Set genotype(s) for (int genoNr = 0; genoNr < nrOfGenotypes; genoNr++) { int currCol = 5 + (genoNr * 2); String paName = ct.makeProtocolApplication(invName, "SetGenotype"); String geneName = request.getString(currCol + "_" + animalCount); if (geneName == null || geneName.equals("")) { continue; // skip genes that have not been filled in } List<ObservedValue> valueList = ct.getObservedValuesByTargetAndFeature(animal.getName(), "GeneModification", investigationNames, invName); if (genoNr < valueList.size()) { value = valueList.get(genoNr); } else { value = new ObservedValue(); value.setFeature_Name("GeneModification"); value.setTarget_Name(animal.getName()); value.setInvestigation_Name(invName); } value.setValue(geneName); if (value.getProtocolApplication_Id() == null) { value.setProtocolApplication_Name(paName); db.add(value); } else { db.update(value); } String geneState = request.getString((currCol + 1) + "_" + animalCount); valueList = ct.getObservedValuesByTargetAndFeature(animal.getName(), "GeneState", investigationNames, invName); if (genoNr < valueList.size()) { value = valueList.get(genoNr); } else { value = new ObservedValue(); value.setFeature_Name("GeneState"); value.setTarget_Name(animal.getName()); value.setInvestigation_Name(invName); } value.setValue(geneState); if (value.getProtocolApplication_Id() == null) { value.setProtocolApplication_Name(paName); db.add(value); } else { db.update(value); } } animalCount++; } return animalCount; } @SuppressWarnings({ "rawtypes", "unchecked" }) private void storeGenotypeTable(Database db, Tuple request) { HtmlInput input; for (int animalCount = 0; animalCount < this.getAnimalsInLitter(db).size(); animalCount++) { if (request.getString("0_" + animalCount) != null) { String dob = request.getString("0_" + animalCount); // already in new format input = (HtmlInput) genotypeTable.getCell(0, animalCount); input.setValue(dob); genotypeTable.setCell(0, animalCount, input); } if (request.getString("1_" + animalCount) != null) { String sexName = request.getString("1_" + animalCount); input = (HtmlInput) genotypeTable.getCell(1, animalCount); input.setValue(sexName); genotypeTable.setCell(1, animalCount, input); } if (request.getString("2_" + animalCount) != null) { String color = request.getString("2_" + animalCount); input = (HtmlInput) genotypeTable.getCell(2, animalCount); input.setValue(color); genotypeTable.setCell(2, animalCount, input); } if (request.getString("3_" + animalCount) != null) { String earmark = request.getString("3_" + animalCount); input = (HtmlInput) genotypeTable.getCell(3, animalCount); input.setValue(earmark); genotypeTable.setCell(3, animalCount, input); } if (request.getString("4_" + animalCount) != null) { String backgroundName = request.getString("4_" + animalCount); input = (HtmlInput) genotypeTable.getCell(4, animalCount); input.setValue(backgroundName); genotypeTable.setCell(4, animalCount, input); } for (int genoNr = 0; genoNr < nrOfGenotypes; genoNr++) { int currCol = 5 + (genoNr * 2); if (request.getString(currCol + "_" + animalCount) != null) { String geneName = request.getString(currCol + "_" + animalCount); input = (HtmlInput) genotypeTable.getCell(currCol, animalCount); input.setValue(geneName); genotypeTable.setCell(currCol, animalCount, input); } if (request.getString((currCol + 1) + "_" + animalCount) != null) { String geneState = request.getString((currCol + 1) + "_" + animalCount); input = (HtmlInput) genotypeTable.getCell(currCol + 1, animalCount); input.setValue(geneState); genotypeTable.setCell(currCol + 1, animalCount, input); } } animalCount++; } } private void AddGenoCol(Database db, Tuple request) { nrOfGenotypes++; genotypeTable.addColumn("Gene modification"); genotypeTable.addColumn("Gene state"); int row = 0; for (Individual animal : getAnimalsInLitter(db)) { String animalName = animal.getName(); // Check for already selected genes for this animal List<String> selectedGenes = new ArrayList<String>(); for (int genoNr = 0; genoNr < nrOfGenotypes - 1; genoNr++) { int currCol = 5 + (genoNr * 2); if (request.getString(currCol + "_" + row) != null) { selectedGenes.add(request.getString(currCol + "_" + row)); } } // Make new gene mod name box int newCol = 5 + ((nrOfGenotypes - 1) * 2); SelectInput geneNameInput = new SelectInput(newCol + "_" + row); for (String geneName : this.geneNameList) { if (!selectedGenes.contains(geneName)) { geneNameInput.addOption(geneName, geneName); } } geneNameInput.setValue(getAnimalGeneInfo("GeneModification", animalName, nrOfGenotypes, db)); geneNameInput.setWidth(-1); genotypeTable.setCell(newCol, row, geneNameInput); // Make new gene state box SelectInput geneStateInput = new SelectInput((newCol + 1) + "_" + row); for (String geneState : this.geneStateList) { geneStateInput.addOption(geneState, geneState); } geneStateInput.setValue(getAnimalGeneInfo("GeneState", animalName, nrOfGenotypes, db)); geneStateInput.setWidth(-1); genotypeTable.setCell(newCol + 1, row, geneStateInput); row++; } } public boolean getWean() { return this.wean; } public String getParentInfo() { return this.parentInfo; } private String getLineInfo(String parentgroupName) throws DatabaseException, ParseException { String lineName = ct.getMostRecentValueAsXrefName(parentgroupName, "Line"); return lineName; } private String getGenoInfo(String animalName, Database db) throws DatabaseException, ParseException { String returnString = ""; String animalBackgroundName = ct.getMostRecentValueAsXrefName(animalName, "Background"); returnString += ("background: " + animalBackgroundName + "; "); Query<ObservedValue> q = db.query(ObservedValue.class); q.addRules(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, animalName)); q.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "GeneModification")); List<ObservedValue> valueList = q.find(); if (valueList != null) { for (ObservedValue value : valueList) { String geneName = value.getValue(); String geneState = ""; Query<ObservedValue> geneStateQuery = db.query(ObservedValue.class); geneStateQuery.addRules(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, animalName)); geneStateQuery.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "GeneState")); geneStateQuery.addRules(new QueryRule(ObservedValue.PROTOCOLAPPLICATION, Operator.EQUALS, value.getProtocolApplication_Id())); List<ObservedValue> geneStateValueList = geneStateQuery.find(); if (geneStateValueList != null && geneStateValueList.size() > 0) { geneState = geneStateValueList.get(0).getValue(); } if (geneName == null || geneName.equals("null") || geneName.equals("")) { geneName = "unknown"; } if (geneState == null || geneState.equals("null") || geneState.equals("")) { geneState = "unknown"; } returnString += ("gene: " + geneName + ": " + geneState + "; "); } } if (returnString.length() > 0) { returnString = returnString.substring(0, returnString.length() - 2); } return returnString; } public String getGenotypeTable() { return genotypeTable.render(); } private void makeDefCageLabels(Database db) throws LabelGeneratorException, DatabaseException, ParseException { // PDF file stuff File tmpDir = new File(System.getProperty("java.io.tmpdir")); File pdfFile = new File(tmpDir.getAbsolutePath() + File.separatorChar + "deflabels.pdf"); String filename = pdfFile.getName(); LabelGenerator labelgenerator = new LabelGenerator(2); labelgenerator.startDocument(pdfFile); // Litter stuff String parentgroupName = ct.getMostRecentValueAsXrefName(litter, "Parentgroup"); String line = this.getLineInfo(parentgroupName); String motherName = findParentForParentgroup(parentgroupName, "Mother", db); String motherInfo = this.getGenoInfo(motherName, db); String fatherName = findParentForParentgroup(parentgroupName, "Father", db); String fatherInfo = this.getGenoInfo(fatherName, db); List<String> elementLabelList; List<String> elementList; for (Individual animal : this.getAnimalsInLitter(litter, db)) { String animalName = animal.getName(); elementList = new ArrayList<String>(); elementLabelList = new ArrayList<String>(); // Name / custom label elementLabelList.add("Name:"); elementList.add(animalName); // Earmark elementLabelList.add("Earmark:"); elementList.add(ct.getMostRecentValueAsString(animalName, "Earmark")); // Line elementLabelList.add("Line:"); elementList.add(line); // Background + GeneModification + GeneState elementLabelList.add("Genotype:"); elementList.add(this.getGenoInfo(animalName, db)); // Color + Sex elementLabelList.add("Color and Sex:"); String color = ct.getMostRecentValueAsString(animalName, "Color"); if (color == null || color.equals("null") || color.equals("")) { color = "unknown"; } String sex = ct.getMostRecentValueAsXrefName(animalName, "Sex"); elementList.add(color + "\t\t" + sex); //Birthdate elementLabelList.add("Birthdate:"); elementList.add(ct.getMostRecentValueAsString(animalName, "DateOfBirth")); // Geno mother elementLabelList.add("Genotype mother:"); elementList.add(motherInfo); // Geno father elementLabelList.add("Genotype father:"); elementList.add(fatherInfo); // Add DEC nr, if present, or empty if not elementLabelList.add("DEC:"); String decNr = ct.getMostRecentValueAsString(animalName, "DecNr"); String expNr = ct.getMostRecentValueAsString(animalName, "ExperimentNr"); String decInfo = (decNr != null ? decNr : "") + " " + (expNr != null ? expNr : ""); elementList.add(decInfo); // Not needed at this time, maybe later: // Birthdate //elementList.add("Birthdate: " + ct.getMostRecentValueAsString(animalId, ct.getMeasurementId("DateOfBirth"))); // OldUliDbExperimentator -> TODO: add responsible researcher //elementList.add("Experimenter: " + ct.getMostRecentValueAsString(animalId, ct.getMeasurementId("OldUliDbExperimentator"))); labelgenerator.addLabelToDocument(elementLabelList, elementList); } // In case of an odd number of animals, add extra label to make row full if (this.getAnimalsInLitter(litter, db).size() %2 != 0) { elementLabelList = new ArrayList<String>(); elementList = new ArrayList<String>(); labelgenerator.addLabelToDocument(elementLabelList, elementList); } labelgenerator.finishDocument(); this.setLabelDownloadLink("<a href=\"tmpfile/" + filename + "\" target=\"blank\">Download definitive cage labels as pdf</a>"); } private void makeTempCageLabels(Database db) throws Exception { // PDF file stuff File tmpDir = new File(System.getProperty("java.io.tmpdir")); File pdfFile = new File(tmpDir.getAbsolutePath() + File.separatorChar + "weanlabels.pdf"); String filename = pdfFile.getName(); LabelGenerator labelgenerator = new LabelGenerator(2); labelgenerator.startDocument(pdfFile); List<String> elementList; // Selected litter stuff String parentgroupName = ct.getMostRecentValueAsXrefName(litter, "Parentgroup"); String lineName = ct.getMostRecentValueAsXrefName(parentgroupName, "Line"); String motherName = findParentForParentgroup(parentgroupName, "Mother", db); String fatherName = findParentForParentgroup(parentgroupName, "Father", db); String litterBirthDateString = ct.getMostRecentValueAsString(litter, "DateOfBirth"); int nrOfFemales = Integer.parseInt(ct.getMostRecentValueAsString(litter, "WeanSizeFemale")); int nrOfMales = Integer.parseInt(ct.getMostRecentValueAsString(litter, "WeanSizeMale")); int nrOfUnknowns = Integer.parseInt(ct.getMostRecentValueAsString(litter, "WeanSizeUnknown")); List<ObservedValue> litterValList = db.query(ObservedValue.class).eq(ObservedValue.FEATURE_NAME, "Litter"). eq(ObservedValue.RELATION_NAME, litter).find(); List<String> females = new ArrayList<String>(); List<String> males = new ArrayList<String>(); List<String> unknowns = new ArrayList<String>(); for (ObservedValue litterVal : litterValList) { String animalName = litterVal.getTarget_Name(); if (ct.getMostRecentValueAsXrefName(animalName, "Sex").equals("Female")) { females.add(animalName); } else if (ct.getMostRecentValueAsXrefName(animalName, "Sex").equals("Male")) { males.add(animalName); } else { unknowns.add(animalName); } } // Labels for females int nrOfCages = 0; int femaleNr = 0; while (nrOfFemales > 0) { elementList = new ArrayList<String>(); // Line name + Nr. of females in cage String firstLine = lineName + "\t\t"; // Females can be 2 or 3 in a cage, if possible not 1 int cageSize; if (nrOfFemales > 4) { cageSize = 3; } else { if (nrOfFemales == 4) { cageSize = 2; } else { cageSize = nrOfFemales; } } firstLine += (cageSize + " female"); if (cageSize > 1) firstLine += "s"; elementList.add(firstLine); // Parents elementList.add(motherName + " x " + fatherName); // Litter birth date elementList.add(litterBirthDateString); // Nrs. for writing extra information behind for (int i = 1; i <= cageSize; i++) { elementList.add(females.get(femaleNr++) + "."); } labelgenerator.addLabelToDocument(elementList); nrOfFemales -= cageSize; nrOfCages++; } // Labels for males int maleNr = 0; while (nrOfMales > 0) { elementList = new ArrayList<String>(); // Line name + Nr. of males in cage String firstLine = lineName; if (nrOfMales >= 2) { firstLine += "\t\t2 males"; } else { firstLine += "\t\t1 male"; } elementList.add(firstLine); // Parents elementList.add(motherName + " x " + fatherName); // Litter birth date elementList.add(litterBirthDateString); // Nrs. for writing extra information behind for (int i = 1; i <= Math.min(nrOfMales, 2); i++) { elementList.add(males.get(maleNr++) + "."); } labelgenerator.addLabelToDocument(elementList); nrOfMales -= 2; nrOfCages++; } // Labels for unknowns // TODO: keep or group together with (fe)males? int unknownNr = 0; while (nrOfUnknowns > 0) { elementList = new ArrayList<String>(); // Line name + Nr. of unknowns in cage String firstLine = lineName; if (nrOfUnknowns >= 2) { firstLine += "\t\t2 unknowns"; } else { firstLine += "\t\t1 unknown"; } elementList.add(firstLine); // Parents elementList.add(motherName + " x " + fatherName); // Litter birth date elementList.add(litterBirthDateString); // Nrs. for writing extra information behind for (int i = 1; i <= Math.min(nrOfUnknowns, 2); i++) { elementList.add(unknowns.get(unknownNr++) + "."); } labelgenerator.addLabelToDocument(elementList); nrOfUnknowns -= 2; nrOfCages++; } // In case of an odd number of cages, add extra label to make row full if (nrOfCages %2 != 0) { elementList = new ArrayList<String>(); labelgenerator.addLabelToDocument(elementList); } labelgenerator.finishDocument(); this.setLabelDownloadLink("<a href=\"tmpfile/" + filename + "\" target=\"blank\">Download temporary wean labels as pdf</a>"); } public String getLabelDownloadLink() { return labelDownloadLink; } public void setLabelDownloadLink(String labelDownloadLink) { this.labelDownloadLink = labelDownloadLink; } public String getWeandate() { if (weandate != null) { return weandate; } return dbFormat.format(new Date()); } public String getGenodate() { return dbFormat.format(new Date()); } public int getNumberOfPG() { return numberOfPG; } public List<String> getPgName() { return pgName; } // public HashMap<String, List<String>> getHashMothers() // { // return hashMothers; // } public HashMap<Integer, List<String>> getHashMothers() { return hashMothers; } public List<String> getMotherElement(Integer key) { return hashMothers.get(key); } public List<String> getFatherElement(Integer key) { return hashFathers.get(key); } public String getSex() { return sex; } public HashMap<Integer, List<String>> getHashFathers() { return hashFathers; } public boolean isStillToWeanYN() { return stillToWeanYN; } public boolean isStillToGenotypeYN() { return stillToGenotypeYN; } }
true
true
public void handleRequest(Database db, Tuple request) { ct.setDatabase(db); action = request.getString("__action"); try { if (motherMatrixViewer != null && action.startsWith(motherMatrixViewer.getName())) { motherMatrixViewer.setDatabase(db); motherMatrixViewer.handleRequest(db, request); motherMatrixViewerString = motherMatrixViewer.render(); this.action = "selectParents"; // return to mother selection screen return; } if (fatherMatrixViewer != null && action.startsWith(fatherMatrixViewer.getName())) { fatherMatrixViewer.setDatabase(db); fatherMatrixViewer.handleRequest(db, request); fatherMatrixViewerString = fatherMatrixViewer.render(); this.action = "addParentgroupScreen3"; // return to father selection screen //this.action = "selectParents"; return; } if (pgMatrixViewer != null && action.startsWith(pgMatrixViewer.getName())) { pgMatrixViewer.setDatabase(db); pgMatrixViewer.handleRequest(db, request); pgMatrixViewerString = pgMatrixViewer.render(); this.action = "init"; // return to start screen this.entity = "Parentgroups"; return; } if (litterMatrixViewer != null && action.startsWith(litterMatrixViewer.getName())) { litterMatrixViewer.setDatabase(db); litterMatrixViewer.handleRequest(db, request); litterMatrixViewerString = litterMatrixViewer.render(); this.action = "init"; // return to start screen this.entity = "Litters"; return; } if (action.equals("init")) { // do nothing here } if (action.equals("selectParents")) { hashFathers.clear(); hashMothers.clear(); List<String> lis = new ArrayList<String>(); lis.add(""); numberOfPG = request.getInt("numberPG"); if(numberOfPG == null) { numberOfPG = -1; } for(int i = 0; i < numberOfPG; i++){ hashMothers.put(i, lis); hashFathers.put(i, lis); pgName.add(i+""); } } if(pgName.size()!=0){ for(int i= 0; i < pgName.size(); i++){ if(action.equals("selectParentsM"+(i))){ List<String> selectedFatherNameList = new ArrayList<String>(); @SuppressWarnings("unchecked") List<ObservationElement> rows = (List<ObservationElement>) motherMatrixViewer.getSelection(db); int rowCnt = 0; sex = "not selected"; for (ObservationElement row : rows) { if (request.getBool(MOTHERMATRIX + "_selected_" + rowCnt) != null) { String fatherName = row.getName(); sex = ct.getMostRecentValueAsXrefName(fatherName, "Sex"); if(sex.equals("Male")){ if (!selectedFatherNameList.contains(fatherName)) { selectedFatherNameList.add(fatherName); } }else{ this.setMessages(new ScreenMessage("Not a Female", false)); } } rowCnt++; } hashFathers.put(i, selectedFatherNameList); } if(action.equals("selectParentsF"+(i))){ List<String> selectedMotherNameList = new ArrayList<String>(); @SuppressWarnings("unchecked") List<ObservationElement> rows = (List<ObservationElement>) motherMatrixViewer.getSelection(db); int rowCnt = 0; sex = "not selected"; for (ObservationElement row : rows) { if (request.getBool(MOTHERMATRIX + "_selected_" + rowCnt) != null) { String motherName = row.getName(); sex = ct.getMostRecentValueAsXrefName(motherName, "Sex"); if(sex.equals("Female")){ if (!selectedMotherNameList.contains(motherName)) { selectedMotherNameList.add(motherName); } } else{ this.setMessages(new ScreenMessage("Not a Female", false)); } } rowCnt++; } hashMothers.put(i, selectedMotherNameList); } } } try{ if(action.equals("init")){ hashFathers.clear(); hashMothers.clear(); numberOfPG = null; } if(action.equals("JensonButton")){ boolean papa = false; boolean mama = false; List<String> pgNames = new ArrayList<String>(); for(Entry<Integer,List<String>> entry : hashFathers.entrySet()){ for(String s : entry.getValue()){ if(s.isEmpty()){ papa = true; } } } for(Entry<Integer,List<String>> entry : hashMothers.entrySet()){ for(String s : entry.getValue()){ if(s.isEmpty()){ mama = true; } } } if(papa == false || mama == false){ for(Entry <Integer,List<String>> entry: hashFathers.entrySet()){ String x = ""; String y = ""; if(request.getDate("startdate"+entry.getKey())!=null){ x = request.getString("startdate"+entry.getKey()); } if(request.getString("remarks"+entry.getKey())!=null){ y = request.getString("remarks"+entry.getKey()); } pgNames.add(AddParentgroup2(db, request,entry.getValue(),hashMothers.get(entry.getKey()),x,y)); // Reset matrix and add filter on name of newly added PG: loadPgMatrixViewer(db); pgMatrixViewer.setDatabase(db); //pgMatrixViewer.getMatrix().getRules().add(new MatrixQueryRule(MatrixQueryRule.Type.rowHeader, //Individual.NAME, Operator.EQUALS, pgNames)); pgMatrixViewer.reloadMatrix(db, null); pgMatrixViewerString = pgMatrixViewer.render(); // Reset other fields this.action = "init"; this.startdate = newDateOnlyFormat.format(new Date()); this.remarks = null; motherMatrixViewer = null; this.setSuccess("Parentgroup " + pgNames + " successfully added; adding filter to matrix: name = " + pgNames); } hashFathers.clear(); hashMothers.clear(); numberOfPG = null; } else{ this.setMessages(new ScreenMessage("Not all fathers or mothers are filled in", false)); action = "selectParents"; } } } catch(Exception e){ //this.setMessages(new ScreenMessage("Not all fathers or mothers are filled in", false)); } if (action.equals("createParentgroup")) { numberOfPG = -1; loadMotherMatrixViewer(db); motherMatrixViewer.setDatabase(db); motherMatrixViewerString = motherMatrixViewer.render(); } if (action.equals("changeLine")) { this.line = request.getString("line"); this.setSuccess("Breeding line changed to " + this.line); // Reset matrices and return to main screen loadPgMatrixViewer(db); pgMatrixViewer.setDatabase(db); pgMatrixViewerString = pgMatrixViewer.render(); loadLitterMatrixViewer(db); litterMatrixViewer.setDatabase(db); litterMatrixViewerString = litterMatrixViewer.render(); this.action = "init"; } if (action.equals("switchParentgroups")) { this.entity = "Parentgroups"; this.action = "init"; } if (action.equals("switchLitters")) { this.entity = "Litters"; this.action = "init"; } if (action.equals("deActivate")) { List<?> rows = pgMatrixViewer.getSelection(db); String pgName; try { int row = request.getInt(PGMATRIX + "_selected"); pgName = ((ObservationElement) rows.get(row)).getName(); } catch (Exception e) { this.action = "init"; throw new Exception("No parentgroup selected"); } ObservedValue activeVal = db.query(ObservedValue.class). eq(ObservedValue.TARGET_NAME, pgName). eq(ObservedValue.FEATURE_NAME, "Active"). find().get(0); if (activeVal.getValue().equals("Active")) { activeVal.setValue("Inactive"); } else { activeVal.setValue("Active"); } db.update(activeVal); // Reset matrix and return to main screen loadPgMatrixViewer(db); pgMatrixViewer.setDatabase(db); pgMatrixViewerString = pgMatrixViewer.render(); this.action = "init"; this.entity = "Parentgroups"; } if (action.equals("deActivateLitter")) { List<?> rows = litterMatrixViewer.getSelection(db); String litterName; try { int row = request.getInt(LITTERMATRIX + "_selected"); litterName = ((ObservationElement) rows.get(row)).getName(); } catch (Exception e) { this.action = "init"; throw new Exception("No litter selected"); } ObservedValue activeVal = db.query(ObservedValue.class). eq(ObservedValue.TARGET_NAME, litterName). eq(ObservedValue.FEATURE_NAME, "Active"). find().get(0); if (activeVal.getValue().equals("Active")) { activeVal.setValue("Inactive"); } else { activeVal.setValue("Active"); } db.update(activeVal); // Reset matrix and return to main screen loadLitterMatrixViewer(db); litterMatrixViewer.setDatabase(db); litterMatrixViewerString = litterMatrixViewer.render(); this.action = "init"; this.entity = "Litters"; } if (action.equals("createLitter")) { this.entity = "Litters"; // switch to litter view // Get selected parentgroup from PARENTGROUP matrix List<?> rows = pgMatrixViewer.getSelection(db); try { int row = request.getInt(PGMATRIX + "_selected"); this.selectedParentgroup = ((ObservationElement) rows.get(row)).getName(); } catch (Exception e) { this.action = "init"; throw new Exception("No parentgroup selected"); } } if (action.equals("addLitter")) { String newLitterName = ApplyAddLitter(db, request); // Reload litter matrix and set filter on name of newly added litter loadLitterMatrixViewer(db); litterMatrixViewer.setDatabase(db); litterMatrixViewer.getMatrix().getRules().add(new MatrixQueryRule(MatrixQueryRule.Type.rowHeader, Individual.NAME, Operator.EQUALS, newLitterName)); litterMatrixViewer.reloadMatrix(db, null); litterMatrixViewerString = litterMatrixViewer.render(); // Reset other fields this.birthdate = null; this.litterSize = 0; this.litterRemarks = null; // Return to start screen for litters this.action = "init"; this.entity = "Litters"; this.setSuccess("Litter " + newLitterName + " successfully added; adding filter to matrix: name = " + newLitterName); } if (action.equals("WeanLitter")) { stillToWeanYN = true; // Get selected litter List<?> rows = litterMatrixViewer.getSelection(db); try { int row = request.getInt(LITTERMATRIX + "_selected"); this.litter = ((ObservationElement) rows.get(row)).getName(); } catch (Exception e) { this.action = "init"; this.entity = "Litters"; throw new Exception("No litter selected"); } if(isWeaned(db)){ stillToWeanYN = false; this.setMessages(new ScreenMessage("Already weaned", false)); action="addLitter"; } else{ weanLitter(db); } } if (action.equals("GenotypeLitter")) { // Prepare parent info stillToGenotypeYN = true; List<?> rows = litterMatrixViewer.getSelection(db); try { int row = request.getInt(LITTERMATRIX + "_selected"); this.litter = ((ObservationElement) rows.get(row)).getName(); } catch (Exception e) { this.action = "init"; this.entity = "Litters"; throw new Exception("No litter selected"); } if(!isWeaned(db)){ this.setMessages(new ScreenMessage("The litter is not weaned yet!", false)); action="addLitter"; } else{ if(isGenotyped(db)){ stillToGenotypeYN = false; this.setMessages(new ScreenMessage("Already genotyped", false)); action="addLitter"; } else{ String parentgroupName = ct.getMostRecentValueAsXrefName(this.litter, "Parentgroup"); parentInfo = ""; parentInfo += ("Parentgroup: " + parentgroupName + "<br />"); parentInfo += ("Line: " + getLineInfo(parentgroupName) + "<br />"); String motherName = findParentForParentgroup(parentgroupName, "Mother", db); parentInfo += ("Mother: " + getGenoInfo(motherName, db) + "<br />"); String fatherName = findParentForParentgroup(parentgroupName, "Father", db); parentInfo += ("Father: " + getGenoInfo(fatherName, db) + "<br />"); genotypeLitter(db); } } } if (action.equals("applyWean")) { int weanSize = Wean(db, request); // Update custom label map now new animals have been added ct.makeObservationTargetNameMap(this.getLogin().getUserName(), true); // Reset all values this.wean = false; this.weandate = null; this.weanSizeFemale = 0; this.weanSizeMale = 0; this.weanSizeUnknown = 0; this.remarks = null; this.respres = null; this.selectedParentgroup = null; this.locName = null; // Reload litter matrix and set filter on name of newly weaned litter loadLitterMatrixViewer(db); litterMatrixViewer.setDatabase(db); litterMatrixViewer.getMatrix().getRules().add(new MatrixQueryRule(MatrixQueryRule.Type.rowHeader, Individual.NAME, Operator.EQUALS, this.litter)); litterMatrixViewer.reloadMatrix(db, null); litterMatrixViewerString = litterMatrixViewer.render(); this.action = "init"; this.entity = "Litters"; this.setSuccess("All " + weanSize + " animals successfully weaned; adding filter to matrix: name = " + this.litter); } if (action.equals("applyGenotype")) { int animalCount = Genotype(db, request); // Reload litter matrix and set filter on name of newly weaned litter loadLitterMatrixViewer(db); litterMatrixViewer.setDatabase(db); litterMatrixViewer.getMatrix().getRules().add(new MatrixQueryRule(MatrixQueryRule.Type.rowHeader, Individual.NAME, Operator.EQUALS, this.litter)); litterMatrixViewer.reloadMatrix(db, null); litterMatrixViewerString = litterMatrixViewer.render(); // Reset other fields this.action = "init"; this.entity = "Litters"; this.setSuccess("All " + animalCount + " animals successfully genotyped; adding filter to matrix: name = " + this.litter); } if (action.equals("makeLabels")) { // Get selected litter List<?> rows = litterMatrixViewer.getSelection(db); try { int row = request.getInt(LITTERMATRIX + "_selected"); this.litter = ((ObservationElement) rows.get(row)).getName(); } catch (Exception e) { this.action = "init"; this.entity = "Litters"; throw new Exception("No litter selected"); } if (ct.getMostRecentValueAsString(this.litter, "WeanDate") == null) { this.action = "init"; this.entity = "Litters"; throw new Exception("Cannot make labels for an unweaned litter"); } else if (ct.getMostRecentValueAsString(this.litter, "GenotypeDate") == null) { makeTempCageLabels(db); } else { makeDefCageLabels(db); } } if (action.equals("AddGenoCol")) { storeGenotypeTable(db, request); AddGenoCol(db, request); this.action = "GenotypeLitter"; this.setSuccess("Gene modification + state pair successfully added"); } if (action.equals("RemGenoCol")) { if (nrOfGenotypes > 1) { int currCol = 5 + ((nrOfGenotypes - 1) * 2); genotypeTable.removeColumn(currCol); // NB: nr. of cols is now 1 lower! genotypeTable.removeColumn(currCol); nrOfGenotypes--; this.setSuccess("Gene modification + state pair successfully removed"); } else { this.setError("Cannot remove - at least one Gene modification + state pair has to remain"); } storeGenotypeTable(db, request); this.action = "GenotypeLitter"; } } catch (Exception e) { String message = "Something went wrong"; if (e.getMessage() != null) { message += ": " + e.getMessage(); } this.setError(message); e.printStackTrace(); } }
public void handleRequest(Database db, Tuple request) { ct.setDatabase(db); action = request.getString("__action"); try { if (motherMatrixViewer != null && action.startsWith(motherMatrixViewer.getName())) { motherMatrixViewer.setDatabase(db); motherMatrixViewer.handleRequest(db, request); motherMatrixViewerString = motherMatrixViewer.render(); this.action = "selectParents"; // return to mother selection screen return; } if (fatherMatrixViewer != null && action.startsWith(fatherMatrixViewer.getName())) { fatherMatrixViewer.setDatabase(db); fatherMatrixViewer.handleRequest(db, request); fatherMatrixViewerString = fatherMatrixViewer.render(); this.action = "addParentgroupScreen3"; // return to father selection screen //this.action = "selectParents"; return; } if (pgMatrixViewer != null && action.startsWith(pgMatrixViewer.getName())) { pgMatrixViewer.setDatabase(db); pgMatrixViewer.handleRequest(db, request); pgMatrixViewerString = pgMatrixViewer.render(); this.action = "init"; // return to start screen this.entity = "Parentgroups"; return; } if (litterMatrixViewer != null && action.startsWith(litterMatrixViewer.getName())) { litterMatrixViewer.setDatabase(db); litterMatrixViewer.handleRequest(db, request); litterMatrixViewerString = litterMatrixViewer.render(); this.action = "init"; // return to start screen this.entity = "Litters"; return; } if (action.equals("init")) { // do nothing here } if (action.equals("selectParents")) { hashFathers.clear(); hashMothers.clear(); List<String> lis = new ArrayList<String>(); lis.add(""); numberOfPG = request.getInt("numberPG"); if(numberOfPG == null) { numberOfPG = -1; } for(int i = 0; i < numberOfPG; i++){ hashMothers.put(i, lis); hashFathers.put(i, lis); pgName.add(i+""); } } if(pgName.size()!=0){ for(int i= 0; i < pgName.size(); i++){ if(action.equals("selectParentsM"+(i))){ List<String> selectedFatherNameList = new ArrayList<String>(); @SuppressWarnings("unchecked") List<ObservationElement> rows = (List<ObservationElement>) motherMatrixViewer.getSelection(db); int rowCnt = 0; sex = "not selected"; for (ObservationElement row : rows) { if (request.getBool(MOTHERMATRIX + "_selected_" + rowCnt) != null) { String fatherName = row.getName(); sex = ct.getMostRecentValueAsXrefName(fatherName, "Sex"); if(sex.equals("Male")){ if (!selectedFatherNameList.contains(fatherName)) { selectedFatherNameList.add(fatherName); } }else{ this.setMessages(new ScreenMessage("Not a Male", false)); } } rowCnt++; } hashFathers.put(i, selectedFatherNameList); } if(action.equals("selectParentsF"+(i))){ List<String> selectedMotherNameList = new ArrayList<String>(); @SuppressWarnings("unchecked") List<ObservationElement> rows = (List<ObservationElement>) motherMatrixViewer.getSelection(db); int rowCnt = 0; sex = "not selected"; for (ObservationElement row : rows) { if (request.getBool(MOTHERMATRIX + "_selected_" + rowCnt) != null) { String motherName = row.getName(); sex = ct.getMostRecentValueAsXrefName(motherName, "Sex"); if(sex.equals("Female")){ if (!selectedMotherNameList.contains(motherName)) { selectedMotherNameList.add(motherName); } } else{ this.setMessages(new ScreenMessage("Not a Female", false)); } } rowCnt++; } hashMothers.put(i, selectedMotherNameList); } } } try{ if(action.equals("init")){ hashFathers.clear(); hashMothers.clear(); numberOfPG = null; } if(action.equals("JensonButton")){ boolean papa = false; boolean mama = false; List<String> pgNames = new ArrayList<String>(); for(Entry<Integer,List<String>> entry : hashFathers.entrySet()){ for(String s : entry.getValue()){ if(s.isEmpty()){ papa = true; } } } for(Entry<Integer,List<String>> entry : hashMothers.entrySet()){ for(String s : entry.getValue()){ if(s.isEmpty()){ mama = true; } } } if(papa == false || mama == false){ for(Entry <Integer,List<String>> entry: hashFathers.entrySet()){ String x = ""; String y = ""; if(request.getDate("startdate"+entry.getKey())!=null){ x = request.getString("startdate"+entry.getKey()); } if(request.getString("remarks"+entry.getKey())!=null){ y = request.getString("remarks"+entry.getKey()); } pgNames.add(AddParentgroup2(db, request,entry.getValue(),hashMothers.get(entry.getKey()),x,y)); // Reset matrix and add filter on name of newly added PG: loadPgMatrixViewer(db); pgMatrixViewer.setDatabase(db); //pgMatrixViewer.getMatrix().getRules().add(new MatrixQueryRule(MatrixQueryRule.Type.rowHeader, //Individual.NAME, Operator.EQUALS, pgNames)); pgMatrixViewer.reloadMatrix(db, null); pgMatrixViewerString = pgMatrixViewer.render(); // Reset other fields this.action = "init"; this.startdate = newDateOnlyFormat.format(new Date()); this.remarks = null; motherMatrixViewer = null; this.setSuccess("Parentgroup " + pgNames + " successfully added; adding filter to matrix: name = " + pgNames); } hashFathers.clear(); hashMothers.clear(); numberOfPG = null; } else{ this.setMessages(new ScreenMessage("Not all fathers or mothers are filled in", false)); action = "selectParents"; } } } catch(Exception e){ //this.setMessages(new ScreenMessage("Not all fathers or mothers are filled in", false)); } if (action.equals("createParentgroup")) { numberOfPG = -1; loadMotherMatrixViewer(db); motherMatrixViewer.setDatabase(db); motherMatrixViewerString = motherMatrixViewer.render(); } if (action.equals("changeLine")) { this.line = request.getString("line"); this.setSuccess("Breeding line changed to " + this.line); // Reset matrices and return to main screen loadPgMatrixViewer(db); pgMatrixViewer.setDatabase(db); pgMatrixViewerString = pgMatrixViewer.render(); loadLitterMatrixViewer(db); litterMatrixViewer.setDatabase(db); litterMatrixViewerString = litterMatrixViewer.render(); this.action = "init"; } if (action.equals("switchParentgroups")) { this.entity = "Parentgroups"; this.action = "init"; } if (action.equals("switchLitters")) { this.entity = "Litters"; this.action = "init"; } if (action.equals("deActivate")) { List<?> rows = pgMatrixViewer.getSelection(db); String pgName; try { int row = request.getInt(PGMATRIX + "_selected"); pgName = ((ObservationElement) rows.get(row)).getName(); } catch (Exception e) { this.action = "init"; throw new Exception("No parentgroup selected"); } ObservedValue activeVal = db.query(ObservedValue.class). eq(ObservedValue.TARGET_NAME, pgName). eq(ObservedValue.FEATURE_NAME, "Active"). find().get(0); if (activeVal.getValue().equals("Active")) { activeVal.setValue("Inactive"); } else { activeVal.setValue("Active"); } db.update(activeVal); // Reset matrix and return to main screen loadPgMatrixViewer(db); pgMatrixViewer.setDatabase(db); pgMatrixViewerString = pgMatrixViewer.render(); this.action = "init"; this.entity = "Parentgroups"; } if (action.equals("deActivateLitter")) { List<?> rows = litterMatrixViewer.getSelection(db); String litterName; try { int row = request.getInt(LITTERMATRIX + "_selected"); litterName = ((ObservationElement) rows.get(row)).getName(); } catch (Exception e) { this.action = "init"; throw new Exception("No litter selected"); } ObservedValue activeVal = db.query(ObservedValue.class). eq(ObservedValue.TARGET_NAME, litterName). eq(ObservedValue.FEATURE_NAME, "Active"). find().get(0); if (activeVal.getValue().equals("Active")) { activeVal.setValue("Inactive"); } else { activeVal.setValue("Active"); } db.update(activeVal); // Reset matrix and return to main screen loadLitterMatrixViewer(db); litterMatrixViewer.setDatabase(db); litterMatrixViewerString = litterMatrixViewer.render(); this.action = "init"; this.entity = "Litters"; } if (action.equals("createLitter")) { this.entity = "Litters"; // switch to litter view // Get selected parentgroup from PARENTGROUP matrix List<?> rows = pgMatrixViewer.getSelection(db); try { int row = request.getInt(PGMATRIX + "_selected"); this.selectedParentgroup = ((ObservationElement) rows.get(row)).getName(); } catch (Exception e) { this.action = "init"; throw new Exception("No parentgroup selected"); } } if (action.equals("addLitter")) { String newLitterName = ApplyAddLitter(db, request); // Reload litter matrix and set filter on name of newly added litter loadLitterMatrixViewer(db); litterMatrixViewer.setDatabase(db); litterMatrixViewer.getMatrix().getRules().add(new MatrixQueryRule(MatrixQueryRule.Type.rowHeader, Individual.NAME, Operator.EQUALS, newLitterName)); litterMatrixViewer.reloadMatrix(db, null); litterMatrixViewerString = litterMatrixViewer.render(); // Reset other fields this.birthdate = null; this.litterSize = 0; this.litterRemarks = null; // Return to start screen for litters this.action = "init"; this.entity = "Litters"; this.setSuccess("Litter " + newLitterName + " successfully added; adding filter to matrix: name = " + newLitterName); } if (action.equals("WeanLitter")) { stillToWeanYN = true; // Get selected litter List<?> rows = litterMatrixViewer.getSelection(db); try { int row = request.getInt(LITTERMATRIX + "_selected"); this.litter = ((ObservationElement) rows.get(row)).getName(); } catch (Exception e) { this.action = "init"; this.entity = "Litters"; throw new Exception("No litter selected"); } if(isWeaned(db)){ stillToWeanYN = false; this.setMessages(new ScreenMessage("Already weaned", false)); action="addLitter"; } else{ weanLitter(db); } } if (action.equals("GenotypeLitter")) { // Prepare parent info stillToGenotypeYN = true; List<?> rows = litterMatrixViewer.getSelection(db); try { int row = request.getInt(LITTERMATRIX + "_selected"); this.litter = ((ObservationElement) rows.get(row)).getName(); } catch (Exception e) { this.action = "init"; this.entity = "Litters"; throw new Exception("No litter selected"); } if(!isWeaned(db)){ this.setMessages(new ScreenMessage("The litter is not weaned yet!", false)); action="addLitter"; } else{ if(isGenotyped(db)){ stillToGenotypeYN = false; this.setMessages(new ScreenMessage("Already genotyped", false)); action="addLitter"; } else{ String parentgroupName = ct.getMostRecentValueAsXrefName(this.litter, "Parentgroup"); parentInfo = ""; parentInfo += ("Parentgroup: " + parentgroupName + "<br />"); parentInfo += ("Line: " + getLineInfo(parentgroupName) + "<br />"); String motherName = findParentForParentgroup(parentgroupName, "Mother", db); parentInfo += ("Mother: " + getGenoInfo(motherName, db) + "<br />"); String fatherName = findParentForParentgroup(parentgroupName, "Father", db); parentInfo += ("Father: " + getGenoInfo(fatherName, db) + "<br />"); genotypeLitter(db); } } } if (action.equals("applyWean")) { int weanSize = Wean(db, request); // Update custom label map now new animals have been added ct.makeObservationTargetNameMap(this.getLogin().getUserName(), true); // Reset all values this.wean = false; this.weandate = null; this.weanSizeFemale = 0; this.weanSizeMale = 0; this.weanSizeUnknown = 0; this.remarks = null; this.respres = null; this.selectedParentgroup = null; this.locName = null; // Reload litter matrix and set filter on name of newly weaned litter loadLitterMatrixViewer(db); litterMatrixViewer.setDatabase(db); litterMatrixViewer.getMatrix().getRules().add(new MatrixQueryRule(MatrixQueryRule.Type.rowHeader, Individual.NAME, Operator.EQUALS, this.litter)); litterMatrixViewer.reloadMatrix(db, null); litterMatrixViewerString = litterMatrixViewer.render(); this.action = "init"; this.entity = "Litters"; this.setSuccess("All " + weanSize + " animals successfully weaned; adding filter to matrix: name = " + this.litter); } if (action.equals("applyGenotype")) { int animalCount = Genotype(db, request); // Reload litter matrix and set filter on name of newly weaned litter loadLitterMatrixViewer(db); litterMatrixViewer.setDatabase(db); litterMatrixViewer.getMatrix().getRules().add(new MatrixQueryRule(MatrixQueryRule.Type.rowHeader, Individual.NAME, Operator.EQUALS, this.litter)); litterMatrixViewer.reloadMatrix(db, null); litterMatrixViewerString = litterMatrixViewer.render(); // Reset other fields this.action = "init"; this.entity = "Litters"; this.setSuccess("All " + animalCount + " animals successfully genotyped; adding filter to matrix: name = " + this.litter); } if (action.equals("makeLabels")) { // Get selected litter List<?> rows = litterMatrixViewer.getSelection(db); try { int row = request.getInt(LITTERMATRIX + "_selected"); this.litter = ((ObservationElement) rows.get(row)).getName(); } catch (Exception e) { this.action = "init"; this.entity = "Litters"; throw new Exception("No litter selected"); } if (ct.getMostRecentValueAsString(this.litter, "WeanDate") == null) { this.action = "init"; this.entity = "Litters"; throw new Exception("Cannot make labels for an unweaned litter"); } else if (ct.getMostRecentValueAsString(this.litter, "GenotypeDate") == null) { makeTempCageLabels(db); } else { makeDefCageLabels(db); } } if (action.equals("AddGenoCol")) { storeGenotypeTable(db, request); AddGenoCol(db, request); this.action = "GenotypeLitter"; this.setSuccess("Gene modification + state pair successfully added"); } if (action.equals("RemGenoCol")) { if (nrOfGenotypes > 1) { int currCol = 5 + ((nrOfGenotypes - 1) * 2); genotypeTable.removeColumn(currCol); // NB: nr. of cols is now 1 lower! genotypeTable.removeColumn(currCol); nrOfGenotypes--; this.setSuccess("Gene modification + state pair successfully removed"); } else { this.setError("Cannot remove - at least one Gene modification + state pair has to remain"); } storeGenotypeTable(db, request); this.action = "GenotypeLitter"; } } catch (Exception e) { String message = "Something went wrong"; if (e.getMessage() != null) { message += ": " + e.getMessage(); } this.setError(message); e.printStackTrace(); } }
diff --git a/library/org.beangle.model/src/main/java/org/beangle/model/comment/SqlCommentGenerator.java b/library/org.beangle.model/src/main/java/org/beangle/model/comment/SqlCommentGenerator.java index b4f2a35b..26e499cc 100644 --- a/library/org.beangle.model/src/main/java/org/beangle/model/comment/SqlCommentGenerator.java +++ b/library/org.beangle.model/src/main/java/org/beangle/model/comment/SqlCommentGenerator.java @@ -1,277 +1,277 @@ /* Copyright c 2005-2012. * Licensed under GNU LESSER General Public License, Version 3. * http://www.gnu.org/licenses */ package org.beangle.model.comment; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.net.URL; import java.util.Enumeration; import java.util.Set; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; import org.beangle.commons.collection.CollectUtils; import org.beangle.commons.lang.StrUtils; import org.beangle.commons.text.inflector.Pluralizer; import org.beangle.commons.text.inflector.lang.en.EnNounPluralizer; import org.beangle.model.persist.hibernate.support.DefaultTableNameConfig; import org.beangle.model.persist.hibernate.support.TableNameConfig; import com.sun.javadoc.AnnotationDesc; import com.sun.javadoc.ClassDoc; import com.sun.javadoc.DocErrorReporter; import com.sun.javadoc.FieldDoc; import com.sun.javadoc.RootDoc; /** * 扫描@Entity头和字段的注释,生成sql语句 * * @author chaostone * @version $Id: ListTags.java Jul 30, 2011 12:42:54 AM chaostone $ */ public class SqlCommentGenerator { private static final String CONFIG = "config"; private static final String SQLFILE = "file"; private static DefaultTableNameConfig tableNameConfig; public static boolean start(RootDoc root) throws IOException { ClassDoc[] classes = root.classes(); NamingStrategy strategy = new NamingStrategy(); strategy.setTableNameConfig(tableNameConfig); // out files String commentFileName = getFileOption(root.options()); String commentLogFileName = System.getProperty("java.io.tmpdir") + "/comment_log.txt"; BufferedWriter out = new BufferedWriter(new FileWriter(commentFileName)); BufferedWriter log = new BufferedWriter(new FileWriter(commentLogFileName)); // reserved types Set<String> multiTypes = CollectUtils.newHashSet("Set", "Map", "List"); Set<String> scalaTypes = CollectUtils.newHashSet("String", "Integer", "int", "Long", "long", "Float", "float", "Double", "double", "Date", "DateTime", "Calendar", "BigDecimal", "Boolean", "boolean"); // nocomment int nocomment = 0; StringBuilder nocomments = new StringBuilder(); for (int i = 0; i < classes.length; i++) { if (!isEntity(classes[i])) continue; ClassDoc classDoc = classes[i]; // generate table name - strategy.generatePrefix(classDoc.name()); + strategy.generatePrefix(classDoc.qualifiedName()); String tableName = getTableName(classDoc); if (null != tableName) { tableName = strategy.tableName(tableName); } else { - tableName = strategy.classToTableName(classDoc.name()); + tableName = strategy.classToTableName(classDoc.qualifiedName()); } // find table comment String tableComment = processComment(classDoc.commentText()); if (null != tableComment) { out.write("\ncomment on table " + tableName + " is '" + tableComment + "';\n"); } else { - nocomments.append(classDoc.name()).append('\n'); + nocomments.append(classDoc.qualifiedName()).append('\n'); nocomment++; } // process classDoc and it's superClassDoc while (null != classDoc) { if (classDoc.simpleTypeName().equals("Object")) break; FieldDoc[] fields = classDoc.fields(false); for (int j = 0; j < fields.length; j++) { FieldDoc field = fields[j]; if (field.isTransient() || field.isStatic() || field.isEnum()) continue; String simpleTypeName = field.type().simpleTypeName(); if (multiTypes.contains(simpleTypeName)) continue; String columnComment = processComment(fields[j].commentText()); if (null != columnComment) { String columnName = StrUtils.unCamel(fields[j].name(), '_', true); if (!scalaTypes.contains(simpleTypeName)) { columnName = columnName + "_id"; columnComment = columnComment + "ID"; } out.write("comment on column " + tableName + "." + columnName + " is '" + columnComment + "';\n"); } else { if (null != fields[j].position() && fields[j].position().column() > 0) { - nocomments.append(classDoc.name()).append('.').append(fields[j].name()) + nocomments.append(classDoc.qualifiedName()).append('.').append(fields[j].name()) .append('\n'); nocomment++; } } } classDoc = (null == classDoc.superclassType()) ? null : classDoc.superclassType() .asClassDoc(); } } // summary if (nocomment > 0) log.write("Find " + nocomment + " properties without comment.\n"); else log.write("Congratulations! All entity properties have valid comment.\n"); log.write(nocomments.toString()); // cleanup out.close(); log.close(); System.out.println("Generated comment sqlfile:" + commentFileName); System.out.println("Generated comment logfile:" + commentLogFileName); return true; } private static String processComment(String comment) { if (StringUtils.isEmpty(comment)) return null; int newlineIndex = comment.indexOf('\n'); if (newlineIndex > 0) { comment = comment.substring(0, newlineIndex); } return comment.trim(); } private static boolean isEntity(ClassDoc classDoc) { AnnotationDesc[] anns = classDoc.annotations(); if (null == anns || anns.length == 0) return false; for (AnnotationDesc anno : anns) { if ("Entity".equals(anno.annotationType().name())) return true; } return false; } private static String getTableName(ClassDoc classDoc) { AnnotationDesc[] anns = classDoc.annotations(); if (null == anns || anns.length == 0) return null; for (AnnotationDesc anno : anns) { if ("Table".equals(anno.annotationType().name())) { AnnotationDesc.ElementValuePair[] pairs = anno.elementValues(); if (null != pairs && pairs.length > 0) { for (AnnotationDesc.ElementValuePair pair : pairs) { if (pair.element().name().equals("name")) return pair.value().value().toString(); } } } } return null; } /** * Doclet method called by Javadoc to recognize * custom parameters. */ public static int optionLength(String option) { if (option.equals("-" + CONFIG)) return 2; if (option.equals("-" + SQLFILE)) return 2; else return 0; } public static boolean validOptions(String options[][], DocErrorReporter reporter) throws IOException { System.out.println("start valid options..."); tableNameConfig = new DefaultTableNameConfig(); for (int i = 0; i < options.length; i++) { String[] opt = options[i]; if (opt[0].equals("-file")) { FileUtils.touch(new File(opt[1])); } else if (opt[0].equals("-config")) { String fileName = opt[1]; if (null == fileName) continue; File file = new File(fileName); if (!file.exists()) { reporter.printError("config file [" + fileName + "] not exists."); return false; } else { ((DefaultTableNameConfig) tableNameConfig).addConfig(file.toURI().toURL()); } } } Enumeration<URL> urls = Thread.currentThread().getContextClassLoader() .getResources("/META-INF/beangle/table.properties"); while (urls.hasMoreElements()) { tableNameConfig.addConfig(urls.nextElement()); } if (tableNameConfig.getPatterns().isEmpty()) { reporter.printError("Cannot find table.properties in classpath or options. Using -config your/path/to/table.properties"); return false; } else { System.out.println(tableNameConfig); return true; } } private static String getFileOption(String[][] options) { String tagName = null; for (int i = 0; i < options.length; i++) { String[] opt = options[i]; if (opt[0].equals("-file")) { tagName = opt[1]; } } if (null == tagName) tagName = System.getProperty("java.io.tmpdir") + "/comment.sql"; return tagName; } } class NamingStrategy { private Pluralizer pluralizer = new EnNounPluralizer(); private TableNameConfig tableNameConfig; private String tblPrefix; public String classToTableName(String className) { if (className.endsWith("Bean")) { className = StringUtils.substringBeforeLast(className, "Bean"); } String tableName = addUnderscores(unqualify(className)); if (null != pluralizer) { tableName = pluralizer.pluralize(tableName); } if (null != tblPrefix) { tableName = tblPrefix + tableName; } return tableName; } public void generatePrefix(String className) { tblPrefix = tableNameConfig.getPrefix(className); } public String tableName(String tableName) { String newName = tableName; if (null != tblPrefix) { if (!tableName.startsWith(tblPrefix)) { newName = tblPrefix + tableName; } } return newName; } public void setPluralizer(Pluralizer pluralizer) { this.pluralizer = pluralizer; } public void setTableNameConfig(TableNameConfig tableNameConfig) { this.tableNameConfig = tableNameConfig; } protected static String addUnderscores(String name) { return StrUtils.unCamel(name.replace('.', '_'), '_'); } protected static String unqualify(String qualifiedName) { int loc = qualifiedName.lastIndexOf('.'); return (loc < 0) ? qualifiedName : qualifiedName.substring(loc + 1); } }
false
true
public static boolean start(RootDoc root) throws IOException { ClassDoc[] classes = root.classes(); NamingStrategy strategy = new NamingStrategy(); strategy.setTableNameConfig(tableNameConfig); // out files String commentFileName = getFileOption(root.options()); String commentLogFileName = System.getProperty("java.io.tmpdir") + "/comment_log.txt"; BufferedWriter out = new BufferedWriter(new FileWriter(commentFileName)); BufferedWriter log = new BufferedWriter(new FileWriter(commentLogFileName)); // reserved types Set<String> multiTypes = CollectUtils.newHashSet("Set", "Map", "List"); Set<String> scalaTypes = CollectUtils.newHashSet("String", "Integer", "int", "Long", "long", "Float", "float", "Double", "double", "Date", "DateTime", "Calendar", "BigDecimal", "Boolean", "boolean"); // nocomment int nocomment = 0; StringBuilder nocomments = new StringBuilder(); for (int i = 0; i < classes.length; i++) { if (!isEntity(classes[i])) continue; ClassDoc classDoc = classes[i]; // generate table name strategy.generatePrefix(classDoc.name()); String tableName = getTableName(classDoc); if (null != tableName) { tableName = strategy.tableName(tableName); } else { tableName = strategy.classToTableName(classDoc.name()); } // find table comment String tableComment = processComment(classDoc.commentText()); if (null != tableComment) { out.write("\ncomment on table " + tableName + " is '" + tableComment + "';\n"); } else { nocomments.append(classDoc.name()).append('\n'); nocomment++; } // process classDoc and it's superClassDoc while (null != classDoc) { if (classDoc.simpleTypeName().equals("Object")) break; FieldDoc[] fields = classDoc.fields(false); for (int j = 0; j < fields.length; j++) { FieldDoc field = fields[j]; if (field.isTransient() || field.isStatic() || field.isEnum()) continue; String simpleTypeName = field.type().simpleTypeName(); if (multiTypes.contains(simpleTypeName)) continue; String columnComment = processComment(fields[j].commentText()); if (null != columnComment) { String columnName = StrUtils.unCamel(fields[j].name(), '_', true); if (!scalaTypes.contains(simpleTypeName)) { columnName = columnName + "_id"; columnComment = columnComment + "ID"; } out.write("comment on column " + tableName + "." + columnName + " is '" + columnComment + "';\n"); } else { if (null != fields[j].position() && fields[j].position().column() > 0) { nocomments.append(classDoc.name()).append('.').append(fields[j].name()) .append('\n'); nocomment++; } } } classDoc = (null == classDoc.superclassType()) ? null : classDoc.superclassType() .asClassDoc(); } } // summary if (nocomment > 0) log.write("Find " + nocomment + " properties without comment.\n"); else log.write("Congratulations! All entity properties have valid comment.\n"); log.write(nocomments.toString()); // cleanup out.close(); log.close(); System.out.println("Generated comment sqlfile:" + commentFileName); System.out.println("Generated comment logfile:" + commentLogFileName); return true; }
public static boolean start(RootDoc root) throws IOException { ClassDoc[] classes = root.classes(); NamingStrategy strategy = new NamingStrategy(); strategy.setTableNameConfig(tableNameConfig); // out files String commentFileName = getFileOption(root.options()); String commentLogFileName = System.getProperty("java.io.tmpdir") + "/comment_log.txt"; BufferedWriter out = new BufferedWriter(new FileWriter(commentFileName)); BufferedWriter log = new BufferedWriter(new FileWriter(commentLogFileName)); // reserved types Set<String> multiTypes = CollectUtils.newHashSet("Set", "Map", "List"); Set<String> scalaTypes = CollectUtils.newHashSet("String", "Integer", "int", "Long", "long", "Float", "float", "Double", "double", "Date", "DateTime", "Calendar", "BigDecimal", "Boolean", "boolean"); // nocomment int nocomment = 0; StringBuilder nocomments = new StringBuilder(); for (int i = 0; i < classes.length; i++) { if (!isEntity(classes[i])) continue; ClassDoc classDoc = classes[i]; // generate table name strategy.generatePrefix(classDoc.qualifiedName()); String tableName = getTableName(classDoc); if (null != tableName) { tableName = strategy.tableName(tableName); } else { tableName = strategy.classToTableName(classDoc.qualifiedName()); } // find table comment String tableComment = processComment(classDoc.commentText()); if (null != tableComment) { out.write("\ncomment on table " + tableName + " is '" + tableComment + "';\n"); } else { nocomments.append(classDoc.qualifiedName()).append('\n'); nocomment++; } // process classDoc and it's superClassDoc while (null != classDoc) { if (classDoc.simpleTypeName().equals("Object")) break; FieldDoc[] fields = classDoc.fields(false); for (int j = 0; j < fields.length; j++) { FieldDoc field = fields[j]; if (field.isTransient() || field.isStatic() || field.isEnum()) continue; String simpleTypeName = field.type().simpleTypeName(); if (multiTypes.contains(simpleTypeName)) continue; String columnComment = processComment(fields[j].commentText()); if (null != columnComment) { String columnName = StrUtils.unCamel(fields[j].name(), '_', true); if (!scalaTypes.contains(simpleTypeName)) { columnName = columnName + "_id"; columnComment = columnComment + "ID"; } out.write("comment on column " + tableName + "." + columnName + " is '" + columnComment + "';\n"); } else { if (null != fields[j].position() && fields[j].position().column() > 0) { nocomments.append(classDoc.qualifiedName()).append('.').append(fields[j].name()) .append('\n'); nocomment++; } } } classDoc = (null == classDoc.superclassType()) ? null : classDoc.superclassType() .asClassDoc(); } } // summary if (nocomment > 0) log.write("Find " + nocomment + " properties without comment.\n"); else log.write("Congratulations! All entity properties have valid comment.\n"); log.write(nocomments.toString()); // cleanup out.close(); log.close(); System.out.println("Generated comment sqlfile:" + commentFileName); System.out.println("Generated comment logfile:" + commentLogFileName); return true; }
diff --git a/src/main/java/gr/forth/ics/icardea/pid/PIXQueryHandler.java b/src/main/java/gr/forth/ics/icardea/pid/PIXQueryHandler.java index a82aeec..ef42f15 100644 --- a/src/main/java/gr/forth/ics/icardea/pid/PIXQueryHandler.java +++ b/src/main/java/gr/forth/ics/icardea/pid/PIXQueryHandler.java @@ -1,191 +1,193 @@ package gr.forth.ics.icardea.pid; import gr.forth.ics.icardea.mllp.HL7MLLPServer; import java.util.HashSet; import org.apache.log4j.Logger; import ca.uhn.hl7v2.HL7Exception; import ca.uhn.hl7v2.app.Application; import ca.uhn.hl7v2.app.ApplicationException; import ca.uhn.hl7v2.model.Message; import ca.uhn.hl7v2.model.Type; import ca.uhn.hl7v2.model.v25.message.QBP_Q21; import ca.uhn.hl7v2.model.v25.message.RSP_K23; import ca.uhn.hl7v2.model.v25.segment.QPD; import ca.uhn.hl7v2.util.Terser; /** * PIX Query: ITI-9 (ITI TF-2a / 3.9) * * This transaction involves a request by the Patient Identifier Cross-reference * Consumer Actor for a list of patient identifiers that correspond to a patient * identifier known by the consumer. The request is received by the Patient * Identifier Cross-reference Manager. The Patient Identifier Cross-reference * Manager immediately processes the request and returns a response in the form * of a list of corresponding patient identifiers, if any. * * The Request for Corresponding Patient Identifiers transaction is conducted by * the HL7 QBP^Q23 message. Responds with RSP_K23 * */ final class PIXQueryHandler implements Application { static Logger logger = Logger.getLogger(PIXQueryHandler.class); final static int QIP_FLD_NUM = 3; public void register(HL7MLLPServer s) { s.registerApplication("QBP", "Q23", this); } /* * What we expect is QBP_Q23 v2.5 message but this is implemented through * QBP_Q21 according to * hapi-structures-v25-1.0.1-sources.jar/ca/uhn/hl7v2/parser/eventmap/2.5.properties */ public boolean canProcess(Message msg) { return msg instanceof QBP_Q21; } /** * See ITI-vol2a, 3.9 */ public Message processMessage(Message msg) throws ApplicationException{ try { logger.debug("Received:"+msg.encode()); } catch (HL7Exception e) { } QBP_Q21 m = (QBP_Q21) msg; QPD qpd = m.getQPD(); String qt = qpd.getQpd2_QueryTag().getValue(); RSP_K23 resp = new RSP_K23(); try { String reqMsgCtrlId = m.getMSH().getMessageControlID().getValue(); // String reqRcvApp = m.getMSH().getReceivingApplication().encode(); String reqSndApp = m.getMSH().getSendingApplication().encode(); HL7Utils.fillResponseHeader(m.getMSH(), resp.getMSH()); resp.getMSH().getMsh9_MessageType().parse("RSP^K23^RSP_K23"); // resp.getMSH().getSendingApplication().parse(reqRcvApp); resp.getMSH().getReceivingApplication().parse(reqSndApp); resp.getMSA().getMessageControlID().setValue(reqMsgCtrlId); AssigningAuthority fromAuth = null; String id = Terser.get(qpd, 3, 0, 1, 1); String ns = Terser.get(qpd, 3, 0, 4, 1); if (ns == null || "".equals(ns)) { String uid = Terser.get(qpd, 3, 0, 4, 2); - String uid_type = Terser.get(qpd, 3, 0, 4, 2); + String uid_type = Terser.get(qpd, 3, 0, 4, 3); + // System.out.println("GOT uid='"+uid+"' type='"+uid_type+"'"); fromAuth = AssigningAuthority.find_by_uid(uid, uid_type); + ns = fromAuth.namespace; } else fromAuth = AssigningAuthority.find(ns); if (fromAuth == null) { HL7Exception ex = new HL7Exception("Unsupported authority:"+qpd.getField(3, 0).encode(), HL7Exception.UNKNOWN_KEY_IDENTIFIER); ex.setSegmentName("QPD"); ex.setSegmentRepetition(1); ex.setFieldPosition(3); throw ex; } iCARDEA_Patient.ID fromId = new iCARDEA_Patient.ID(ns, id); HashSet<String> hs = new HashSet<String>(); Type[] tt = qpd.getField(4); for (Type t: tt) { AssigningAuthority auth = null; String tons = Terser.getPrimitive(t, 4, 1).getValue(); if (tons == null || "".equals(tons)) { String uid = Terser.getPrimitive(t, 4, 2).getValue(); String uid_type = Terser.getPrimitive(t, 4, 3).getValue(); auth = AssigningAuthority.find_by_uid(uid, uid_type); } else { auth = AssigningAuthority.find(tons); } if (auth == null) { HL7Exception ex = new HL7Exception("Unsupported authority:"+t.encode(), HL7Exception.UNKNOWN_KEY_IDENTIFIER); ex.setSegmentName("QPD"); ex.setSegmentRepetition(1); ex.setFieldPosition(4); throw ex; } hs.add(auth.namespace); } String[] toNS = new String[0]; toNS = hs.toArray(toNS); iCARDEA_Patient p = StorageManager.getInstance().retrieve(fromId, toNS); resp.getQAK().getQak1_QueryTag().setValue(qt); resp.getQAK().getQak2_QueryResponseStatus().setValue("OK"); resp.getQPD().parse(qpd.encode()); if (p != null) { // We need to remove namespaces that were not requested // unless no namespace was requested where we return all for (java.util.ListIterator<iCARDEA_Patient.ID> it = p.ids.listIterator(); !hs.isEmpty() && it.hasNext();) { iCARDEA_Patient.ID n = it.next(); if (!hs.contains(n.namespace)) it.remove(); } ca.uhn.hl7v2.model.v25.segment.PID pid = resp.getQUERY_RESPONSE().getPID(); p.toPidv25(pid, true); /* * "To eliminate the issue of conflicting name values between * Patient Identifier Domains, the Patient Identifier * Cross-reference Manager Actor shall return in an empty (not * present) value in the first repetition of field PID-5-Patient * Name, and shall return a second repetition of field * PID-5-Patient Name in which the only populated component is * Component 7 (Name Type Code). Component 7 of repetition 2 * shall contain a value of S (Coded Pseudo-name to assure * anonymity). All other components of repetition 2 shall be * empty (not present)." */ pid.getPid5_PatientName(0).parse(""); pid.getPid5_PatientName(1).parse("^^^^^^S"); } else resp.getQAK().getQak2_QueryResponseStatus().setValue("NF"); resp.getMSA().getAcknowledgmentCode().setValue("AA"); } catch (HL7Exception e) { e.printStackTrace(); try { resp.getMSA().getMsa1_AcknowledgmentCode().setValue("AE"); // resp.getMSA().getTextMessage().setValue(e.getMessage()); HL7Utils.fillErrHeader(resp, e); resp.getQAK().getQak1_QueryTag().setValue(qt); resp.getQAK().getQak2_QueryResponseStatus().setValue("AE"); resp.getQPD().parse(qpd.encode()); } catch (HL7Exception ex) { ex.printStackTrace(); throw new ApplicationException(ex.getMessage(), ex); } } catch (Exception e) { e.printStackTrace(); try { resp.getMSA().getAcknowledgmentCode().setValue("AR"); resp.getMSA().getTextMessage().setValue(e.getMessage()); resp.getERR().getErr3_HL7ErrorCode().getCwe1_Identifier().setValue(""+HL7Exception.APPLICATION_INTERNAL_ERROR); resp.getERR().getErr3_HL7ErrorCode().getCwe2_Text().setValue(e.getMessage()); resp.getQAK().getQak1_QueryTag().setValue(qt); resp.getQAK().getQak2_QueryResponseStatus().setValue("AR"); resp.getQPD().parse(qpd.encode()); } catch (HL7Exception ex) { ex.printStackTrace(); throw new ApplicationException(ex.getMessage(), ex); } } try { logger.debug("Sending:"+resp.encode()); } catch (HL7Exception e) { } return resp; } }
false
true
public Message processMessage(Message msg) throws ApplicationException{ try { logger.debug("Received:"+msg.encode()); } catch (HL7Exception e) { } QBP_Q21 m = (QBP_Q21) msg; QPD qpd = m.getQPD(); String qt = qpd.getQpd2_QueryTag().getValue(); RSP_K23 resp = new RSP_K23(); try { String reqMsgCtrlId = m.getMSH().getMessageControlID().getValue(); // String reqRcvApp = m.getMSH().getReceivingApplication().encode(); String reqSndApp = m.getMSH().getSendingApplication().encode(); HL7Utils.fillResponseHeader(m.getMSH(), resp.getMSH()); resp.getMSH().getMsh9_MessageType().parse("RSP^K23^RSP_K23"); // resp.getMSH().getSendingApplication().parse(reqRcvApp); resp.getMSH().getReceivingApplication().parse(reqSndApp); resp.getMSA().getMessageControlID().setValue(reqMsgCtrlId); AssigningAuthority fromAuth = null; String id = Terser.get(qpd, 3, 0, 1, 1); String ns = Terser.get(qpd, 3, 0, 4, 1); if (ns == null || "".equals(ns)) { String uid = Terser.get(qpd, 3, 0, 4, 2); String uid_type = Terser.get(qpd, 3, 0, 4, 2); fromAuth = AssigningAuthority.find_by_uid(uid, uid_type); } else fromAuth = AssigningAuthority.find(ns); if (fromAuth == null) { HL7Exception ex = new HL7Exception("Unsupported authority:"+qpd.getField(3, 0).encode(), HL7Exception.UNKNOWN_KEY_IDENTIFIER); ex.setSegmentName("QPD"); ex.setSegmentRepetition(1); ex.setFieldPosition(3); throw ex; } iCARDEA_Patient.ID fromId = new iCARDEA_Patient.ID(ns, id); HashSet<String> hs = new HashSet<String>(); Type[] tt = qpd.getField(4); for (Type t: tt) { AssigningAuthority auth = null; String tons = Terser.getPrimitive(t, 4, 1).getValue(); if (tons == null || "".equals(tons)) { String uid = Terser.getPrimitive(t, 4, 2).getValue(); String uid_type = Terser.getPrimitive(t, 4, 3).getValue(); auth = AssigningAuthority.find_by_uid(uid, uid_type); } else { auth = AssigningAuthority.find(tons); } if (auth == null) { HL7Exception ex = new HL7Exception("Unsupported authority:"+t.encode(), HL7Exception.UNKNOWN_KEY_IDENTIFIER); ex.setSegmentName("QPD"); ex.setSegmentRepetition(1); ex.setFieldPosition(4); throw ex; } hs.add(auth.namespace); } String[] toNS = new String[0]; toNS = hs.toArray(toNS); iCARDEA_Patient p = StorageManager.getInstance().retrieve(fromId, toNS); resp.getQAK().getQak1_QueryTag().setValue(qt); resp.getQAK().getQak2_QueryResponseStatus().setValue("OK"); resp.getQPD().parse(qpd.encode()); if (p != null) { // We need to remove namespaces that were not requested // unless no namespace was requested where we return all for (java.util.ListIterator<iCARDEA_Patient.ID> it = p.ids.listIterator(); !hs.isEmpty() && it.hasNext();) { iCARDEA_Patient.ID n = it.next(); if (!hs.contains(n.namespace)) it.remove(); } ca.uhn.hl7v2.model.v25.segment.PID pid = resp.getQUERY_RESPONSE().getPID(); p.toPidv25(pid, true); /* * "To eliminate the issue of conflicting name values between * Patient Identifier Domains, the Patient Identifier * Cross-reference Manager Actor shall return in an empty (not * present) value in the first repetition of field PID-5-Patient * Name, and shall return a second repetition of field * PID-5-Patient Name in which the only populated component is * Component 7 (Name Type Code). Component 7 of repetition 2 * shall contain a value of S (Coded Pseudo-name to assure * anonymity). All other components of repetition 2 shall be * empty (not present)." */ pid.getPid5_PatientName(0).parse(""); pid.getPid5_PatientName(1).parse("^^^^^^S"); } else resp.getQAK().getQak2_QueryResponseStatus().setValue("NF"); resp.getMSA().getAcknowledgmentCode().setValue("AA"); } catch (HL7Exception e) { e.printStackTrace(); try { resp.getMSA().getMsa1_AcknowledgmentCode().setValue("AE"); // resp.getMSA().getTextMessage().setValue(e.getMessage()); HL7Utils.fillErrHeader(resp, e); resp.getQAK().getQak1_QueryTag().setValue(qt); resp.getQAK().getQak2_QueryResponseStatus().setValue("AE"); resp.getQPD().parse(qpd.encode()); } catch (HL7Exception ex) { ex.printStackTrace(); throw new ApplicationException(ex.getMessage(), ex); } } catch (Exception e) { e.printStackTrace(); try { resp.getMSA().getAcknowledgmentCode().setValue("AR"); resp.getMSA().getTextMessage().setValue(e.getMessage()); resp.getERR().getErr3_HL7ErrorCode().getCwe1_Identifier().setValue(""+HL7Exception.APPLICATION_INTERNAL_ERROR); resp.getERR().getErr3_HL7ErrorCode().getCwe2_Text().setValue(e.getMessage()); resp.getQAK().getQak1_QueryTag().setValue(qt); resp.getQAK().getQak2_QueryResponseStatus().setValue("AR"); resp.getQPD().parse(qpd.encode()); } catch (HL7Exception ex) { ex.printStackTrace(); throw new ApplicationException(ex.getMessage(), ex); } } try { logger.debug("Sending:"+resp.encode()); } catch (HL7Exception e) { } return resp; }
public Message processMessage(Message msg) throws ApplicationException{ try { logger.debug("Received:"+msg.encode()); } catch (HL7Exception e) { } QBP_Q21 m = (QBP_Q21) msg; QPD qpd = m.getQPD(); String qt = qpd.getQpd2_QueryTag().getValue(); RSP_K23 resp = new RSP_K23(); try { String reqMsgCtrlId = m.getMSH().getMessageControlID().getValue(); // String reqRcvApp = m.getMSH().getReceivingApplication().encode(); String reqSndApp = m.getMSH().getSendingApplication().encode(); HL7Utils.fillResponseHeader(m.getMSH(), resp.getMSH()); resp.getMSH().getMsh9_MessageType().parse("RSP^K23^RSP_K23"); // resp.getMSH().getSendingApplication().parse(reqRcvApp); resp.getMSH().getReceivingApplication().parse(reqSndApp); resp.getMSA().getMessageControlID().setValue(reqMsgCtrlId); AssigningAuthority fromAuth = null; String id = Terser.get(qpd, 3, 0, 1, 1); String ns = Terser.get(qpd, 3, 0, 4, 1); if (ns == null || "".equals(ns)) { String uid = Terser.get(qpd, 3, 0, 4, 2); String uid_type = Terser.get(qpd, 3, 0, 4, 3); // System.out.println("GOT uid='"+uid+"' type='"+uid_type+"'"); fromAuth = AssigningAuthority.find_by_uid(uid, uid_type); ns = fromAuth.namespace; } else fromAuth = AssigningAuthority.find(ns); if (fromAuth == null) { HL7Exception ex = new HL7Exception("Unsupported authority:"+qpd.getField(3, 0).encode(), HL7Exception.UNKNOWN_KEY_IDENTIFIER); ex.setSegmentName("QPD"); ex.setSegmentRepetition(1); ex.setFieldPosition(3); throw ex; } iCARDEA_Patient.ID fromId = new iCARDEA_Patient.ID(ns, id); HashSet<String> hs = new HashSet<String>(); Type[] tt = qpd.getField(4); for (Type t: tt) { AssigningAuthority auth = null; String tons = Terser.getPrimitive(t, 4, 1).getValue(); if (tons == null || "".equals(tons)) { String uid = Terser.getPrimitive(t, 4, 2).getValue(); String uid_type = Terser.getPrimitive(t, 4, 3).getValue(); auth = AssigningAuthority.find_by_uid(uid, uid_type); } else { auth = AssigningAuthority.find(tons); } if (auth == null) { HL7Exception ex = new HL7Exception("Unsupported authority:"+t.encode(), HL7Exception.UNKNOWN_KEY_IDENTIFIER); ex.setSegmentName("QPD"); ex.setSegmentRepetition(1); ex.setFieldPosition(4); throw ex; } hs.add(auth.namespace); } String[] toNS = new String[0]; toNS = hs.toArray(toNS); iCARDEA_Patient p = StorageManager.getInstance().retrieve(fromId, toNS); resp.getQAK().getQak1_QueryTag().setValue(qt); resp.getQAK().getQak2_QueryResponseStatus().setValue("OK"); resp.getQPD().parse(qpd.encode()); if (p != null) { // We need to remove namespaces that were not requested // unless no namespace was requested where we return all for (java.util.ListIterator<iCARDEA_Patient.ID> it = p.ids.listIterator(); !hs.isEmpty() && it.hasNext();) { iCARDEA_Patient.ID n = it.next(); if (!hs.contains(n.namespace)) it.remove(); } ca.uhn.hl7v2.model.v25.segment.PID pid = resp.getQUERY_RESPONSE().getPID(); p.toPidv25(pid, true); /* * "To eliminate the issue of conflicting name values between * Patient Identifier Domains, the Patient Identifier * Cross-reference Manager Actor shall return in an empty (not * present) value in the first repetition of field PID-5-Patient * Name, and shall return a second repetition of field * PID-5-Patient Name in which the only populated component is * Component 7 (Name Type Code). Component 7 of repetition 2 * shall contain a value of S (Coded Pseudo-name to assure * anonymity). All other components of repetition 2 shall be * empty (not present)." */ pid.getPid5_PatientName(0).parse(""); pid.getPid5_PatientName(1).parse("^^^^^^S"); } else resp.getQAK().getQak2_QueryResponseStatus().setValue("NF"); resp.getMSA().getAcknowledgmentCode().setValue("AA"); } catch (HL7Exception e) { e.printStackTrace(); try { resp.getMSA().getMsa1_AcknowledgmentCode().setValue("AE"); // resp.getMSA().getTextMessage().setValue(e.getMessage()); HL7Utils.fillErrHeader(resp, e); resp.getQAK().getQak1_QueryTag().setValue(qt); resp.getQAK().getQak2_QueryResponseStatus().setValue("AE"); resp.getQPD().parse(qpd.encode()); } catch (HL7Exception ex) { ex.printStackTrace(); throw new ApplicationException(ex.getMessage(), ex); } } catch (Exception e) { e.printStackTrace(); try { resp.getMSA().getAcknowledgmentCode().setValue("AR"); resp.getMSA().getTextMessage().setValue(e.getMessage()); resp.getERR().getErr3_HL7ErrorCode().getCwe1_Identifier().setValue(""+HL7Exception.APPLICATION_INTERNAL_ERROR); resp.getERR().getErr3_HL7ErrorCode().getCwe2_Text().setValue(e.getMessage()); resp.getQAK().getQak1_QueryTag().setValue(qt); resp.getQAK().getQak2_QueryResponseStatus().setValue("AR"); resp.getQPD().parse(qpd.encode()); } catch (HL7Exception ex) { ex.printStackTrace(); throw new ApplicationException(ex.getMessage(), ex); } } try { logger.debug("Sending:"+resp.encode()); } catch (HL7Exception e) { } return resp; }
diff --git a/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglGL10.java b/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglGL10.java index bd06ee462..6852610a7 100644 --- a/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglGL10.java +++ b/gdx-backend-desktop/src/com/badlogic/gdx/backends/desktop/JoglGL10.java @@ -1,934 +1,934 @@ /******************************************************************************* * Copyright 2010 Mario Zechner ([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 com.badlogic.gdx.backends.desktop; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.IntBuffer; import com.badlogic.gdx.graphics.GL10; /** * An implementation of the {@link GL10} interface based on Jogl. Fixed point vertex * arrays are emulated. * * @author mzechner * */ class JoglGL10 implements GL10 { protected final javax.media.opengl.GL gl; protected final float FIXED_TO_FLOAT = 1 / 65536.0f; private final FloatBuffer colorBuffer; private final FloatBuffer normalBuffer; private final FloatBuffer vertexBuffer; private final FloatBuffer texCoordBuffer[] = new FloatBuffer[16]; private int activeTexture = 0; private float[] tmp = new float[1000]; public JoglGL10( javax.media.opengl.GL gl ) { this.gl = gl; - ByteBuffer buffer = ByteBuffer.allocateDirect( 200000 * 4 * 4 ); + ByteBuffer buffer = ByteBuffer.allocateDirect( 20000 * 4 * 4 ); buffer.order(ByteOrder.nativeOrder()); colorBuffer = buffer.asFloatBuffer(); - buffer = ByteBuffer.allocateDirect( 200000 * 4 * 3 ); + buffer = ByteBuffer.allocateDirect( 20000 * 4 * 3 ); buffer.order(ByteOrder.nativeOrder()); normalBuffer = buffer.asFloatBuffer(); - buffer = ByteBuffer.allocateDirect( 200000 * 4 * 4 ); + buffer = ByteBuffer.allocateDirect( 20000 * 4 * 4 ); buffer.order(ByteOrder.nativeOrder()); vertexBuffer = buffer.asFloatBuffer(); for( int i = 0; i < texCoordBuffer.length; i++ ) { - buffer = ByteBuffer.allocateDirect( 200000 * 4 * 4 ); + buffer = ByteBuffer.allocateDirect( 20000 * 4 * 4 ); buffer.order(ByteOrder.nativeOrder()); texCoordBuffer[i] = buffer.asFloatBuffer(); } } protected final void convertFixedToFloatbuffer( Buffer source, FloatBuffer target, int stride ) { if( source instanceof IntBuffer || source instanceof ByteBuffer ) { IntBuffer buffer = source instanceof ByteBuffer?((ByteBuffer)source).asIntBuffer():(IntBuffer)source; if( stride % 4 != 0 ) throw new IllegalArgumentException( "Can't cope with strides % 4 != 0 for IntBuffers" ); target.clear(); for( int i = buffer.position(); i < buffer.limit(); i++ ) { float value = FIXED_TO_FLOAT * buffer.get(i); target.put( value ); } target.flip(); } else { throw new IllegalArgumentException( "Can't cope with buffer of type " + source.getClass().getName() + ", only ByteBuffers and IntBuffers supported" ); } } @Override public final void glActiveTexture(int texture) { gl.glActiveTexture( texture ); } @Override public final void glAlphaFunc(int func, float ref) { gl.glAlphaFunc( func, ref ); } @Override public final void glAlphaFuncx(int func, int ref) { gl.glAlphaFunc( func, FIXED_TO_FLOAT * ref ); } @Override public final void glBindTexture(int target, int texture) { gl.glBindTexture( target, texture ); } @Override public final void glBlendFunc(int sfactor, int dfactor) { gl.glBlendFunc( sfactor, dfactor ); } @Override public final void glClear(int mask) { gl.glClear( mask ); } @Override public final void glClearColor(float red, float green, float blue, float alpha) { gl.glClearColor( red, green, blue, alpha ); } @Override public final void glClearColorx(int red, int green, int blue, int alpha) { gl.glClearColor( FIXED_TO_FLOAT * red, FIXED_TO_FLOAT * green, FIXED_TO_FLOAT * blue, FIXED_TO_FLOAT * alpha ); } @Override public final void glClearDepthf(float depth) { gl.glClearDepth( depth ); } @Override public final void glClearDepthx(int depth) { gl.glClearDepth( FIXED_TO_FLOAT * depth ); } @Override public final void glClearStencil(int s) { gl.glClearStencil( s ); } @Override public final void glClientActiveTexture(int texture) { activeTexture = texture - GL10.GL_TEXTURE0; gl.glClientActiveTexture( texture ); } @Override public final void glColor4f(float red, float green, float blue, float alpha) { gl.glColor4f( red, green, blue, alpha ); } @Override public final void glColor4x(int red, int green, int blue, int alpha) { gl.glColor4f( FIXED_TO_FLOAT * red, FIXED_TO_FLOAT * green, FIXED_TO_FLOAT * blue, FIXED_TO_FLOAT * alpha ); } @Override public final void glColorMask(boolean red, boolean green, boolean blue, boolean alpha) { gl.glColorMask( red, green, blue, alpha ); } @Override public final void glColorPointer(int size, int type, int stride, Buffer pointer) { if( type == GL10.GL_FIXED ) { convertFixedToFloatbuffer(pointer,colorBuffer, stride); gl.glColorPointer( size, GL10.GL_FLOAT, stride, colorBuffer ); } else { gl.glColorPointer( size, type, stride, pointer ); } } @Override public final void glCompressedTexImage2D(int target, int level, int internalformat, int width, int height, int border, int imageSize, Buffer data) { gl.glCompressedTexImage2D( target, level, internalformat, width, height, border, imageSize, data ); } @Override public final void glCompressedTexSubImage2D(int target, int level, int xoffset, int yoffset, int width, int height, int format, int imageSize, Buffer data) { gl.glCompressedTexSubImage2D( target, level, xoffset, yoffset, width, height, format, imageSize, data ); } @Override public final void glCopyTexImage2D(int target, int level, int internalformat, int x, int y, int width, int height, int border) { gl.glCopyTexImage2D( target, level, internalformat, x, y, width, height, border ); } @Override public final void glCopyTexSubImage2D(int target, int level, int xoffset, int yoffset, int x, int y, int width, int height) { gl.glCopyTexSubImage2D( target, level, xoffset, yoffset, x, y, width, height ); } @Override public final void glCullFace(int mode) { gl.glCullFace( mode ); } @Override public final void glDeleteTextures(int n, IntBuffer textures) { gl.glDeleteTextures( n, textures ); } @Override public final void glDepthFunc(int func) { gl.glDepthFunc( func ); } @Override public final void glDepthMask(boolean flag) { gl.glDepthMask( flag ); } @Override public final void glDepthRangef(float zNear, float zFar) { gl.glDepthRange( zNear, zFar ); } @Override public final void glDepthRangex(int zNear, int zFar) { gl.glDepthRange( FIXED_TO_FLOAT * zNear, FIXED_TO_FLOAT * zFar ); } @Override public final void glDisable(int cap) { gl.glDisable( cap ); } @Override public final void glDisableClientState(int array) { gl.glDisableClientState( array ); } @Override public final void glDrawArrays(int mode, int first, int count) { gl.glDrawArrays( mode, first, count ); } @Override public final void glDrawElements(int mode, int count, int type, Buffer indices) { // nothing to do here per documentation gl.glDrawElements( mode, count, type, indices ); } @Override public final void glEnable(int cap) { gl.glEnable( cap ); } @Override public final void glEnableClientState(int array) { gl.glEnableClientState( array ); } @Override public final void glFinish() { gl.glFinish(); } @Override public final void glFlush() { gl.glFlush(); } @Override public final void glFogf(int pname, float param) { gl.glFogf( pname, param ); } @Override public final void glFogfv(int pname, FloatBuffer params) { gl.glFogfv( pname, params ); } @Override public final void glFogx(int pname, int param) { gl.glFogf( pname, FIXED_TO_FLOAT * param ); } @Override public final void glFogxv(int pname, IntBuffer params) { if( tmp.length < params.capacity() ) tmp = new float[params.capacity()]; int i = 0; while( params.hasRemaining() ) tmp[i++] = FIXED_TO_FLOAT * params.get(); gl.glFogfv(pname, tmp, 0 ); } @Override public final void glFrontFace(int mode) { gl.glFrontFace( mode ); } @Override public final void glFrustumf(float left, float right, float bottom, float top, float zNear, float zFar) { gl.glFrustum( left, right, bottom, top, zNear, zFar ); } @Override public final void glFrustumx(int left, int right, int bottom, int top, int zNear, int zFar) { gl.glFrustum( FIXED_TO_FLOAT * left, FIXED_TO_FLOAT * right, FIXED_TO_FLOAT * bottom, FIXED_TO_FLOAT * top, FIXED_TO_FLOAT * zNear, FIXED_TO_FLOAT * zFar ); } @Override public final void glGenTextures(int n, IntBuffer textures) { gl.glGenTextures( n, textures ); } @Override public final int glGetError() { return gl.glGetError(); } @Override public final void glGetIntegerv(int pname, IntBuffer params) { gl.glGetIntegerv( pname, params ); } @Override public final String glGetString(int name) { return gl.glGetString( name ); } @Override public final void glHint(int target, int mode) { gl.glHint( target, mode ); } @Override public final void glLightModelf(int pname, float param) { gl.glLightModelf( pname, param ); } @Override public final void glLightModelfv(int pname, FloatBuffer params) { gl.glLightModelfv( pname, params ); } @Override public final void glLightModelx(int pname, int param) { gl.glLightModelf( pname, FIXED_TO_FLOAT * param ); } @Override public final void glLightModelxv(int pname, IntBuffer params) { int i = 0; while( params.hasRemaining() ) tmp[i++] = FIXED_TO_FLOAT * params.get(); gl.glLightModelfv( pname, tmp, 0 ); } @Override public final void glLightf(int light, int pname, float param) { gl.glLightf( light, pname, param ); } @Override public final void glLightfv(int light, int pname, FloatBuffer params) { gl.glLightfv( light, pname, params ); } @Override public final void glLightx(int light, int pname, int param) { gl.glLightf( light, pname, FIXED_TO_FLOAT * param ); } @Override public final void glLightxv(int light, int pname, IntBuffer params) { if( tmp.length < params.capacity() ) tmp = new float[params.capacity()]; int i = 0; while( params.hasRemaining() ) tmp[i++] = FIXED_TO_FLOAT * params.get(); gl.glLightfv( light, pname, tmp, 0 ); } @Override public final void glLineWidth(float width) { gl.glLineWidth( width ); } @Override public final void glLineWidthx(int width) { gl.glLineWidth( FIXED_TO_FLOAT * width ); } @Override public final void glLoadIdentity() { gl.glLoadIdentity(); } @Override public final void glLoadMatrixf(FloatBuffer m) { gl.glLoadMatrixf( m ); } @Override public final void glLoadMatrixx(IntBuffer m) { if( tmp.length < m.capacity() ) tmp = new float[m.capacity()]; int i = 0; while( m.hasRemaining() ) tmp[i++] = FIXED_TO_FLOAT * m.get(); gl.glLoadMatrixf( tmp, 0 ); } @Override public final void glLogicOp(int opcode) { gl.glLogicOp( opcode ); } @Override public final void glMaterialf(int face, int pname, float param) { gl.glMaterialf( face, pname, param ); } @Override public final void glMaterialfv(int face, int pname, FloatBuffer params) { gl.glMaterialfv( face, pname, params ); } @Override public final void glMaterialx(int face, int pname, int param) { gl.glMaterialf( face, pname, FIXED_TO_FLOAT * param ); } @Override public final void glMaterialxv(int face, int pname, IntBuffer params) { if( tmp.length < params.capacity() ) tmp = new float[params.capacity()]; int i = 0; while( params.hasRemaining() ) tmp[i++] = FIXED_TO_FLOAT * params.get(); gl.glMaterialfv( face, pname, tmp, 0 ); } @Override public final void glMatrixMode(int mode) { gl.glMatrixMode( mode ); } @Override public final void glMultMatrixf(FloatBuffer m) { gl.glMultMatrixf( m ); } @Override public final void glMultMatrixx(IntBuffer m) { if( tmp.length < m.capacity() ) tmp = new float[m.capacity()]; int i = 0; while( m.hasRemaining() ) tmp[i++] = FIXED_TO_FLOAT * m.get(); gl.glMultMatrixf( tmp, 0 ); } @Override public final void glMultiTexCoord4f(int target, float s, float t, float r, float q) { gl.glMultiTexCoord4f( target, s, t, r, q ); } @Override public final void glMultiTexCoord4x(int target, int s, int t, int r, int q) { gl.glMultiTexCoord4f( target, FIXED_TO_FLOAT * s, FIXED_TO_FLOAT * t, FIXED_TO_FLOAT * r, FIXED_TO_FLOAT * q ); } @Override public final void glNormal3f(float nx, float ny, float nz) { gl.glNormal3f( nx, ny, nz ); } @Override public final void glNormal3x(int nx, int ny, int nz) { gl.glNormal3f( FIXED_TO_FLOAT * nx, FIXED_TO_FLOAT * ny, FIXED_TO_FLOAT * nz ); } @Override public final void glNormalPointer(int type, int stride, Buffer pointer) { if( type == GL10.GL_FIXED ) { convertFixedToFloatbuffer(pointer,normalBuffer, stride); gl.glNormalPointer( GL10.GL_FLOAT, stride, normalBuffer ); } else { gl.glNormalPointer( type, stride, pointer ); } } @Override public final void glOrthof(float left, float right, float bottom, float top, float zNear, float zFar) { gl.glOrtho( left, right, bottom, top, zNear, zFar ); } @Override public final void glOrthox(int left, int right, int bottom, int top, int zNear, int zFar) { gl.glOrtho( FIXED_TO_FLOAT * left, FIXED_TO_FLOAT * right, FIXED_TO_FLOAT * bottom, FIXED_TO_FLOAT * top, FIXED_TO_FLOAT * zNear, FIXED_TO_FLOAT * zFar ); } @Override public final void glPixelStorei(int pname, int param) { gl.glPixelStorei( pname, param ); } @Override public final void glPointSize(float size) { gl.glPointSize( size ); } @Override public final void glPointSizex(int size) { gl.glPointSize( FIXED_TO_FLOAT * size ); } @Override public final void glPolygonOffset(float factor, float units) { gl.glPolygonOffset( factor, units ); } @Override public final void glPolygonOffsetx(int factor, int units) { gl.glPolygonOffset( FIXED_TO_FLOAT * factor, FIXED_TO_FLOAT * units ); } @Override public final void glPopMatrix() { gl.glPopMatrix(); } @Override public final void glPushMatrix() { gl.glPushMatrix(); } @Override public final void glReadPixels(int x, int y, int width, int height, int format, int type, Buffer pixels) { gl.glReadPixels( x, y, width, height, format, type, pixels ); } @Override public final void glRotatef(float angle, float x, float y, float z) { gl.glRotatef( angle, x, y, z ); } @Override public final void glRotatex(int angle, int x, int y, int z) { gl.glRotatef( FIXED_TO_FLOAT * angle, FIXED_TO_FLOAT * x, FIXED_TO_FLOAT * y, FIXED_TO_FLOAT * z ); } @Override public final void glSampleCoverage(float value, boolean invert) { gl.glSampleCoverage( value, invert ); } @Override public final void glSampleCoveragex(int value, boolean invert) { gl.glSampleCoverage( FIXED_TO_FLOAT * value, invert ); } @Override public final void glScalef(float x, float y, float z) { gl.glScalef( x, y, z ); } @Override public final void glScalex(int x, int y, int z) { gl.glScalef( FIXED_TO_FLOAT * x, FIXED_TO_FLOAT * y, FIXED_TO_FLOAT * z ); } @Override public final void glScissor(int x, int y, int width, int height) { gl.glScissor( x, y, width, height ); } @Override public final void glShadeModel(int mode) { gl.glShadeModel(mode); } @Override public final void glStencilFunc(int func, int ref, int mask) { gl.glStencilFunc( func, ref, mask ); } @Override public final void glStencilMask(int mask) { gl.glStencilMask( mask ); } @Override public final void glStencilOp(int fail, int zfail, int zpass) { gl.glStencilOp( fail, zfail, zpass ); } @Override public final void glTexCoordPointer(int size, int type, int stride, Buffer pointer) { if( type == GL10.GL_FIXED ) { convertFixedToFloatbuffer(pointer,texCoordBuffer[activeTexture], stride); gl.glTexCoordPointer( size, GL10.GL_FLOAT, stride, texCoordBuffer[activeTexture] ); } else gl.glTexCoordPointer( size, type, stride, pointer ); } @Override public final void glTexEnvf(int target, int pname, float param) { gl.glTexEnvf( target, pname, param ); } @Override public final void glTexEnvfv(int target, int pname, FloatBuffer params) { gl.glTexEnvfv( target, pname, params ); } @Override public final void glTexEnvx(int target, int pname, int param) { gl.glTexEnvf( target, pname, FIXED_TO_FLOAT * param ); } @Override public final void glTexEnvxv(int target, int pname, IntBuffer params) { if( tmp.length < params.capacity() ) tmp = new float[params.capacity()]; int i = 0; while( params.hasRemaining() ) tmp[i++] = FIXED_TO_FLOAT * params.get(); gl.glTexEnvfv( target, pname, tmp, 0 ); } @Override public final void glTexImage2D(int target, int level, int internalformat, int width, int height, int border, int format, int type, Buffer pixels) { gl.glTexImage2D( target, level, internalformat, width, height, border, format, type, pixels ); } @Override public final void glTexParameterf(int target, int pname, float param) { gl.glTexParameterf( target, pname, param ); } @Override public final void glTexParameterx(int target, int pname, int param) { gl.glTexParameterf( target, pname, FIXED_TO_FLOAT * param ); } @Override public final void glTexSubImage2D(int target, int level, int xoffset, int yoffset, int width, int height, int format, int type, Buffer pixels) { gl.glTexSubImage2D( target, level, xoffset, yoffset, width, height, format, type, pixels ); } @Override public final void glTranslatef(float x, float y, float z) { gl.glTranslatef( x, y, z ); } @Override public final void glTranslatex(int x, int y, int z) { gl.glTranslatef( FIXED_TO_FLOAT * x, FIXED_TO_FLOAT * y, FIXED_TO_FLOAT * z ); } @Override public final void glVertexPointer(int size, int type, int stride, Buffer pointer) { if( type == GL10.GL_FIXED ) { convertFixedToFloatbuffer(pointer,vertexBuffer, stride); gl.glVertexPointer( size, GL10.GL_FLOAT, stride, vertexBuffer ); } else gl.glVertexPointer( size, GL10.GL_FLOAT, stride, pointer ); } @Override public final void glViewport(int x, int y, int width, int height) { gl.glViewport( x, y, width, height ); } @Override public final void glDeleteTextures(int n, int[] textures, int offset) { gl.glDeleteTextures( n, textures, offset ); } @Override public final void glFogfv(int pname, float[] params, int offset) { gl.glFogfv( pname, params, offset ); } @Override public final void glFogxv(int pname, int[] params, int offset) { if( params.length > tmp.length ) tmp = new float[params.length]; for( int i = 0; i + offset< params.length; i++ ) tmp[i] = FIXED_TO_FLOAT * params[i + offset]; gl.glFogfv( pname, tmp, 0 ); } @Override public final void glGenTextures(int n, int[] textures, int offset) { gl.glGenTextures( n, textures, offset ); } @Override public final void glGetIntegerv(int pname, int[] params, int offset) { gl.glGetIntegerv( pname, params, offset ); } @Override public final void glLightModelfv(int pname, float[] params, int offset) { gl.glLightModelfv( pname, params, offset ); } @Override public final void glLightModelxv(int pname, int[] params, int offset) { if( params.length > tmp.length ) tmp = new float[params.length]; for( int i = 0; i + offset< params.length; i++ ) tmp[i] = FIXED_TO_FLOAT * params[i + offset]; gl.glLightModelfv( pname, tmp, 0 ); } @Override public final void glLightfv(int light, int pname, float[] params, int offset) { gl.glLightfv( light, pname, params, offset ); } @Override public final void glLightxv(int light, int pname, int[] params, int offset) { if( params.length > tmp.length ) tmp = new float[params.length]; for( int i = 0; i + offset < params.length; i++ ) tmp[i] = FIXED_TO_FLOAT * params[i + offset]; gl.glLightfv( light, pname, tmp, 0 ); } @Override public final void glLoadMatrixf(float[] m, int offset) { gl.glLoadMatrixf( m, offset ); } @Override public final void glLoadMatrixx(int[] m, int offset) { if( m.length > tmp.length ) tmp = new float[m.length]; for( int i = 0; i + offset< m.length; i++ ) tmp[i] = FIXED_TO_FLOAT * m[i + offset]; gl.glLoadMatrixf( tmp, 0 ); } @Override public final void glMaterialfv(int face, int pname, float[] params, int offset) { gl.glMaterialfv( face, pname, params, offset ); } @Override public final void glMaterialxv(int face, int pname, int[] params, int offset) { if( params.length > tmp.length ) tmp = new float[params.length]; for( int i = 0; i + offset < params.length; i++ ) tmp[i] = FIXED_TO_FLOAT * params[i + offset]; gl.glMaterialfv( face, pname, tmp, 0 ); } @Override public final void glMultMatrixf(float[] m, int offset) { gl.glMultMatrixf( m, offset ); } @Override public final void glMultMatrixx(int[] m, int offset) { if( m.length > tmp.length ) tmp = new float[m.length]; for( int i = 0; i + offset< m.length; i++ ) tmp[i] = FIXED_TO_FLOAT * m[i + offset]; gl.glMultMatrixf( tmp, 0 ); } @Override public final void glTexEnvfv(int target, int pname, float[] params, int offset) { gl.glTexEnvfv( target, pname, params, offset ); } @Override public final void glTexEnvxv(int target, int pname, int[] params, int offset) { if( params.length > tmp.length ) tmp = new float[params.length]; for( int i = 0; i + offset< params.length; i++ ) tmp[i] = FIXED_TO_FLOAT * params[i + offset]; gl.glTexEnvfv( target, pname, tmp, 0 ); } }
false
true
public JoglGL10( javax.media.opengl.GL gl ) { this.gl = gl; ByteBuffer buffer = ByteBuffer.allocateDirect( 200000 * 4 * 4 ); buffer.order(ByteOrder.nativeOrder()); colorBuffer = buffer.asFloatBuffer(); buffer = ByteBuffer.allocateDirect( 200000 * 4 * 3 ); buffer.order(ByteOrder.nativeOrder()); normalBuffer = buffer.asFloatBuffer(); buffer = ByteBuffer.allocateDirect( 200000 * 4 * 4 ); buffer.order(ByteOrder.nativeOrder()); vertexBuffer = buffer.asFloatBuffer(); for( int i = 0; i < texCoordBuffer.length; i++ ) { buffer = ByteBuffer.allocateDirect( 200000 * 4 * 4 ); buffer.order(ByteOrder.nativeOrder()); texCoordBuffer[i] = buffer.asFloatBuffer(); } }
public JoglGL10( javax.media.opengl.GL gl ) { this.gl = gl; ByteBuffer buffer = ByteBuffer.allocateDirect( 20000 * 4 * 4 ); buffer.order(ByteOrder.nativeOrder()); colorBuffer = buffer.asFloatBuffer(); buffer = ByteBuffer.allocateDirect( 20000 * 4 * 3 ); buffer.order(ByteOrder.nativeOrder()); normalBuffer = buffer.asFloatBuffer(); buffer = ByteBuffer.allocateDirect( 20000 * 4 * 4 ); buffer.order(ByteOrder.nativeOrder()); vertexBuffer = buffer.asFloatBuffer(); for( int i = 0; i < texCoordBuffer.length; i++ ) { buffer = ByteBuffer.allocateDirect( 20000 * 4 * 4 ); buffer.order(ByteOrder.nativeOrder()); texCoordBuffer[i] = buffer.asFloatBuffer(); } }
diff --git a/modules/VisualizationImpl/src/main/java/org/gephi/visualization/opengl/CompatibilityEngine.java b/modules/VisualizationImpl/src/main/java/org/gephi/visualization/opengl/CompatibilityEngine.java index eea387305..4dee54a80 100644 --- a/modules/VisualizationImpl/src/main/java/org/gephi/visualization/opengl/CompatibilityEngine.java +++ b/modules/VisualizationImpl/src/main/java/org/gephi/visualization/opengl/CompatibilityEngine.java @@ -1,754 +1,754 @@ /* Copyright 2008-2010 Gephi Authors : Mathieu Bastian <[email protected]> Website : http://www.gephi.org This file is part of Gephi. DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. Copyright 2011 Gephi Consortium. All rights reserved. The contents of this file are subject to the terms of either the GNU General Public License Version 3 only ("GPL") or the Common Development and Distribution License("CDDL") (collectively, the "License"). You may not use this file except in compliance with the License. You can obtain a copy of the License at http://gephi.org/about/legal/license-notice/ or /cddl-1.0.txt and /gpl-3.0.txt. See the License for the specific language governing permissions and limitations under the License. When distributing the software, include this License Header Notice in each file and include the License files at /cddl-1.0.txt and /gpl-3.0.txt. If applicable, add the following below the License Header, with the fields enclosed by brackets [] replaced by your own identifying information: "Portions Copyrighted [year] [name of copyright owner]" If you wish your version of this file to be governed by only the CDDL or only the GPL Version 3, indicate your decision by adding "[Contributor] elects to include this software in this distribution under the [CDDL or GPL Version 3] license." If you do not indicate a single choice of license, a recipient has the option to distribute your version of this file under either the CDDL, the GPL Version 3 or to extend the choice of license to its licensees as provided above. However, if you add GPL Version 3 code and therefore, elected the GPL Version 3 license, then the option applies only if the new code is made subject to such option by the copyright holder. Contributor(s): Portions Copyrighted 2011 Gephi Consortium. */ package org.gephi.visualization.opengl; import java.awt.Color; import java.nio.FloatBuffer; import java.util.Arrays; import java.util.Iterator; import javax.media.opengl.GL2; import javax.media.opengl.glu.GLU; import javax.media.opengl.glu.GLUquadric; import org.gephi.visualization.VizController; import org.gephi.visualization.VizModel; import org.gephi.visualization.api.initializer.Modeler; import org.gephi.visualization.apiimpl.Scheduler; import org.gephi.visualization.model.ModelClass; import org.gephi.visualization.model.edge.EdgeModel; import org.gephi.visualization.model.node.NodeModel; import org.gephi.visualization.model.node.NodeModeler; import org.gephi.visualization.octree.Octree; import org.gephi.visualization.scheduler.CompatibilityScheduler; import org.gephi.visualization.selection.Cylinder; import org.gephi.visualization.selection.Rectangle; /** * * @author Mathieu Bastian */ public class CompatibilityEngine extends AbstractEngine { private CompatibilityScheduler scheduler; private int markTime = 0; //Selection // private ConcurrentLinkedQueue<ModelImpl>[] selectedObjects; private boolean anySelected = false; public CompatibilityEngine() { super(); } @Override public void initArchitecture() { super.initArchitecture(); scheduler = (CompatibilityScheduler) VizController.getInstance().getScheduler(); vizEventManager = VizController.getInstance().getVizEventManager(); //Init octree = new Octree(vizConfig.getOctreeDepth(), vizConfig.getOctreeWidth()); octree.initArchitecture(); } public void updateSelection(GL2 gl, GLU glu) { if (vizConfig.isSelectionEnable() && currentSelectionArea != null && currentSelectionArea.isEnabled()) { float[] mp = Arrays.copyOf(graphIO.getMousePosition(), 2); float[] cent = currentSelectionArea.getSelectionAreaCenter(); if (cent != null) { mp[0] += cent[0]; mp[1] += cent[1]; } octree.updateSelectedOctant(gl, glu, mp, currentSelectionArea.getSelectionAreaRectancle()); } } @Override public boolean updateWorld() { boolean repositioned = octree.repositionNodes(); boolean updated = dataBridge.updateWorld(); return repositioned || updated; // boolean res = false; // boolean newConfig = configChanged; // if (newConfig) { // dataBridge.reset(); // if (!vizConfig.isCustomSelection()) { // //Reset model classes //// for (ModelClass objClass : getModelClasses()) { //// if (objClass.isEnabled()) { //// objClass.swapModelers(); //// resetObjectClass(objClass); //// } //// } // } // // initSelection(); // // } // if (dataBridge.requireUpdate() || newConfig) { // dataBridge.updateWorld(); // res = true; // } // if (newConfig) { // // configChanged = false; // } // return res; } @Override public void beforeDisplay(GL2 gl, GLU glu) { //Lighten delta if (lightenAnimationDelta != 0) { float factor = vizConfig.getLightenNonSelectedFactor(); factor += lightenAnimationDelta; if (factor >= 0.5f && factor <= 0.98f) { vizConfig.setLightenNonSelectedFactor(factor); } else { lightenAnimationDelta = 0; vizConfig.setLightenNonSelected(anySelected); } } if (backgroundChanged) { Color backgroundColor = vizController.getVizModel().getBackgroundColor(); gl.glClearColor(backgroundColor.getRed() / 255f, backgroundColor.getGreen() / 255f, backgroundColor.getBlue() / 255f, 1f); gl.glClear(GL2.GL_COLOR_BUFFER_BIT); backgroundChanged = false; } if (reinit) { VizController.getInstance().refreshWorkspace(); dataBridge.reset(); graphDrawable.initConfig(gl); graphDrawable.setCameraLocation(vizController.getVizModel().getCameraPosition()); graphDrawable.setCameraTarget(vizController.getVizModel().getCameraTarget()); vizConfig.setCustomSelection(false); reinit = false; } } @Override public void display(GL2 gl, GLU glu) { //Update viewport NodeModeler nodeModeler = (NodeModeler) nodeClass.getCurrentModeler(); for (Iterator<NodeModel> itr = octree.getNodeIterator(); itr.hasNext();) { //TODO Move this NodeModel obj = itr.next(); nodeModeler.setViewportPosition(obj); } markTime++; VizModel vizModel = VizController.getInstance().getVizModel(); //Edges if (edgeClass.isEnabled()) { edgeClass.beforeDisplay(gl, glu); for (Iterator<EdgeModel> itr = octree.getEdgeIterator(); itr.hasNext();) { EdgeModel obj = itr.next(); if (obj.markTime != markTime) { obj.display(gl, glu, vizModel); obj.markTime = markTime; } } edgeClass.afterDisplay(gl, glu); } markTime++; //Arrows - if (vizConfig.isShowArrows() && dataBridge.isDirected()) { + if (edgeClass.isEnabled() && vizConfig.isShowArrows() && dataBridge.isDirected()) { gl.glBegin(GL2.GL_TRIANGLES); for (Iterator<EdgeModel> itr = octree.getEdgeIterator(); itr.hasNext();) { EdgeModel obj = itr.next(); if (obj.getEdge().isDirected() && obj.markTime != markTime) { obj.displayArrow(gl, glu, vizModel); obj.markTime = markTime; } } gl.glEnd(); } //Nodes if (nodeClass.isEnabled()) { nodeClass.beforeDisplay(gl, glu); for (Iterator<NodeModel> itr = octree.getNodeIterator(); itr.hasNext();) { NodeModel obj = itr.next(); if (obj.markTime != markTime) { obj.display(gl, glu, vizModel); obj.markTime = markTime; } } nodeClass.afterDisplay(gl, glu); } //Labels if (vizModel.getTextModel().isShowNodeLabels() || vizModel.getTextModel().isShowEdgeLabels()) { markTime++; if (nodeClass.isEnabled() && vizModel.getTextModel().isShowNodeLabels()) { textManager.getNodeRenderer().beginRendering(); textManager.defaultNodeColor(); if (textManager.isSelectedOnly()) { for (Iterator<NodeModel> itr = octree.getNodeIterator(); itr.hasNext();) { NodeModel obj = itr.next(); if (obj.markTime != markTime) { if (obj.isSelected() && obj.isTextVisible()) { textManager.getNodeRenderer().drawTextNode(obj); } obj.markTime = markTime; } } } else { for (Iterator<NodeModel> itr = octree.getNodeIterator(); itr.hasNext();) { NodeModel obj = itr.next(); if (obj.markTime != markTime) { if (obj.isTextVisible()) { textManager.getNodeRenderer().drawTextNode(obj); } obj.markTime = markTime; } } } textManager.getNodeRenderer().endRendering(); } // if (edgeClass.isEnabled() && vizModel.getTextModel().isShowEdgeLabels()) { // textManager.getEdgeRenderer().beginRendering(); // textManager.defaultEdgeColor(); // if (textManager.isSelectedOnly()) { // for (Iterator<ModelImpl> itr = octree.getObjectIterator(AbstractEngine.CLASS_EDGE); itr.hasNext();) { // ModelImpl obj = itr.next(); // if (obj.markTime != markTime) { // if ((obj.isSelected() || obj.isHighlight()) && obj.getObj().getTextData().isVisible()) { // textManager.getEdgeRenderer().drawTextEdge(obj); // } // obj.markTime = markTime; // } // } // } else { // for (Iterator<ModelImpl> itr = octree.getObjectIterator(AbstractEngine.CLASS_EDGE); itr.hasNext();) { // ModelImpl obj = itr.next(); // if (obj.markTime != markTime) { // if (obj.getObj().getTextData().isVisible()) { // textManager.getEdgeRenderer().drawTextEdge(obj); // } // obj.markTime = markTime; // } // } // } // textManager.getEdgeRenderer().endRendering(); // } } // octree.displayOctree(gl, glu); } @Override public void afterDisplay(GL2 gl, GLU glu) { if (vizConfig.isSelectionEnable() && currentSelectionArea != null) { gl.glMatrixMode(GL2.GL_PROJECTION); gl.glPushMatrix(); gl.glLoadIdentity(); gl.glOrtho(0, graphDrawable.getViewportWidth(), 0, graphDrawable.getViewportHeight(), -1, 1); gl.glMatrixMode(GL2.GL_MODELVIEW); gl.glPushMatrix(); gl.glLoadIdentity(); currentSelectionArea.drawArea(gl, glu); gl.glMatrixMode(GL2.GL_PROJECTION); gl.glPopMatrix(); gl.glMatrixMode(GL2.GL_MODELVIEW); gl.glPopMatrix(); } graphIO.trigger(); } @Override public void cameraHasBeenMoved(GL2 gl, GLU glu) { } @Override public void initEngine(final GL2 gl, final GLU glu) { initDisplayLists(gl, glu); // scheduler.cameraMoved.set(true); // scheduler.mouseMoved.set(true); lifeCycle.setInited(); } @Override public void initScreenshot(GL2 gl, GLU glu) { initDisplayLists(gl, glu); textManager.getNodeRenderer().reinitRenderer(); textManager.getEdgeRenderer().reinitRenderer(); // scheduler.cameraMoved.set(true); } @Override public void resetObjectClass(ModelClass object3dClass) { // octree.resetObjectClass(object3dClass.getClassId()); } @Override public void mouseClick() { if (vizConfig.isSelectionEnable() && rectangleSelection && !customSelection) { Rectangle rectangle = (Rectangle) currentSelectionArea; //rectangle.setBlocking(false); //Select with click int i = 0; boolean someSelection = false; // for (Iterator<ModelImpl> itr = octree.getSelectedObjectIterator(objClass.getClassId()); itr.hasNext();) { // NodeModel obj = (NodeModel) itr.next(); // if (isUnderMouse(obj)) { // if (!obj.isSelected()) { // //New selected // obj.setSelected(true); // /*if (vizEventManager.hasSelectionListeners()) { // newSelectedObjects.add(obj); // }*/ // selectedObjects[i].add(obj); // } // someSelection = true; // obj.selectionMark = markTime2; // } // } // if (!(rectangle.isCtrl() && someSelection)) { // for (Iterator<ModelImpl> itr = selectedObjects[i].iterator(); itr.hasNext();) { // ModelImpl o = itr.next(); // if (o.selectionMark != markTime2) { // itr.remove(); // o.setSelected(false); // } // } // // // i++; // } rectangle.setBlocking(someSelection); if (vizController.getVizModel().isLightenNonSelectedAuto()) { if (vizConfig.isLightenNonSelectedAnimation()) { if (!anySelected && someSelection) { //Start animation lightenAnimationDelta = 0.07f; } else if (anySelected && !someSelection) { //Stop animation lightenAnimationDelta = -0.07f; } vizConfig.setLightenNonSelected(someSelection || lightenAnimationDelta != 0); } else { vizConfig.setLightenNonSelected(someSelection); } } anySelected = someSelection; scheduler.requireUpdateSelection(); } } @Override public void mouseDrag() { if (vizConfig.isMouseSelectionUpdateWhileDragging()) { mouseMove(); } else { // float[] drag = graphIO.getMouseDrag3d(); // for (ModelImpl obj : selectedObjects[0]) { // float[] mouseDistance = obj.getDragDistanceFromMouse(); // obj.getObj().setX(drag[0] + mouseDistance[0]); // obj.getObj().setY(drag[1] + mouseDistance[1]); // } } } @Override public void mouseMove() { //Selection if (vizConfig.isSelectionEnable() && rectangleSelection) { Rectangle rectangle = (Rectangle) currentSelectionArea; rectangle.setMousePosition(graphIO.getMousePosition()); if (rectangle.isStop()) { return; } } if (customSelection || currentSelectionArea.blockSelection()) { return; } // // // /*List<ModelImpl> newSelectedObjects = null; // List<ModelImpl> unSelectedObjects = null; // // if (vizEventManager.hasSelectionListeners()) { // newSelectedObjects = new ArrayList<ModelImpl>(); // unSelectedObjects = new ArrayList<ModelImpl>(); // }*/ // boolean someSelection = false; for (Iterator<NodeModel> itr = octree.getSelectableNodeIterator(); itr.hasNext();) { NodeModel obj = itr.next(); if (isUnderMouse(obj)) { if (!obj.isSelected()) { //New selected obj.setSelected(true); } someSelection = true; } else if (obj.isSelected()) { obj.setSelected(false); } } // // for (ModelClass objClass : selectableClasses) { // forceUnselect = objClass.isAloneSelection() && someSelection; // for (Iterator<ModelImpl> itr = octree.getSelectedObjectIterator(objClass.getClassId()); itr.hasNext();) { // ModelImpl obj = itr.next(); // if (!forceUnselect && isUnderMouse(obj) && currentSelectionArea.select(obj.getObj())) { // if (!objClass.isAloneSelection()) { //avoid potatoes to select // someSelection = true; // } // if (!obj.isSelected()) { // //New selected // obj.setSelected(true); // /*if (vizEventManager.hasSelectionListeners()) { // newSelectedObjects.add(obj); // }*/ // selectedObjects[i].add(obj); // } // obj.selectionMark = markTime2; // } else if (currentSelectionArea.unselect(obj.getObj())) { // if (forceUnselect) { // obj.setAutoSelect(false); // } /*else if (vizEventManager.hasSelectionListeners() && obj.isSelected()) { // unSelectedObjects.add(obj); // }*/ // } // } // // for (Iterator<ModelImpl> itr = selectedObjects[i].iterator(); itr.hasNext();) { // ModelImpl o = itr.next(); // if (o.selectionMark != markTime2) { // itr.remove(); // o.setSelected(false); // } // } // } // if (vizController.getVizModel().isLightenNonSelectedAuto()) { if (vizConfig.isLightenNonSelectedAnimation()) { if (!anySelected && someSelection) { //Start animation lightenAnimationDelta = 0.07f; } else if (anySelected && !someSelection) { //Stop animation lightenAnimationDelta = -0.07f; } vizConfig.setLightenNonSelected(someSelection || lightenAnimationDelta != 0); } else { vizConfig.setLightenNonSelected(someSelection); } } anySelected = someSelection; } @Override public void refreshGraphLimits() { } @Override public void startDrag() { float x = graphIO.getMouseDrag3d()[0]; float y = graphIO.getMouseDrag3d()[1]; // for (Iterator<ModelImpl> itr = selectedObjects[0].iterator(); itr.hasNext();) { // ModelImpl o = itr.next(); // float[] tab = o.getDragDistanceFromMouse(); // tab[0] = o.getObj().x() - x; // tab[1] = o.getObj().y() - y; // } } @Override public void stopDrag() { //Selection if (vizConfig.isSelectionEnable() && rectangleSelection) { Rectangle rectangle = (Rectangle) currentSelectionArea; rectangle.stop(); scheduler.requireUpdateSelection(); } } @Override public void updateObjectsPosition() { // for (ModelClass objClass : modelClasses) { // if (objClass.isEnabled()) { // octree.updateObjectsPosition(objClass.getClassId()); // } // } } // @Override // public ModelImpl[] getSelectedObjects(int modelClass) { // return selectedObjects[modelClasses[modelClass].getSelectionId()].toArray(new ModelImpl[0]); // } // @Override // public void selectObject(Model obj) { // ModelImpl modl = (ModelImpl) obj; // if (!customSelection) { // vizConfig.setRectangleSelection(false); // customSelection = true; // configChanged = true; // //Reset // for (ModelClass objClass : selectableClasses) { // for (Iterator<ModelImpl> itr = selectedObjects[objClass.getSelectionId()].iterator(); itr.hasNext();) { // ModelImpl o = itr.next(); // itr.remove(); // o.setSelected(false); // } // } // anySelected = true; // //Force highlight // if (vizController.getVizModel().isLightenNonSelectedAuto()) { // // if (vizConfig.isLightenNonSelectedAnimation()) { // //Start animation // lightenAnimationDelta = 0.07f; // vizConfig.setLightenNonSelected(true); // } else { // vizConfig.setLightenNonSelected(true); // } // } // } // modl.setSelected(true); // if (modl.getObj() instanceof NodeData) { // selectedObjects[modelClasses[AbstractEngine.CLASS_NODE].getSelectionId()].add(modl); // } // // forceSelectRefresh(modelClasses[AbstractEngine.CLASS_EDGE].getClassId()); // } // @Override // public void selectObject(Model[] objs) { // if (!customSelection) { // vizConfig.setRectangleSelection(false); // customSelection = true; // configChanged = true; // //Reset // for (ModelClass objClass : selectableClasses) { // for (Iterator<ModelImpl> itr = selectedObjects[objClass.getSelectionId()].iterator(); itr.hasNext();) { // ModelImpl o = itr.next(); // itr.remove(); // o.setSelected(false); // } // } // anySelected = true; // //Force highlight // if (vizController.getVizModel().isLightenNonSelectedAuto()) { // // if (vizConfig.isLightenNonSelectedAnimation()) { // //Start animation // lightenAnimationDelta = 0.07f; // vizConfig.setLightenNonSelected(true); // } else { // vizConfig.setLightenNonSelected(true); // } // } // } else { // //Reset // for (ModelClass objClass : selectableClasses) { // for (Iterator<ModelImpl> itr = selectedObjects[objClass.getSelectionId()].iterator(); itr.hasNext();) { // ModelImpl o = itr.next(); // itr.remove(); // o.setSelected(false); // } // } // // for (Iterator<ModelImpl> itr = octree.getSelectedObjectIterator(modelClasses[AbstractEngine.CLASS_EDGE].getClassId()); itr.hasNext();) { // ModelImpl obj = itr.next(); // obj.setSelected(false); // } // } // for (Model r : objs) { // if (r != null) { // ModelImpl mdl = (ModelImpl) r; // mdl.setSelected(true); // if (mdl.getObj() instanceof NodeData) { // selectedObjects[modelClasses[AbstractEngine.CLASS_NODE].getSelectionId()].add(mdl); // } else if (mdl.getObj() instanceof EdgeData) { // selectedObjects[modelClasses[AbstractEngine.CLASS_EDGE].getSelectionId()].add(mdl); // } // } // } // // } public void forceSelectRefresh(int selectedClass) { // for (Iterator<ModelImpl> itr = octree.getSelectedObjectIterator(selectedClass); itr.hasNext();) { // ModelImpl obj = itr.next(); // if (isUnderMouse(obj)) { // if (!obj.isSelected()) { // //New selected // obj.setSelected(true); // selectedObjects[selectedClass].add(obj); // } // } // } } @Override public void resetSelection() { customSelection = false; configChanged = true; anySelected = false; // for (ModelClass objClass : selectableClasses) { // selectedObjects[objClass.getSelectionId()].clear(); // } } private void initDisplayLists(GL2 gl, GLU glu) { //Constants float blancCasse[] = {(float) 213 / 255, (float) 208 / 255, (float) 188 / 255, 1.0f}; float noirCasse[] = {(float) 39 / 255, (float) 25 / 255, (float) 99 / 255, 1.0f}; float noir[] = {(float) 0 / 255, (float) 0 / 255, (float) 0 / 255, 0.0f}; float[] shine_low = {10.0f, 0.0f, 0.0f, 0.0f}; FloatBuffer ambient_metal = FloatBuffer.wrap(noir); FloatBuffer diffuse_metal = FloatBuffer.wrap(noirCasse); FloatBuffer specular_metal = FloatBuffer.wrap(blancCasse); FloatBuffer shininess_metal = FloatBuffer.wrap(shine_low); //End //Quadric for all the glu models GLUquadric quadric = glu.gluNewQuadric(); int ptr = gl.glGenLists(4); // Metal material display list int MATTER_METAL = ptr; gl.glNewList(MATTER_METAL, GL2.GL_COMPILE); gl.glMaterialfv(GL2.GL_FRONT_AND_BACK, GL2.GL_AMBIENT, ambient_metal); gl.glMaterialfv(GL2.GL_FRONT_AND_BACK, GL2.GL_DIFFUSE, diffuse_metal); gl.glMaterialfv(GL2.GL_FRONT_AND_BACK, GL2.GL_SPECULAR, specular_metal); gl.glMaterialfv(GL2.GL_FRONT_AND_BACK, GL2.GL_SHININESS, shininess_metal); gl.glEndList(); //Fin //Display lists for (Modeler cis : nodeClass.getModelers()) { int newPtr = cis.initDisplayLists(gl, glu, quadric, ptr); ptr = newPtr; } //Fin // Sphere with a texture //SHAPE_BILLBOARD = SHAPE_SPHERE32 + 1; /*gl.glNewList(SHAPE_BILLBOARD,GL2.GL_COMPILE); textures[0].bind(); gl.glBegin(GL2.GL_TRIANGLE_STRIP); // Map the texture and create the vertices for the particle. gl.glTexCoord2d(1, 1); gl.glVertex3f(0.5f, 0.5f, 0); gl.glTexCoord2d(0, 1); gl.glVertex3f(-0.5f, 0.5f,0); gl.glTexCoord2d(1, 0); gl.glVertex3f(0.5f, -0.5f, 0); gl.glTexCoord2d(0, 0); gl.glVertex3f(-0.5f,-0.5f, 0); gl.glEnd(); gl.glBindTexture(GL2.GL_TEXTURE_2D,0); gl.glEndList();*/ //Fin glu.gluDeleteQuadric(quadric); } @Override public void initObject3dClass() { modelClassLibrary.createModelClassesCompatibility(this); nodeClass = modelClassLibrary.getNodeClass(); edgeClass = modelClassLibrary.getEdgeClass(); nodeClass.setEnabled(true); edgeClass.setEnabled(vizController.getVizModel().isShowEdges()); } @Override public void initSelection() { if (vizConfig.isCustomSelection()) { rectangleSelection = false; currentSelectionArea = null; } else if (vizConfig.isRectangleSelection()) { currentSelectionArea = new Rectangle(); rectangleSelection = true; customSelection = false; } else { currentSelectionArea = new Cylinder(); rectangleSelection = false; customSelection = false; } } @Override public void startAnimating() { if (!scheduler.isAnimating()) { scheduler.start(); graphIO.startMouseListening(); } } @Override public void stopAnimating() { if (scheduler.isAnimating()) { scheduler.stop(); graphIO.stopMouseListening(); } } @Override public Scheduler getScheduler() { return scheduler; } }
true
true
public void display(GL2 gl, GLU glu) { //Update viewport NodeModeler nodeModeler = (NodeModeler) nodeClass.getCurrentModeler(); for (Iterator<NodeModel> itr = octree.getNodeIterator(); itr.hasNext();) { //TODO Move this NodeModel obj = itr.next(); nodeModeler.setViewportPosition(obj); } markTime++; VizModel vizModel = VizController.getInstance().getVizModel(); //Edges if (edgeClass.isEnabled()) { edgeClass.beforeDisplay(gl, glu); for (Iterator<EdgeModel> itr = octree.getEdgeIterator(); itr.hasNext();) { EdgeModel obj = itr.next(); if (obj.markTime != markTime) { obj.display(gl, glu, vizModel); obj.markTime = markTime; } } edgeClass.afterDisplay(gl, glu); } markTime++; //Arrows if (vizConfig.isShowArrows() && dataBridge.isDirected()) { gl.glBegin(GL2.GL_TRIANGLES); for (Iterator<EdgeModel> itr = octree.getEdgeIterator(); itr.hasNext();) { EdgeModel obj = itr.next(); if (obj.getEdge().isDirected() && obj.markTime != markTime) { obj.displayArrow(gl, glu, vizModel); obj.markTime = markTime; } } gl.glEnd(); } //Nodes if (nodeClass.isEnabled()) { nodeClass.beforeDisplay(gl, glu); for (Iterator<NodeModel> itr = octree.getNodeIterator(); itr.hasNext();) { NodeModel obj = itr.next(); if (obj.markTime != markTime) { obj.display(gl, glu, vizModel); obj.markTime = markTime; } } nodeClass.afterDisplay(gl, glu); } //Labels if (vizModel.getTextModel().isShowNodeLabels() || vizModel.getTextModel().isShowEdgeLabels()) { markTime++; if (nodeClass.isEnabled() && vizModel.getTextModel().isShowNodeLabels()) { textManager.getNodeRenderer().beginRendering(); textManager.defaultNodeColor(); if (textManager.isSelectedOnly()) { for (Iterator<NodeModel> itr = octree.getNodeIterator(); itr.hasNext();) { NodeModel obj = itr.next(); if (obj.markTime != markTime) { if (obj.isSelected() && obj.isTextVisible()) { textManager.getNodeRenderer().drawTextNode(obj); } obj.markTime = markTime; } } } else { for (Iterator<NodeModel> itr = octree.getNodeIterator(); itr.hasNext();) { NodeModel obj = itr.next(); if (obj.markTime != markTime) { if (obj.isTextVisible()) { textManager.getNodeRenderer().drawTextNode(obj); } obj.markTime = markTime; } } } textManager.getNodeRenderer().endRendering(); } // if (edgeClass.isEnabled() && vizModel.getTextModel().isShowEdgeLabels()) { // textManager.getEdgeRenderer().beginRendering(); // textManager.defaultEdgeColor(); // if (textManager.isSelectedOnly()) { // for (Iterator<ModelImpl> itr = octree.getObjectIterator(AbstractEngine.CLASS_EDGE); itr.hasNext();) { // ModelImpl obj = itr.next(); // if (obj.markTime != markTime) { // if ((obj.isSelected() || obj.isHighlight()) && obj.getObj().getTextData().isVisible()) { // textManager.getEdgeRenderer().drawTextEdge(obj); // } // obj.markTime = markTime; // } // } // } else { // for (Iterator<ModelImpl> itr = octree.getObjectIterator(AbstractEngine.CLASS_EDGE); itr.hasNext();) { // ModelImpl obj = itr.next(); // if (obj.markTime != markTime) { // if (obj.getObj().getTextData().isVisible()) { // textManager.getEdgeRenderer().drawTextEdge(obj); // } // obj.markTime = markTime; // } // } // } // textManager.getEdgeRenderer().endRendering(); // } } // octree.displayOctree(gl, glu); }
public void display(GL2 gl, GLU glu) { //Update viewport NodeModeler nodeModeler = (NodeModeler) nodeClass.getCurrentModeler(); for (Iterator<NodeModel> itr = octree.getNodeIterator(); itr.hasNext();) { //TODO Move this NodeModel obj = itr.next(); nodeModeler.setViewportPosition(obj); } markTime++; VizModel vizModel = VizController.getInstance().getVizModel(); //Edges if (edgeClass.isEnabled()) { edgeClass.beforeDisplay(gl, glu); for (Iterator<EdgeModel> itr = octree.getEdgeIterator(); itr.hasNext();) { EdgeModel obj = itr.next(); if (obj.markTime != markTime) { obj.display(gl, glu, vizModel); obj.markTime = markTime; } } edgeClass.afterDisplay(gl, glu); } markTime++; //Arrows if (edgeClass.isEnabled() && vizConfig.isShowArrows() && dataBridge.isDirected()) { gl.glBegin(GL2.GL_TRIANGLES); for (Iterator<EdgeModel> itr = octree.getEdgeIterator(); itr.hasNext();) { EdgeModel obj = itr.next(); if (obj.getEdge().isDirected() && obj.markTime != markTime) { obj.displayArrow(gl, glu, vizModel); obj.markTime = markTime; } } gl.glEnd(); } //Nodes if (nodeClass.isEnabled()) { nodeClass.beforeDisplay(gl, glu); for (Iterator<NodeModel> itr = octree.getNodeIterator(); itr.hasNext();) { NodeModel obj = itr.next(); if (obj.markTime != markTime) { obj.display(gl, glu, vizModel); obj.markTime = markTime; } } nodeClass.afterDisplay(gl, glu); } //Labels if (vizModel.getTextModel().isShowNodeLabels() || vizModel.getTextModel().isShowEdgeLabels()) { markTime++; if (nodeClass.isEnabled() && vizModel.getTextModel().isShowNodeLabels()) { textManager.getNodeRenderer().beginRendering(); textManager.defaultNodeColor(); if (textManager.isSelectedOnly()) { for (Iterator<NodeModel> itr = octree.getNodeIterator(); itr.hasNext();) { NodeModel obj = itr.next(); if (obj.markTime != markTime) { if (obj.isSelected() && obj.isTextVisible()) { textManager.getNodeRenderer().drawTextNode(obj); } obj.markTime = markTime; } } } else { for (Iterator<NodeModel> itr = octree.getNodeIterator(); itr.hasNext();) { NodeModel obj = itr.next(); if (obj.markTime != markTime) { if (obj.isTextVisible()) { textManager.getNodeRenderer().drawTextNode(obj); } obj.markTime = markTime; } } } textManager.getNodeRenderer().endRendering(); } // if (edgeClass.isEnabled() && vizModel.getTextModel().isShowEdgeLabels()) { // textManager.getEdgeRenderer().beginRendering(); // textManager.defaultEdgeColor(); // if (textManager.isSelectedOnly()) { // for (Iterator<ModelImpl> itr = octree.getObjectIterator(AbstractEngine.CLASS_EDGE); itr.hasNext();) { // ModelImpl obj = itr.next(); // if (obj.markTime != markTime) { // if ((obj.isSelected() || obj.isHighlight()) && obj.getObj().getTextData().isVisible()) { // textManager.getEdgeRenderer().drawTextEdge(obj); // } // obj.markTime = markTime; // } // } // } else { // for (Iterator<ModelImpl> itr = octree.getObjectIterator(AbstractEngine.CLASS_EDGE); itr.hasNext();) { // ModelImpl obj = itr.next(); // if (obj.markTime != markTime) { // if (obj.getObj().getTextData().isVisible()) { // textManager.getEdgeRenderer().drawTextEdge(obj); // } // obj.markTime = markTime; // } // } // } // textManager.getEdgeRenderer().endRendering(); // } } // octree.displayOctree(gl, glu); }
diff --git a/src/main/java/novoda/lib/sqliteprovider/provider/SQLiteContentProviderImpl.java b/src/main/java/novoda/lib/sqliteprovider/provider/SQLiteContentProviderImpl.java index 4b66476..d7b72c4 100644 --- a/src/main/java/novoda/lib/sqliteprovider/provider/SQLiteContentProviderImpl.java +++ b/src/main/java/novoda/lib/sqliteprovider/provider/SQLiteContentProviderImpl.java @@ -1,186 +1,186 @@ package novoda.lib.sqliteprovider.provider; import android.content.*; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.net.Uri; import novoda.lib.sqliteprovider.provider.action.InsertHelper; import novoda.lib.sqliteprovider.sqlite.ExtendedSQLiteOpenHelper; import novoda.lib.sqliteprovider.sqlite.ExtendedSQLiteQueryBuilder; import novoda.lib.sqliteprovider.util.*; import novoda.lib.sqliteprovider.util.Log.Provider; import java.io.IOException; import java.util.*; public class SQLiteContentProviderImpl extends SQLiteContentProvider { private static final String ID = "_id"; private static final String GROUP_BY = "groupBy"; private static final String HAVING = "having"; private static final String LIMIT = "limit"; private static final String EXPAND = "expand"; private InsertHelper helper; @Override public boolean onCreate() { super.onCreate(); helper = new InsertHelper((ExtendedSQLiteOpenHelper) getDatabaseHelper()); return true; } @Override protected SQLiteOpenHelper getDatabaseHelper(Context context) { try { return new ExtendedSQLiteOpenHelper(context); } catch (IOException e) { Log.Provider.e(e); throw new IllegalStateException(e.getMessage()); } } @Override protected Uri insertInTransaction(Uri uri, ContentValues values) { long rowId = helper.insert(uri, values); if (rowId > 0) { Uri newUri = ContentUris.withAppendedId(uri, rowId); notifyUriChange(newUri); return newUri; } throw new SQLException("Failed to insert row into " + uri); } protected SQLiteDatabase getWritableDatabase() { return getDatabaseHelper().getWritableDatabase(); } protected SQLiteDatabase getReadableDatabase() { return getDatabaseHelper().getReadableDatabase(); } @Override protected int updateInTransaction(Uri uri, ContentValues values, String selection, String[] selectionArgs) { ContentValues insertValues = (values != null) ? new ContentValues(values) : new ContentValues(); int rowId = getWritableDatabase().update(UriUtils.getItemDirID(uri), insertValues, selection, selectionArgs); if (rowId > 0) { Uri insertUri = ContentUris.withAppendedId(uri, rowId); notifyUriChange(insertUri); return rowId; } throw new SQLException("Failed to update row into " + uri); } @Override protected int deleteInTransaction(Uri uri, String selection, String[] selectionArgs) { SQLiteDatabase database = getWritableDatabase(); int count = database.delete(UriUtils.getItemDirID(uri), selection, selectionArgs); notifyUriChange(uri); return count; } @Override protected void notifyChange() { } public void notifyUriChange(Uri uri) { getContext().getContentResolver().notifyChange(uri, null, getNotificationSyncToNetwork()); } public boolean getNotificationSyncToNetwork() { return false; } @Override public String getType(Uri uri) { return null; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { if (Provider.verboseLoggingEnabled()) { Provider.v("==================== start of query ======================="); Provider.v("Uri: " + uri.toString()); } final ExtendedSQLiteQueryBuilder builder = getSQLiteQueryBuilder(); final List<String> expands = uri.getQueryParameters(EXPAND); final String groupBy = uri.getQueryParameter(GROUP_BY); final String having = uri.getQueryParameter(HAVING); final String limit = uri.getQueryParameter(LIMIT); final StringBuilder tableName = new StringBuilder(UriUtils.getItemDirID(uri)); builder.setTables(tableName.toString()); Map<String, String> autoproj = null; if (expands.size() > 0) { builder.addInnerJoin(expands.toArray(new String[] {})); - ExtendedSQLiteOpenHelper helper = (ExtendedSQLiteOpenHelper) getDatabaseHelper(); - autoproj = helper.getProjectionMap(tableName.toString(), + ExtendedSQLiteOpenHelper extendedHelper = (ExtendedSQLiteOpenHelper) getDatabaseHelper(); + autoproj = extendedHelper.getProjectionMap(tableName.toString(), expands.toArray(new String[] {})); builder.setProjectionMap(autoproj); } if (UriUtils.isItem(uri)) { if (Provider.verboseLoggingEnabled()) { Provider.v("Appending to where clause: " + ID + "=" + uri.getLastPathSegment()); } builder.appendWhere(ID + "=" + uri.getLastPathSegment()); } else { if (UriUtils.hasParent(uri)) { if (Provider.verboseLoggingEnabled()) { Provider.v("Appending to where clause: " + UriUtils.getParentColumnName(uri) + ID + "=" + UriUtils.getParentId(uri)); } builder.appendWhereEscapeString(UriUtils.getParentColumnName(uri) + ID + "=" + UriUtils.getParentId(uri)); } } if (Provider.verboseLoggingEnabled()) { Provider.v("table: " + builder.getTables()); if (projection != null) Provider.v("projection:" + Arrays.toString(projection)); if (selection != null) Provider.v("selection: " + selection + " with arguments " + Arrays.toString(selectionArgs)); Provider.v("extra args: " + groupBy + " ,having: " + having + " ,sort order: " + sortOrder + " ,limit: " + limit); if (autoproj != null) Provider.v("projectionAutomated: " + autoproj); Provider.v("==================== end of query ======================="); } Cursor cursor = builder.query(getReadableDatabase(), projection, selection, selectionArgs, groupBy, having, sortOrder, limit); cursor.setNotificationUri(getContext().getContentResolver(), uri); return cursor; } protected ExtendedSQLiteQueryBuilder getSQLiteQueryBuilder() { return new ExtendedSQLiteQueryBuilder(); } }
true
true
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { if (Provider.verboseLoggingEnabled()) { Provider.v("==================== start of query ======================="); Provider.v("Uri: " + uri.toString()); } final ExtendedSQLiteQueryBuilder builder = getSQLiteQueryBuilder(); final List<String> expands = uri.getQueryParameters(EXPAND); final String groupBy = uri.getQueryParameter(GROUP_BY); final String having = uri.getQueryParameter(HAVING); final String limit = uri.getQueryParameter(LIMIT); final StringBuilder tableName = new StringBuilder(UriUtils.getItemDirID(uri)); builder.setTables(tableName.toString()); Map<String, String> autoproj = null; if (expands.size() > 0) { builder.addInnerJoin(expands.toArray(new String[] {})); ExtendedSQLiteOpenHelper helper = (ExtendedSQLiteOpenHelper) getDatabaseHelper(); autoproj = helper.getProjectionMap(tableName.toString(), expands.toArray(new String[] {})); builder.setProjectionMap(autoproj); } if (UriUtils.isItem(uri)) { if (Provider.verboseLoggingEnabled()) { Provider.v("Appending to where clause: " + ID + "=" + uri.getLastPathSegment()); } builder.appendWhere(ID + "=" + uri.getLastPathSegment()); } else { if (UriUtils.hasParent(uri)) { if (Provider.verboseLoggingEnabled()) { Provider.v("Appending to where clause: " + UriUtils.getParentColumnName(uri) + ID + "=" + UriUtils.getParentId(uri)); } builder.appendWhereEscapeString(UriUtils.getParentColumnName(uri) + ID + "=" + UriUtils.getParentId(uri)); } } if (Provider.verboseLoggingEnabled()) { Provider.v("table: " + builder.getTables()); if (projection != null) Provider.v("projection:" + Arrays.toString(projection)); if (selection != null) Provider.v("selection: " + selection + " with arguments " + Arrays.toString(selectionArgs)); Provider.v("extra args: " + groupBy + " ,having: " + having + " ,sort order: " + sortOrder + " ,limit: " + limit); if (autoproj != null) Provider.v("projectionAutomated: " + autoproj); Provider.v("==================== end of query ======================="); } Cursor cursor = builder.query(getReadableDatabase(), projection, selection, selectionArgs, groupBy, having, sortOrder, limit); cursor.setNotificationUri(getContext().getContentResolver(), uri); return cursor; }
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { if (Provider.verboseLoggingEnabled()) { Provider.v("==================== start of query ======================="); Provider.v("Uri: " + uri.toString()); } final ExtendedSQLiteQueryBuilder builder = getSQLiteQueryBuilder(); final List<String> expands = uri.getQueryParameters(EXPAND); final String groupBy = uri.getQueryParameter(GROUP_BY); final String having = uri.getQueryParameter(HAVING); final String limit = uri.getQueryParameter(LIMIT); final StringBuilder tableName = new StringBuilder(UriUtils.getItemDirID(uri)); builder.setTables(tableName.toString()); Map<String, String> autoproj = null; if (expands.size() > 0) { builder.addInnerJoin(expands.toArray(new String[] {})); ExtendedSQLiteOpenHelper extendedHelper = (ExtendedSQLiteOpenHelper) getDatabaseHelper(); autoproj = extendedHelper.getProjectionMap(tableName.toString(), expands.toArray(new String[] {})); builder.setProjectionMap(autoproj); } if (UriUtils.isItem(uri)) { if (Provider.verboseLoggingEnabled()) { Provider.v("Appending to where clause: " + ID + "=" + uri.getLastPathSegment()); } builder.appendWhere(ID + "=" + uri.getLastPathSegment()); } else { if (UriUtils.hasParent(uri)) { if (Provider.verboseLoggingEnabled()) { Provider.v("Appending to where clause: " + UriUtils.getParentColumnName(uri) + ID + "=" + UriUtils.getParentId(uri)); } builder.appendWhereEscapeString(UriUtils.getParentColumnName(uri) + ID + "=" + UriUtils.getParentId(uri)); } } if (Provider.verboseLoggingEnabled()) { Provider.v("table: " + builder.getTables()); if (projection != null) Provider.v("projection:" + Arrays.toString(projection)); if (selection != null) Provider.v("selection: " + selection + " with arguments " + Arrays.toString(selectionArgs)); Provider.v("extra args: " + groupBy + " ,having: " + having + " ,sort order: " + sortOrder + " ,limit: " + limit); if (autoproj != null) Provider.v("projectionAutomated: " + autoproj); Provider.v("==================== end of query ======================="); } Cursor cursor = builder.query(getReadableDatabase(), projection, selection, selectionArgs, groupBy, having, sortOrder, limit); cursor.setNotificationUri(getContext().getContentResolver(), uri); return cursor; }
diff --git a/src/uk/ac/horizon/ug/exploding/client/GpsStatusActivity.java b/src/uk/ac/horizon/ug/exploding/client/GpsStatusActivity.java index 90303e5..4db6a45 100755 --- a/src/uk/ac/horizon/ug/exploding/client/GpsStatusActivity.java +++ b/src/uk/ac/horizon/ug/exploding/client/GpsStatusActivity.java @@ -1,163 +1,162 @@ /** * Copyright 2010 The University of Nottingham * * This file is part of GenericAndroidClient. * * GenericAndroidClient 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. * * GenericAndroidClient is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with GenericAndroidClient. If not, see <http://www.gnu.org/licenses/>. * */ package uk.ac.horizon.ug.exploding.client; import java.util.Arrays; import java.util.Date; import java.util.Iterator; import android.app.Activity; import android.content.Context; import android.location.GpsSatellite; import android.location.GpsStatus; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.location.LocationProvider; import android.location.GpsStatus.Listener; import android.os.Bundle; import android.util.Log; import android.widget.TextView; /** * @author cmg * */ public class GpsStatusActivity extends Activity implements Listener, LocationListener { private static final String GPS_PROVIDER = "gps"; private static final String TAG = "GpsStatus"; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.gpsstatus); } @Override protected void onPause() { super.onPause(); LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); locationManager.removeGpsStatusListener(this); locationManager.removeUpdates(this); Log.d(TAG, "Pause: disabled Location callbacks"); } @Override protected void onResume() { super.onResume(); LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); locationManager.addGpsStatusListener(this); locationManager.requestLocationUpdates(GPS_PROVIDER, 0, 0, this); Location loc = locationManager.getLastKnownLocation(GPS_PROVIDER); updateLocation(loc); updateEnabled(locationManager.isProviderEnabled(GPS_PROVIDER)); Log.d(TAG, "Resume : enabled Location callbacks"); } private void updateEnabled(boolean providerEnabled) { TextView enabledTextView = (TextView)findViewById(R.id.gps_enabled_text_view); enabledTextView.setText(providerEnabled ? "Yes" : "No"); } private void updateLocation(Location loc) { TextView tv; tv = (TextView)findViewById(R.id.gps_loc_time_text_view); tv.setText(loc==null ? "-" : ""+new Date(loc.getTime())); tv = (TextView)findViewById(R.id.gps_time_text_view); tv.setText(loc==null ? "-" : ""+new Date()); tv = (TextView)findViewById(R.id.gps_latitude_text_view); tv.setText(loc==null ? "-" : ""+loc.getLatitude()); tv = (TextView)findViewById(R.id.gps_longitude_text_view); tv.setText(loc==null ? "-" : ""+loc.getLongitude()); tv = (TextView)findViewById(R.id.gps_altitude_text_view); tv.setText(loc==null ? "-" : ""+loc.getAltitude()); tv = (TextView)findViewById(R.id.gps_accuracy_text_view); tv.setText(loc==null ? "-" : loc.hasAccuracy() ? ""+loc.getAccuracy() : "Not Available"); tv = (TextView)findViewById(R.id.gps_accuracy_text_view); tv.setText(loc==null ? "-" : loc.hasAccuracy() ? ""+loc.getAccuracy() : "Not Available"); } @Override public void onGpsStatusChanged(int event) { - // TODO Auto-generated method stub LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); GpsStatus status = locationManager.getGpsStatus(null); TextView tv; tv = (TextView)findViewById(R.id.gps_time_to_fix_text_view); - tv.setText(""+new Date(status.getTimeToFirstFix())); + tv.setText(""+(status.getTimeToFirstFix()/1000)+"s"); int satCount = 0, satFixCount = 0; double snrs[] = new double[status.getMaxSatellites()]; int i =0; Iterator<GpsSatellite> sats = status.getSatellites().iterator(); while(sats.hasNext()) { GpsSatellite sat = sats.next(); if (sat.usedInFix()) satFixCount++; satCount++; snrs[i] = sat.getSnr(); i++; } // ascending Arrays.sort(snrs); tv = (TextView)findViewById(R.id.gps_sat_number_fix_text_view); tv.setText(""+satFixCount); tv = (TextView)findViewById(R.id.gps_sat_number_total_text_view); tv.setText(""+satCount); tv = (TextView)findViewById(R.id.gps_sat_snr_text_view); if (snrs.length>=4) tv.setText(""+snrs[snrs.length-4]); else if (snrs.length>0) tv.setText(""+snrs[snrs.length-1]); else tv.setText("-"); } @Override public void onLocationChanged(Location location) { updateLocation(location); } @Override public void onProviderDisabled(String provider) { if (GPS_PROVIDER.equals(provider)) updateEnabled(false); } @Override public void onProviderEnabled(String provider) { if (GPS_PROVIDER.equals(provider)) updateEnabled(true); } @Override public void onStatusChanged(String provider, int status, Bundle extras) { if (GPS_PROVIDER.equals(provider)) updateStatus(status); } private void updateStatus(int status) { TextView enabledTextView = (TextView)findViewById(R.id.gps_status_text_view); String statusText = (status==LocationProvider.AVAILABLE ? "AVAILABLE" : status==LocationProvider.OUT_OF_SERVICE ? "OUT_OF_SERVICE" : status==LocationProvider.TEMPORARILY_UNAVAILABLE ? "TEMPORARILY_UNAVAILABLE" : "unknown ("+status+")"); enabledTextView.setText(statusText); } }
false
true
public void onGpsStatusChanged(int event) { // TODO Auto-generated method stub LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); GpsStatus status = locationManager.getGpsStatus(null); TextView tv; tv = (TextView)findViewById(R.id.gps_time_to_fix_text_view); tv.setText(""+new Date(status.getTimeToFirstFix())); int satCount = 0, satFixCount = 0; double snrs[] = new double[status.getMaxSatellites()]; int i =0; Iterator<GpsSatellite> sats = status.getSatellites().iterator(); while(sats.hasNext()) { GpsSatellite sat = sats.next(); if (sat.usedInFix()) satFixCount++; satCount++; snrs[i] = sat.getSnr(); i++; } // ascending Arrays.sort(snrs); tv = (TextView)findViewById(R.id.gps_sat_number_fix_text_view); tv.setText(""+satFixCount); tv = (TextView)findViewById(R.id.gps_sat_number_total_text_view); tv.setText(""+satCount); tv = (TextView)findViewById(R.id.gps_sat_snr_text_view); if (snrs.length>=4) tv.setText(""+snrs[snrs.length-4]); else if (snrs.length>0) tv.setText(""+snrs[snrs.length-1]); else tv.setText("-"); }
public void onGpsStatusChanged(int event) { LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); GpsStatus status = locationManager.getGpsStatus(null); TextView tv; tv = (TextView)findViewById(R.id.gps_time_to_fix_text_view); tv.setText(""+(status.getTimeToFirstFix()/1000)+"s"); int satCount = 0, satFixCount = 0; double snrs[] = new double[status.getMaxSatellites()]; int i =0; Iterator<GpsSatellite> sats = status.getSatellites().iterator(); while(sats.hasNext()) { GpsSatellite sat = sats.next(); if (sat.usedInFix()) satFixCount++; satCount++; snrs[i] = sat.getSnr(); i++; } // ascending Arrays.sort(snrs); tv = (TextView)findViewById(R.id.gps_sat_number_fix_text_view); tv.setText(""+satFixCount); tv = (TextView)findViewById(R.id.gps_sat_number_total_text_view); tv.setText(""+satCount); tv = (TextView)findViewById(R.id.gps_sat_snr_text_view); if (snrs.length>=4) tv.setText(""+snrs[snrs.length-4]); else if (snrs.length>0) tv.setText(""+snrs[snrs.length-1]); else tv.setText("-"); }
diff --git a/src/edu/common/dynamicextensions/domain/DoubleAttributeTypeInformation.java b/src/edu/common/dynamicextensions/domain/DoubleAttributeTypeInformation.java index 4a0477071..c086ed80b 100644 --- a/src/edu/common/dynamicextensions/domain/DoubleAttributeTypeInformation.java +++ b/src/edu/common/dynamicextensions/domain/DoubleAttributeTypeInformation.java @@ -1,75 +1,72 @@ package edu.common.dynamicextensions.domain; import java.text.DecimalFormat; import java.text.NumberFormat; import edu.common.dynamicextensions.domaininterface.DoubleTypeInformationInterface; import edu.common.dynamicextensions.domaininterface.DoubleValueInterface; import edu.common.dynamicextensions.domaininterface.PermissibleValueInterface; import edu.common.dynamicextensions.entitymanager.EntityManagerConstantsInterface; /** * @hibernate.joined-subclass table="DYEXTN_DOUBLE_TYPE_INFO" * @hibernate.joined-subclass-key column="IDENTIFIER" * @author sujay_narkar * */ public class DoubleAttributeTypeInformation extends NumericAttributeTypeInformation implements DoubleTypeInformationInterface { /** * Serial version id. */ private static final long serialVersionUID = 7901101750879429344L; /** * @see edu.common.dynamicextensions.domaininterface.AttributeTypeInformationInterface#getDataType() */ public String getDataType() { return EntityManagerConstantsInterface.DOUBLE_ATTRIBUTE_TYPE; } /** * */ public PermissibleValueInterface getPermissibleValueForString(String value) { DomainObjectFactory factory = DomainObjectFactory.getInstance(); DoubleValueInterface doubleValue = factory.createDoubleValue(); doubleValue.setValue(new Double(value)); return doubleValue; } /** * */ public String getFormattedValue(Double value) { String formattedValue = ""; if (value != null) { if (this.decimalPlaces.intValue() > 0) { DecimalFormat formatDecimal = (DecimalFormat) NumberFormat .getNumberInstance(); formatDecimal.setParseBigDecimal(true); formatDecimal.setMaximumFractionDigits(this.decimalPlaces .intValue()); formattedValue = formatDecimal.format(value); } else { - PermissibleValueInterface permissibleValueInterface = getPermissibleValueForString(value - .toString()); - formattedValue = permissibleValueInterface.getValueAsObject() - .toString(); + formattedValue = value.toString(); } } return formattedValue; } }
true
true
public String getFormattedValue(Double value) { String formattedValue = ""; if (value != null) { if (this.decimalPlaces.intValue() > 0) { DecimalFormat formatDecimal = (DecimalFormat) NumberFormat .getNumberInstance(); formatDecimal.setParseBigDecimal(true); formatDecimal.setMaximumFractionDigits(this.decimalPlaces .intValue()); formattedValue = formatDecimal.format(value); } else { PermissibleValueInterface permissibleValueInterface = getPermissibleValueForString(value .toString()); formattedValue = permissibleValueInterface.getValueAsObject() .toString(); } } return formattedValue; }
public String getFormattedValue(Double value) { String formattedValue = ""; if (value != null) { if (this.decimalPlaces.intValue() > 0) { DecimalFormat formatDecimal = (DecimalFormat) NumberFormat .getNumberInstance(); formatDecimal.setParseBigDecimal(true); formatDecimal.setMaximumFractionDigits(this.decimalPlaces .intValue()); formattedValue = formatDecimal.format(value); } else { formattedValue = value.toString(); } } return formattedValue; }
diff --git a/src/main/java/de/cismet/tools/gui/documents/DocumentPanelTester.java b/src/main/java/de/cismet/tools/gui/documents/DocumentPanelTester.java index 80e6efb..57dddac 100644 --- a/src/main/java/de/cismet/tools/gui/documents/DocumentPanelTester.java +++ b/src/main/java/de/cismet/tools/gui/documents/DocumentPanelTester.java @@ -1,64 +1,64 @@ /* * DocumentPanelTester.java * * Created on 26. August 2008, 12:56 */ package de.cismet.tools.gui.documents; import de.cismet.tools.gui.log4jquickconfig.Log4JQuickConfig; /** * * @author hell */ public class DocumentPanelTester extends javax.swing.JFrame { /** Creates new form DocumentPanelTester */ public DocumentPanelTester() { Log4JQuickConfig.configure4LumbermillOnLocalhost(); initComponents(); - dopTest.getDocumentListModel().addElement(new DefaultDocument("briefpapier", "/home/hell/test/briefpapier.pdf")); - dopTest.getDocumentListModel().addElement(new DefaultDocument("ein png", "/home/hell/test/cubert.png")); - dopTest.getDocumentListModel().addElement(new DefaultDocument("hiker (jpg)", "/home/hell/test/hiker.jpg")); - dopTest.getDocumentListModel().addElement(new DefaultDocument("ein gif", "/home/hell/test/santa.gif")); - dopTest.getDocumentListModel().addElement(new DefaultDocument("google online gif ", "http://www.google.de/intl/de_de/images/logo.gif")); - dopTest.getDocumentListModel().addElement(new DefaultDocument("website", "http://www.ebay.de/")); - dopTest.getDocumentListModel().addElement(new DefaultDocument("website", "http://demohost/web/shen/utilities/wastewaterrecycling/SST-1.pdf")); + dopTest.getDocumentListModel().addElement(new DefaultDocument("briefpapier", "/home/hell/test/briefpapier.pdf")); //NOI18N + dopTest.getDocumentListModel().addElement(new DefaultDocument("ein png", "/home/hell/test/cubert.png")); //NOI18N + dopTest.getDocumentListModel().addElement(new DefaultDocument("hiker (jpg)", "/home/hell/test/hiker.jpg")); //NOI18N + dopTest.getDocumentListModel().addElement(new DefaultDocument("ein gif", "/home/hell/test/santa.gif")); //NOI18N + dopTest.getDocumentListModel().addElement(new DefaultDocument("google online gif ", "http://www.google.de/intl/de_de/images/logo.gif")); //NOI18N + dopTest.getDocumentListModel().addElement(new DefaultDocument("website", "http://www.ebay.de/")); //NOI18N + dopTest.getDocumentListModel().addElement(new DefaultDocument("website", "http://demohost/web/shen/utilities/wastewaterrecycling/SST-1.pdf")); //NOI18N } /** 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() { dopTest = new de.cismet.tools.gui.documents.DocumentPanel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); getContentPane().add(dopTest, java.awt.BorderLayout.CENTER); pack(); }// </editor-fold>//GEN-END:initComponents /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new DocumentPanelTester().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private de.cismet.tools.gui.documents.DocumentPanel dopTest; // End of variables declaration//GEN-END:variables }
true
true
public DocumentPanelTester() { Log4JQuickConfig.configure4LumbermillOnLocalhost(); initComponents(); dopTest.getDocumentListModel().addElement(new DefaultDocument("briefpapier", "/home/hell/test/briefpapier.pdf")); dopTest.getDocumentListModel().addElement(new DefaultDocument("ein png", "/home/hell/test/cubert.png")); dopTest.getDocumentListModel().addElement(new DefaultDocument("hiker (jpg)", "/home/hell/test/hiker.jpg")); dopTest.getDocumentListModel().addElement(new DefaultDocument("ein gif", "/home/hell/test/santa.gif")); dopTest.getDocumentListModel().addElement(new DefaultDocument("google online gif ", "http://www.google.de/intl/de_de/images/logo.gif")); dopTest.getDocumentListModel().addElement(new DefaultDocument("website", "http://www.ebay.de/")); dopTest.getDocumentListModel().addElement(new DefaultDocument("website", "http://demohost/web/shen/utilities/wastewaterrecycling/SST-1.pdf")); }
public DocumentPanelTester() { Log4JQuickConfig.configure4LumbermillOnLocalhost(); initComponents(); dopTest.getDocumentListModel().addElement(new DefaultDocument("briefpapier", "/home/hell/test/briefpapier.pdf")); //NOI18N dopTest.getDocumentListModel().addElement(new DefaultDocument("ein png", "/home/hell/test/cubert.png")); //NOI18N dopTest.getDocumentListModel().addElement(new DefaultDocument("hiker (jpg)", "/home/hell/test/hiker.jpg")); //NOI18N dopTest.getDocumentListModel().addElement(new DefaultDocument("ein gif", "/home/hell/test/santa.gif")); //NOI18N dopTest.getDocumentListModel().addElement(new DefaultDocument("google online gif ", "http://www.google.de/intl/de_de/images/logo.gif")); //NOI18N dopTest.getDocumentListModel().addElement(new DefaultDocument("website", "http://www.ebay.de/")); //NOI18N dopTest.getDocumentListModel().addElement(new DefaultDocument("website", "http://demohost/web/shen/utilities/wastewaterrecycling/SST-1.pdf")); //NOI18N }
diff --git a/src/org/jrubyparser/lexer/Lexer.java b/src/org/jrubyparser/lexer/Lexer.java index 1cadd7b..fd0fcf5 100644 --- a/src/org/jrubyparser/lexer/Lexer.java +++ b/src/org/jrubyparser/lexer/Lexer.java @@ -1,2916 +1,2921 @@ /* ***** 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) 2002 Benoit Cerrina <[email protected]> * Copyright (C) 2002-2004 Anders Bengtsson <[email protected]> * Copyright (C) 2002-2004 Jan Arne Petersen <[email protected]> * Copyright (C) 2004-2009 Thomas E Enebo <[email protected]> * Copyright (C) 2004 Stefan Matthias Aust <[email protected]> * Copyright (C) 2004-2005 David Corbin <[email protected]> * Copyright (C) 2005 Zach Dennis <[email protected]> * Copyright (C) 2006 Thomas Corbat <[email protected]> * * Alternatively, the contents of this file may be used under the terms of * either of the GNU General Public License Version 2 or later (the "GPL"), * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the CPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the CPL, the GPL or the LGPL. ***** END LICENSE BLOCK *****/ package org.jrubyparser.lexer; import java.io.IOException; import java.math.BigInteger; import java.util.HashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.jrubyparser.ast.BackRefNode; import org.jrubyparser.ast.BignumNode; import org.jrubyparser.ast.CommentNode; import org.jrubyparser.ast.FixnumNode; import org.jrubyparser.ast.FloatNode; import org.jrubyparser.ast.NthRefNode; import org.jrubyparser.ast.StrNode; import org.jrubyparser.IRubyWarnings; import org.jrubyparser.IRubyWarnings.ID; import org.jrubyparser.SourcePosition; import org.jrubyparser.lexer.SyntaxException.PID; import org.jrubyparser.parser.ParserSupport; import org.jrubyparser.parser.Tokens; import org.jrubyparser.util.CStringBuilder; /** * This is a port of the MRI lexer to Java it is compatible to Ruby 1.8.x and Ruby 1.9.x * depending on compatibility flag. */ public class Lexer { private static String END_MARKER = "_END__"; private static String BEGIN_DOC_MARKER = "begin"; private static String END_DOC_MARKER = "end"; private static HashMap<String, Keyword> map; static { map = new HashMap<String, Keyword>(); map.put("end", Keyword.END); map.put("else", Keyword.ELSE); map.put("case", Keyword.CASE); map.put("ensure", Keyword.ENSURE); map.put("module", Keyword.MODULE); map.put("elsif", Keyword.ELSIF); map.put("def", Keyword.DEF); map.put("rescue", Keyword.RESCUE); map.put("not", Keyword.NOT); map.put("then", Keyword.THEN); map.put("yield", Keyword.YIELD); map.put("for", Keyword.FOR); map.put("self", Keyword.SELF); map.put("false", Keyword.FALSE); map.put("retry", Keyword.RETRY); map.put("return", Keyword.RETURN); map.put("true", Keyword.TRUE); map.put("if", Keyword.IF); map.put("defined?", Keyword.DEFINED_P); map.put("super", Keyword.SUPER); map.put("undef", Keyword.UNDEF); map.put("break", Keyword.BREAK); map.put("in", Keyword.IN); map.put("do", Keyword.DO); map.put("nil", Keyword.NIL); map.put("until", Keyword.UNTIL); map.put("unless", Keyword.UNLESS); map.put("or", Keyword.OR); map.put("next", Keyword.NEXT); map.put("when", Keyword.WHEN); map.put("redo", Keyword.REDO); map.put("and", Keyword.AND); map.put("begin", Keyword.BEGIN); map.put("__LINE__", Keyword.__LINE__); map.put("class", Keyword.CLASS); map.put("__FILE__", Keyword.__FILE__); map.put("END", Keyword.LEND); map.put("BEGIN", Keyword.LBEGIN); map.put("while", Keyword.WHILE); map.put("alias", Keyword.ALIAS); map.put("__ENCODING__", Keyword.__ENCODING__); } private int getFloatToken(String number) { double d; try { d = Double.parseDouble(number); } catch (NumberFormatException e) { warnings.warn(ID.FLOAT_OUT_OF_RANGE, getPosition(), "Float " + number + " out of range.", number); d = number.startsWith("-") ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY; } yaccValue = new FloatNode(getPosition(), d); return Tokens.tFLOAT; } private Object newBignumNode(String value, int radix) { return new BignumNode(getPosition(), new BigInteger(value, radix)); } private Object newFixnumNode(String value, int radix) throws NumberFormatException { return new FixnumNode(getPosition(), Long.parseLong(value, radix)); } public enum Keyword { END ("end", Tokens.kEND, Tokens.kEND, LexState.EXPR_END), ELSE ("else", Tokens.kELSE, Tokens.kELSE, LexState.EXPR_BEG), CASE ("case", Tokens.kCASE, Tokens.kCASE, LexState.EXPR_BEG), ENSURE ("ensure", Tokens.kENSURE, Tokens.kENSURE, LexState.EXPR_BEG), MODULE ("module", Tokens.kMODULE, Tokens.kMODULE, LexState.EXPR_BEG), ELSIF ("elsif", Tokens.kELSIF, Tokens.kELSIF, LexState.EXPR_BEG), DEF ("def", Tokens.kDEF, Tokens.kDEF, LexState.EXPR_FNAME), RESCUE ("rescue", Tokens.kRESCUE, Tokens.kRESCUE_MOD, LexState.EXPR_MID), NOT ("not", Tokens.kNOT, Tokens.kNOT, LexState.EXPR_BEG), THEN ("then", Tokens.kTHEN, Tokens.kTHEN, LexState.EXPR_BEG), YIELD ("yield", Tokens.kYIELD, Tokens.kYIELD, LexState.EXPR_ARG), FOR ("for", Tokens.kFOR, Tokens.kFOR, LexState.EXPR_BEG), SELF ("self", Tokens.kSELF, Tokens.kSELF, LexState.EXPR_END), FALSE ("false", Tokens.kFALSE, Tokens.kFALSE, LexState.EXPR_END), RETRY ("retry", Tokens.kRETRY, Tokens.kRETRY, LexState.EXPR_END), RETURN ("return", Tokens.kRETURN, Tokens.kRETURN, LexState.EXPR_MID), TRUE ("true", Tokens.kTRUE, Tokens.kTRUE, LexState.EXPR_END), IF ("if", Tokens.kIF, Tokens.kIF_MOD, LexState.EXPR_BEG), DEFINED_P ("defined?", Tokens.kDEFINED, Tokens.kDEFINED, LexState.EXPR_ARG), SUPER ("super", Tokens.kSUPER, Tokens.kSUPER, LexState.EXPR_ARG), UNDEF ("undef", Tokens.kUNDEF, Tokens.kUNDEF, LexState.EXPR_FNAME), BREAK ("break", Tokens.kBREAK, Tokens.kBREAK, LexState.EXPR_MID), IN ("in", Tokens.kIN, Tokens.kIN, LexState.EXPR_BEG), DO ("do", Tokens.kDO, Tokens.kDO, LexState.EXPR_BEG), NIL ("nil", Tokens.kNIL, Tokens.kNIL, LexState.EXPR_END), UNTIL ("until", Tokens.kUNTIL, Tokens.kUNTIL_MOD, LexState.EXPR_BEG), UNLESS ("unless", Tokens.kUNLESS, Tokens.kUNLESS_MOD, LexState.EXPR_BEG), OR ("or", Tokens.kOR, Tokens.kOR, LexState.EXPR_BEG), NEXT ("next", Tokens.kNEXT, Tokens.kNEXT, LexState.EXPR_MID), WHEN ("when", Tokens.kWHEN, Tokens.kWHEN, LexState.EXPR_BEG), REDO ("redo", Tokens.kREDO, Tokens.kREDO, LexState.EXPR_END), AND ("and", Tokens.kAND, Tokens.kAND, LexState.EXPR_BEG), BEGIN ("begin", Tokens.kBEGIN, Tokens.kBEGIN, LexState.EXPR_BEG), __LINE__ ("__LINE__", Tokens.k__LINE__, Tokens.k__LINE__, LexState.EXPR_END), CLASS ("class", Tokens.kCLASS, Tokens.kCLASS, LexState.EXPR_CLASS), __FILE__("__FILE__", Tokens.k__FILE__, Tokens.k__FILE__, LexState.EXPR_END), LEND ("END", Tokens.klEND, Tokens.klEND, LexState.EXPR_END), LBEGIN ("BEGIN", Tokens.klBEGIN, Tokens.klBEGIN, LexState.EXPR_END), WHILE ("while", Tokens.kWHILE, Tokens.kWHILE_MOD, LexState.EXPR_BEG), ALIAS ("alias", Tokens.kALIAS, Tokens.kALIAS, LexState.EXPR_FNAME), __ENCODING__("__ENCODING__", Tokens.k__ENCODING__, Tokens.k__ENCODING__, LexState.EXPR_END); public final String name; public final int id0; public final int id1; public final LexState state; Keyword(String name, int id0, int id1, LexState state) { this.name = name; this.id0 = id0; this.id1 = id1; this.state = state; } } public enum LexState { EXPR_BEG, EXPR_END, EXPR_ARG, EXPR_CMDARG, EXPR_ENDARG, EXPR_MID, EXPR_FNAME, EXPR_DOT, EXPR_CLASS, EXPR_VALUE, EXPR_ENDFN } public static Keyword getKeyword(String str) { return (Keyword) map.get(str); } // Last token read via yylex(). private int token; // Value of last token which had a value associated with it. Object yaccValue; // Stream of data that yylex() examines. private LexerSource src; // Used for tiny smidgen of grammar in lexer (see setParserSupport()) private ParserSupport parserSupport = null; // What handles warnings private IRubyWarnings warnings; // Additional context surrounding tokens that both the lexer and // grammar use. private LexState lex_state; // Whether or not the lexer should be "space preserving" - see {set,get}PreserveSpaces // the parser should consider whitespace sequences and code comments to be separate // tokens to return to the client. Parsers typically do not want to see any // whitespace or comment tokens - but an IDE trying to tokenize a chunk of source code // does want to identify these separately. The default, false, means the parser mode. private boolean preserveSpaces; private String encoding = null; // List of HeredocTerms to be applied when we see a new line. // This is done to be able to handle heredocs in input source order (instead of // the normal JRuby operation of handling it out of order by stashing the rest of // the line on the side while searching for the end of the heredoc, and then pushing // the line back on the input before proceeding). Out-of-order handling of tokens // is difficult for the IDE to handle, so in syntax highlighting mode we process the // output differently. When we see a heredoc token, we return a normal string-begin // token, but we also push the heredoc term (without line-state) into the "newline-list" // and continue processing normally (with no string strterm in effect). // Whenever we get to a new line, we look at the newline list, and if we find something // there, we pull it off and set it as the current string term and use it to process // the string literal and end token. // NOTE:: This list should not be modified but rather duplicated, in order to ensure // that incremental lexing (which relies on pulling out these lists at token boundaries) // will not interfere with each other. public static class HeredocContext { private HeredocTerm[] heredocTerms; private boolean[] lookingForEnds; public HeredocContext(HeredocTerm term) { heredocTerms = new HeredocTerm[] {term, term}; lookingForEnds = new boolean[] {false, true}; } private HeredocContext(HeredocTerm[] terms, boolean[] lookingForEnds) { heredocTerms = terms; this.lookingForEnds = lookingForEnds; } private HeredocContext add(HeredocTerm h) { // Add 2 entries: one for starting lexing of the string, one for the end token HeredocTerm[] copy = new HeredocTerm[heredocTerms.length + 2]; System.arraycopy(heredocTerms, 0, copy, 0, heredocTerms.length); copy[heredocTerms.length] = h; copy[heredocTerms.length + 1] = h; boolean[] copy2 = new boolean[lookingForEnds.length + 2]; System.arraycopy(lookingForEnds, 0, copy2, 0, lookingForEnds.length); copy2[lookingForEnds.length] = false; copy2[lookingForEnds.length + 1] = true; return new HeredocContext(copy, copy2); } private HeredocTerm getTerm() { return heredocTerms[0]; } private HeredocContext pop() { if (heredocTerms.length > 1) { HeredocTerm[] copy = new HeredocTerm[heredocTerms.length - 1]; System.arraycopy(heredocTerms, 1, copy, 0, copy.length); boolean[] copy2 = new boolean[lookingForEnds.length - 1]; System.arraycopy(lookingForEnds, 1, copy2, 0, copy2.length); HeredocContext hc = new HeredocContext(copy, copy2); return hc; } return null; } public boolean isLookingForEnd() { return lookingForEnds[0]; } @Override public String toString() { CStringBuilder buffer = new CStringBuilder("HeredocContext(count="); buffer.append(Integer.toString(heredocTerms.length)); buffer.append("):"); for (int i = 0; i < heredocTerms.length; i++) { if (i > 0) buffer.append(","); buffer.append("end:").append(lookingForEnds[i]); buffer.append(",term:").append(heredocTerms[i]); } return buffer.toString(); } @Override public int hashCode() { return heredocTerms[0].getMutableState().hashCode(); } @Override public boolean equals(Object other) { if (other instanceof HeredocContext) { HeredocContext o = (HeredocContext) other; if (o.heredocTerms.length != heredocTerms.length) return false; return heredocTerms[0].getMutableState().equals(o.heredocTerms[0].getMutableState()); } return false; } } public HeredocContext heredocContext; // Tempory buffer to build up a potential token. Consumer takes responsibility to reset // this before use. private CStringBuilder tokenBuffer = new CStringBuilder(60); private StackState conditionState = new StackState(); private StackState cmdArgumentState = new StackState(); private StrTerm lex_strterm; public boolean commandStart; // Whether we're processing comments private boolean doComments; // Give a name to a value. Enebo: This should be used more. static final int EOF = -1; // ruby constants for strings (should this be moved somewhere else?) static final int STR_FUNC_ESCAPE=0x01; static final int STR_FUNC_EXPAND=0x02; static final int STR_FUNC_REGEXP=0x04; static final int STR_FUNC_QWORDS=0x08; static final int STR_FUNC_SYMBOL=0x10; // When the heredoc identifier specifies <<-EOF that indents before ident. are ok (the '-'). static final int STR_FUNC_INDENT=0x20; private static final int str_squote = 0; private static final int str_dquote = STR_FUNC_EXPAND; private static final int str_xquote = STR_FUNC_EXPAND; private static final int str_regexp = STR_FUNC_REGEXP | STR_FUNC_ESCAPE | STR_FUNC_EXPAND; private static final int str_ssym = STR_FUNC_SYMBOL; private static final int str_dsym = STR_FUNC_SYMBOL | STR_FUNC_EXPAND; // Are we lexing Ruby 1.8 or 1.9+ syntax private boolean isOneEight; // Count of nested parentheses (1.9 only) private int parenNest = 0; // 1.9 only private int leftParenBegin = 0; /* In normal JRuby, there is a "spaceSeen" flag which is local to yylex. It is * used to interpret input based on whether a space was recently seen. * Since I now bail -out- of yylex() when I see space, I need to be able * to preserve this flag across yylex() calls. In most cases, "spaceSeen" * should be set to false (as it previous was at the beginning of yylex(). * However, when I've seen a space and have bailed out, I need to set spaceSeen=true * on the next call to yylex(). This is what the following flag is all about. * It is set to true when we bail out on space (or other states that didn't * previous bail out and spaceSeen is true). */ private boolean setSpaceSeen; /** * Set whether or not the lexer should be "space preserving" - in other words, whether * the parser should consider whitespace sequences and code comments to be separate * tokens to return to the client. Parsers typically do not want to see any * whitespace or comment tokens - but an IDE trying to tokenize a chunk of source code * does want to identify these separately. The default, false, means the parser mode. * * @param preserveSpaces If true, return space and comment sequences as tokens, if false, skip these * @see #getPreserveSpaces */ public void setPreserveSpaces(final boolean preserveSpaces) { this.preserveSpaces = preserveSpaces; } /** * Return whether or not the lexer should be "space preserving". For a description * of what this means, see {@link #setPreserveSpaces}. * * @return preserveSpaces True iff space and comment sequences will be returned as * tokens, and false otherwise. * * @see #setPreserveSpaces */ public boolean getPreserveSpaces() { return preserveSpaces; } public LexState getLexState() { return lex_state; } public void setLexState(final LexState lex_state) { this.lex_state = lex_state; } public boolean isSetSpaceSeen() { return setSpaceSeen; } public void setSpaceSeen(boolean setSpaceSeen) { this.setSpaceSeen = setSpaceSeen; } public boolean isCommandStart() { return commandStart; } public void setCommandStart(boolean commandStart) { this.commandStart = commandStart; } public LexerSource getSource() { return this.src; } public int incrementParenNest() { parenNest++; return parenNest; } public int getLeftParenBegin() { return leftParenBegin; } public void setLeftParenBegin(int value) { leftParenBegin = value; } public Lexer() { this(true); } public Lexer(boolean isOneEight) { reset(); this.isOneEight = isOneEight; } public void reset() { token = 0; yaccValue = null; src = null; setState(null); resetStacks(); lex_strterm = null; commandStart = true; } /** * How the parser advances to the next token. * * @return true if not at end of file (EOF). */ public boolean advance() throws IOException { return (token = yylex()) != EOF; } public int nextToken() throws IOException { token = yylex(); return token == EOF ? 0 : token; } /** * Last token read from the lexer at the end of a call to yylex() * * @return last token read */ public int token() { return token; } public CStringBuilder getTokenBuffer() { return tokenBuffer; } /** * Value of last token (if it is a token which has a value). * * @return value of last value-laden token */ public Object value() { return yaccValue; } /** * Get position information for Token/Node that follows node represented by startPosition * and current lexer location. * * @param startPosition previous node/token * @param inclusive include previous node into position information of current node * @return a new position */ public SourcePosition getPosition(SourcePosition startPosition, boolean inclusive) { return src.getPosition(startPosition, inclusive); } public SourcePosition getPosition() { return src.getPosition(null, false); } public String getCurrentLine() { return null; // TODO: Add currentLine? // return src.getCurrentLine(); } public void setEncoding(String encoding) { this.encoding = encoding; } public String getEncoding() { return encoding; } /** * Parse must pass its support object for some check at bottom of * yylex(). Ruby does it this way as well (i.e. a little parsing * logic in the lexer). * * @param parserSupport */ public void setParserSupport(ParserSupport parserSupport) { this.parserSupport = parserSupport; // TODO: Probably don't need this either if (parserSupport.getConfiguration() != null) { this.doComments = true; } } /** * Allow the parser to set the source for its lexer. * * @param source where the lexer gets raw data */ public void setSource(LexerSource source) { this.src = source; } public StrTerm getStrTerm() { return lex_strterm; } public void setStrTerm(StrTerm strterm) { this.lex_strterm = strterm; } public void resetStacks() { conditionState.reset(); cmdArgumentState.reset(); } public void setWarnings(IRubyWarnings warnings) { this.warnings = warnings; } private void printState() { if (lex_state == null) { System.out.println("NULL"); } else { System.out.println(lex_state); } } public void setState(LexState state) { this.lex_state = state; // printState(); } public StackState getCmdArgumentState() { return cmdArgumentState; } public boolean isOneEight() { return isOneEight; } public StackState getConditionState() { return conditionState; } public void setValue(Object yaccValue) { this.yaccValue = yaccValue; } private boolean isNext_identchar() throws IOException { int c = src.read(); src.unread(c); return c != EOF && (Character.isLetterOrDigit(c) || c == '_'); } private boolean isBEG() { return lex_state == LexState.EXPR_BEG || lex_state == LexState.EXPR_MID || lex_state == LexState.EXPR_CLASS || (!isOneEight && lex_state == LexState.EXPR_VALUE); } private boolean isEND() { return lex_state == LexState.EXPR_END || lex_state == LexState.EXPR_ENDARG || (!isOneEight && lex_state == LexState.EXPR_ENDFN); } private boolean isARG() { return lex_state == LexState.EXPR_ARG || lex_state == LexState.EXPR_CMDARG; } private void determineExpressionState() { switch (lex_state) { case EXPR_FNAME: case EXPR_DOT: setState(LexState.EXPR_ARG); break; default: setState(LexState.EXPR_BEG); break; } } private Object getInteger(String value, int radix) { try { return newFixnumNode(value, radix); } catch (NumberFormatException e) { return newBignumNode(value, radix); } } /** * @param c the character to test * @return true if character is a hex value (0-9a-f) */ static boolean isHexChar(int c) { return Character.isDigit(c) || ('a' <= c && c <= 'f') || ('A' <= c && c <= 'F'); } /** * @param c the character to test * @return true if character is an octal value (0-7) */ static boolean isOctChar(int c) { return '0' <= c && c <= '7'; } /** * This is a valid character for an identifier? * * @param c is character to be compared * @return whether c is an identifier or not * * mri: is_identchar */ public boolean isIdentifierChar(int c) { return Character.isLetterOrDigit(c) || c == '_'; } /** * What type/kind of quote are we dealing with? * * @param c first character the the quote construct * @return a token that specifies the quote type */ private int parseQuote(int c) throws IOException { int begin, end; boolean shortHand; // Short-hand (e.g. %{,%.,%!,... versus %Q{). if (!Character.isLetterOrDigit(c)) { begin = c; c = 'Q'; shortHand = true; // Long-hand (e.g. %Q{}). } else { shortHand = false; begin = src.read(); if (Character.isLetterOrDigit(begin) /* no mb || ismbchar(term)*/) { throw new SyntaxException(PID.STRING_UNKNOWN_TYPE, getPosition(), getCurrentLine(), "unknown type of %string"); } } if (c == EOF || begin == EOF) { throw new SyntaxException(PID.STRING_HITS_EOF, getPosition(), getCurrentLine(), "unterminated quoted string meets end of file"); } // Figure end-char. '\0' is special to indicate begin=end and that no nesting? switch(begin) { case '(': end = ')'; break; case '[': end = ']'; break; case '{': end = '}'; break; case '<': end = '>'; break; default: end = begin; begin = '\0'; } switch (c) { case 'Q': lex_strterm = new StringTerm(str_dquote, begin ,end); yaccValue = new Token("%"+ (shortHand ? (""+end) : ("" + c + begin)), getPosition()); return Tokens.tSTRING_BEG; case 'q': lex_strterm = new StringTerm(str_squote, begin, end); yaccValue = new Token("%"+c+begin, getPosition()); return Tokens.tSTRING_BEG; case 'W': lex_strterm = new StringTerm(str_dquote | STR_FUNC_QWORDS, begin, end); do {c = src.read();} while (Character.isWhitespace(c)); src.unread(c); yaccValue = new Token("%"+c+begin, getPosition()); return Tokens.tWORDS_BEG; case 'w': lex_strterm = new StringTerm(/* str_squote | */ STR_FUNC_QWORDS, begin, end); do {c = src.read();} while (Character.isWhitespace(c)); src.unread(c); yaccValue = new Token("%"+c+begin, getPosition()); return Tokens.tQWORDS_BEG; case 'x': lex_strterm = new StringTerm(str_xquote, begin, end); yaccValue = new Token("%"+c+begin, getPosition()); return Tokens.tXSTRING_BEG; case 'r': lex_strterm = new StringTerm(str_regexp, begin, end); yaccValue = new Token("%"+c+begin, getPosition()); return Tokens.tREGEXP_BEG; case 's': lex_strterm = new StringTerm(str_ssym, begin, end); setState(LexState.EXPR_FNAME); yaccValue = new Token("%"+c+begin, getPosition()); return Tokens.tSYMBEG; default: throw new SyntaxException(PID.STRING_UNKNOWN_TYPE, getPosition(), getCurrentLine(), "Unknown type of %string. Expected 'Q', 'q', 'w', 'x', 'r' or any non letter character, but found '" + c + "'."); } } private int hereDocumentIdentifier() throws IOException { int c = src.read(); int term; int func = 0; if (c == '-') { c = src.read(); func = STR_FUNC_INDENT; } CStringBuilder markerValue; if (c == '\'' || c == '"' || c == '`') { if (c == '\'') { func |= str_squote; } else if (c == '"') { func |= str_dquote; } else { func |= str_xquote; } markerValue = new CStringBuilder(); term = c; while ((c = src.read()) != EOF && c != term) { markerValue.append(c); } if (c == EOF) { throw new SyntaxException(PID.STRING_MARKER_MISSING, getPosition(), getCurrentLine(), "unterminated here document identifier"); } } else { if (!isIdentifierChar(c)) { src.unread(c); if ((func & STR_FUNC_INDENT) != 0) { src.unread('-'); } return 0; } markerValue = new CStringBuilder(); term = '"'; func |= str_dquote; do { markerValue.append(c); } while ((c = src.read()) != EOF && isIdentifierChar(c)); src.unread(c); } // See issue nb #93990 // It is very difficult for the IDE (especially with incremental lexing) // to handle heredocs with additional input on the line, where the // input end up getting processed out of order (JRuby will read the rest // of the line, process up to the end token, then stash the rest of the line // back on the input and continue (which could process another heredoc) // and then just jump over the heredocs since input is processed out of order. // Instead, use our own HeredocTerms which behave differently; they don't // mess with the output, and will be handled differently from within // the lexer in that it gets invited back on the next line (in order) if (preserveSpaces) { HeredocTerm h = new HeredocTerm(markerValue.toString(), func, null); if (term == '`') { yaccValue = new Token("`", getPosition()); return Tokens.tXSTRING_BEG; } yaccValue = new Token("\"", getPosition()); if (heredocContext == null) { heredocContext = new HeredocContext(h); } else { heredocContext = heredocContext.add(h); } return Tokens.tSTRING_BEG; } String lastLine = src.readLineBytes(); lastLine = lastLine.concat("\n"); lex_strterm = new HeredocTerm(markerValue.toString(), func, lastLine); if (term == '`') { yaccValue = new Token("`", getPosition()); return Tokens.tXSTRING_BEG; } yaccValue = new Token("\"", getPosition()); // Hacky: Advance position to eat newline here.... getPosition(); return Tokens.tSTRING_BEG; } private void arg_ambiguous() { if (warnings.isVerbose()) warnings.warning(ID.AMBIGUOUS_ARGUMENT, getPosition(), "Ambiguous first argument; make sure."); } /* MRI: magic_comment_marker */ /* This impl is a little sucky. We basically double scan the same bytelist twice. Once here * and once in parseMagicComment. */ private int magicCommentMarker(String str, int begin) { int i = begin; int len = str.length(); while (i < len) { switch (str.charAt(i)) { case '-': if (i >= 2 && str.charAt(i - 1) == '*' && str.charAt(i - 2) == '-') return i + 1; i += 2; break; case '*': if (i + 1 >= len) return -1; if (str.charAt(i + 1) != '-') { i += 4; } else if (str.charAt(i - 1) != '-') { i += 2; } else { return i + 2; } break; default: i += 3; break; } } return -1; } private boolean magicCommentSpecialChar(char c) { switch (c) { case '\'': case '"': case ':': case ';': return true; } return false; } private static final String magicString = "([^\\s\'\":;]+)\\s*:\\s*(\"(?:\\\\.|[^\"])*\"|[^\"\\s;]+)[\\s;]*"; private static final Pattern magicRegexp = Pattern.compile(magicString); // MRI: parser_magic_comment protected boolean parseMagicComment(String magicLine) throws IOException { int length = magicLine.length(); if (length <= 7) return false; int beg = magicCommentMarker(magicLine, 0); if (beg < 0) return false; int end = magicCommentMarker(magicLine, beg); if (end < 0) return false; // We only use a regex if -*- ... -*- is found. Not too hot a path? int realSize = magicLine.length(); Matcher matcher = magicRegexp.matcher(magicLine); boolean result = matcher.find(beg); if (!result) return false; String name = matcher.group(1); if (!name.equalsIgnoreCase("encoding")) return false; setEncoding(matcher.group(2)); return true; } // TODO: Make hand-rolled version of this private static final String encodingString = "[cC][oO][dD][iI][nN][gG]\\s*[=:]\\s*([a-zA-Z0-9\\-_]+)"; private static final Pattern encodingRegexp = Pattern.compile(encodingString); protected void handleFileEncodingComment(String encodingLine) throws IOException { Matcher matcher = encodingRegexp.matcher(encodingLine); boolean result = matcher.find(); if (!result) return; setEncoding(matcher.group(1)); } /** * Read a comment up to end of line. When found each comment will get stored away into * the parser result so that any interested party can use them as they seem fit. One idea * is that IDE authors can do distance based heuristics to associate these comments to the * AST node they think they belong to. * * @param c last character read from lexer source * @return newline or eof value */ protected int readComment(int c) throws IOException { if (doComments) { return readCommentLong(c); } return src.skipUntil('\n'); } private int readCommentLong(int c) throws IOException { SourcePosition startPosition = src.getPosition(); tokenBuffer.setLength(0); tokenBuffer.append(c); // FIXME: Consider making a better LexerSource.readLine while ((c = src.read()) != '\n') { if (c == EOF) break; tokenBuffer.append(c); } src.unread(c); // ENEBO: When is parserSupport actually null? if (parserSupport != null) { // Store away each comment to parser result so IDEs can do whatever they want with them. SourcePosition position = startPosition.union(getPosition()); parserSupport.getResult().addComment(new CommentNode(position, tokenBuffer.toString())); } else { getPosition(); } return c; } /* * Not normally used, but is left in here since it can be useful in debugging * grammar and lexing problems. * */ private void printToken(int token) { //System.out.print("LOC: " + support.getPosition() + " ~ "); switch (token) { case Tokens.yyErrorCode: System.err.print("yyErrorCode,"); break; case Tokens.kCLASS: System.err.print("kClass,"); break; case Tokens.kMODULE: System.err.print("kModule,"); break; case Tokens.kDEF: System.err.print("kDEF,"); break; case Tokens.kUNDEF: System.err.print("kUNDEF,"); break; case Tokens.kBEGIN: System.err.print("kBEGIN,"); break; case Tokens.kRESCUE: System.err.print("kRESCUE,"); break; case Tokens.kENSURE: System.err.print("kENSURE,"); break; case Tokens.kEND: System.err.print("kEND,"); break; case Tokens.kIF: System.err.print("kIF,"); break; case Tokens.kUNLESS: System.err.print("kUNLESS,"); break; case Tokens.kTHEN: System.err.print("kTHEN,"); break; case Tokens.kELSIF: System.err.print("kELSIF,"); break; case Tokens.kELSE: System.err.print("kELSE,"); break; case Tokens.kCASE: System.err.print("kCASE,"); break; case Tokens.kWHEN: System.err.print("kWHEN,"); break; case Tokens.kWHILE: System.err.print("kWHILE,"); break; case Tokens.kUNTIL: System.err.print("kUNTIL,"); break; case Tokens.kFOR: System.err.print("kFOR,"); break; case Tokens.kBREAK: System.err.print("kBREAK,"); break; case Tokens.kNEXT: System.err.print("kNEXT,"); break; case Tokens.kREDO: System.err.print("kREDO,"); break; case Tokens.kRETRY: System.err.print("kRETRY,"); break; case Tokens.kIN: System.err.print("kIN,"); break; case Tokens.kDO: System.err.print("kDO,"); break; case Tokens.kDO_COND: System.err.print("kDO_COND,"); break; case Tokens.kDO_BLOCK: System.err.print("kDO_BLOCK,"); break; case Tokens.kRETURN: System.err.print("kRETURN,"); break; case Tokens.kYIELD: System.err.print("kYIELD,"); break; case Tokens.kSUPER: System.err.print("kSUPER,"); break; case Tokens.kSELF: System.err.print("kSELF,"); break; case Tokens.kNIL: System.err.print("kNIL,"); break; case Tokens.kTRUE: System.err.print("kTRUE,"); break; case Tokens.kFALSE: System.err.print("kFALSE,"); break; case Tokens.kAND: System.err.print("kAND,"); break; case Tokens.kOR: System.err.print("kOR,"); break; case Tokens.kNOT: System.err.print("kNOT,"); break; case Tokens.kIF_MOD: System.err.print("kIF_MOD,"); break; case Tokens.kUNLESS_MOD: System.err.print("kUNLESS_MOD,"); break; case Tokens.kWHILE_MOD: System.err.print("kWHILE_MOD,"); break; case Tokens.kUNTIL_MOD: System.err.print("kUNTIL_MOD,"); break; case Tokens.kRESCUE_MOD: System.err.print("kRESCUE_MOD,"); break; case Tokens.kALIAS: System.err.print("kALIAS,"); break; case Tokens.kDEFINED: System.err.print("kDEFINED,"); break; case Tokens.klBEGIN: System.err.print("klBEGIN,"); break; case Tokens.klEND: System.err.print("klEND,"); break; case Tokens.k__LINE__: System.err.print("k__LINE__,"); break; case Tokens.k__FILE__: System.err.print("k__FILE__,"); break; case Tokens.k__ENCODING__: System.err.print("k__ENCODING__,"); break; case Tokens.kDO_LAMBDA: System.err.print("kDO_LAMBDA,"); break; case Tokens.tIDENTIFIER: System.err.print("tIDENTIFIER["+ value() + "],"); break; case Tokens.tFID: System.err.print("tFID[" + value() + "],"); break; case Tokens.tGVAR: System.err.print("tGVAR[" + value() + "],"); break; case Tokens.tIVAR: System.err.print("tIVAR[" + value() +"],"); break; case Tokens.tCONSTANT: System.err.print("tCONSTANT["+ value() +"],"); break; case Tokens.tCVAR: System.err.print("tCVAR,"); break; case Tokens.tINTEGER: System.err.print("tINTEGER,"); break; case Tokens.tFLOAT: System.err.print("tFLOAT,"); break; case Tokens.tSTRING_CONTENT: System.err.print("tSTRING_CONTENT[" + ((StrNode) value()).getValue().toString() + "],"); break; case Tokens.tSTRING_BEG: System.err.print("tSTRING_BEG,"); break; case Tokens.tSTRING_END: System.err.print("tSTRING_END,"); break; case Tokens.tSTRING_DBEG: System.err.print("STRING_DBEG,"); break; case Tokens.tSTRING_DVAR: System.err.print("tSTRING_DVAR,"); break; case Tokens.tXSTRING_BEG: System.err.print("tXSTRING_BEG,"); break; case Tokens.tREGEXP_BEG: System.err.print("tREGEXP_BEG,"); break; case Tokens.tREGEXP_END: System.err.print("tREGEXP_END,"); break; case Tokens.tWORDS_BEG: System.err.print("tWORDS_BEG,"); break; case Tokens.tQWORDS_BEG: System.err.print("tQWORDS_BEG,"); break; case Tokens.tBACK_REF: System.err.print("tBACK_REF,"); break; case Tokens.tBACK_REF2: System.err.print("tBACK_REF2,"); break; case Tokens.tNTH_REF: System.err.print("tNTH_REF,"); break; case Tokens.tUPLUS: System.err.print("tUPLUS"); break; case Tokens.tUMINUS: System.err.print("tUMINUS,"); break; case Tokens.tPOW: System.err.print("tPOW,"); break; case Tokens.tCMP: System.err.print("tCMP,"); break; case Tokens.tEQ: System.err.print("tEQ,"); break; case Tokens.tEQQ: System.err.print("tEQQ,"); break; case Tokens.tNEQ: System.err.print("tNEQ,"); break; case Tokens.tGEQ: System.err.print("tGEQ,"); break; case Tokens.tLEQ: System.err.print("tLEQ,"); break; case Tokens.tANDOP: System.err.print("tANDOP,"); break; case Tokens.tOROP: System.err.print("tOROP,"); break; case Tokens.tMATCH: System.err.print("tMATCH,"); break; case Tokens.tNMATCH: System.err.print("tNMATCH,"); break; case Tokens.tDOT: System.err.print("tDOT,"); break; case Tokens.tDOT2: System.err.print("tDOT2,"); break; case Tokens.tDOT3: System.err.print("tDOT3,"); break; case Tokens.tAREF: System.err.print("tAREF,"); break; case Tokens.tASET: System.err.print("tASET,"); break; case Tokens.tLSHFT: System.err.print("tLSHFT,"); break; case Tokens.tRSHFT: System.err.print("tRSHFT,"); break; case Tokens.tCOLON2: System.err.print("tCOLON2,"); break; case Tokens.tCOLON3: System.err.print("tCOLON3,"); break; case Tokens.tOP_ASGN: System.err.print("tOP_ASGN,"); break; case Tokens.tASSOC: System.err.print("tASSOC,"); break; case Tokens.tLPAREN: System.err.print("tLPAREN,"); break; case Tokens.tLPAREN2: System.err.print("tLPAREN2,"); break; case Tokens.tLPAREN_ARG: System.err.print("tLPAREN_ARG,"); break; case Tokens.tLBRACK: System.err.print("tLBRACK,"); break; case Tokens.tRBRACK: System.err.print("tRBRACK,"); break; case Tokens.tLBRACE: System.err.print("tLBRACE,"); break; case Tokens.tLBRACE_ARG: System.err.print("tLBRACE_ARG,"); break; case Tokens.tSTAR: System.err.print("tSTAR,"); break; case Tokens.tSTAR2: System.err.print("tSTAR2,"); break; case Tokens.tAMPER: System.err.print("tAMPER,"); break; case Tokens.tAMPER2: System.err.print("tAMPER2,"); break; case Tokens.tSYMBEG: System.err.print("tSYMBEG,"); break; case Tokens.tTILDE: System.err.print("tTILDE,"); break; case Tokens.tPERCENT: System.err.print("tPERCENT,"); break; case Tokens.tDIVIDE: System.err.print("tDIVIDE,"); break; case Tokens.tPLUS: System.err.print("tPLUS,"); break; case Tokens.tMINUS: System.err.print("tMINUS,"); break; case Tokens.tLT: System.err.print("tLT,"); break; case Tokens.tGT: System.err.print("tGT,"); break; case Tokens.tCARET: System.err.print("tCARET,"); break; case Tokens.tBANG: System.err.print("tBANG,"); break; case Tokens.tLCURLY: System.err.print("tTLCURLY,"); break; case Tokens.tRCURLY: System.err.print("tRCURLY,"); break; case Tokens.tPIPE: System.err.print("tTPIPE,"); break; case Tokens.tLAMBDA: System.err.print("tLAMBDA,"); break; case Tokens.tLAMBEG: System.err.print("tLAMBEG,"); break; case Tokens.tRPAREN: System.err.print("tRPAREN,"); break; case Tokens.tLABEL: System.err.print("tLABEL("+ ((Token) value()).getValue() +":),"); break; case '\n': System.err.println("NL"); break; case EOF: System.out.println("EOF"); break; default: System.err.print("'" + (char)token + "',"); break; } } // DEBUGGING HELP private int yylex2() throws IOException { int currentToken = yylex(); printToken(currentToken); return currentToken; } /** * Returns the next token. Also sets yyVal is needed. * *@return Description of the Returned Value */ private int yylex() throws IOException { int c; boolean spaceSeen = false; boolean commandState; if (setSpaceSeen) { spaceSeen = true; setSpaceSeen = false; } // On new lines, possibly resume heredoc processing (see docs for newlineTerms for more) if (heredocContext != null) { if (heredocContext.isLookingForEnd()) { lex_strterm = heredocContext.getTerm(); } else if (src.isANewLine()) { lex_strterm = heredocContext.getTerm(); heredocContext = heredocContext.pop(); } } if (lex_strterm != null) { try { int tok = lex_strterm.parseString(this, src); if (tok == Tokens.tSTRING_END || tok == Tokens.tREGEXP_END) { lex_strterm = null; setState(LexState.EXPR_END); if (heredocContext != null && heredocContext.isLookingForEnd()) { heredocContext = heredocContext.pop(); } } return tok; } catch (SyntaxException se) { // If we abort in string parsing, throw away the str term // such that we don't try again on restart lex_strterm = null; setState(LexState.EXPR_END); throw se; } } commandState = commandStart; commandStart = false; loop: for(;;) { c = src.read(); switch(c) { case '\004': /* ^D */ case '\032': /* ^Z */ case EOF: /* end of script. */ return EOF; /* white spaces */ case ' ': case '\t': case '\f': case '\r': case '\13': /* '\v' */ if (preserveSpaces) { // Collapse all whitespace into one token while (true) { c = src.read(); if (c != ' ' && c != '\t' && c != '\f' && c != '\r' && c != '\13') break; } src.unread(c); yaccValue = new Token("whitespace", getPosition()); setSpaceSeen = true; return Tokens.tWHITESPACE; } getPosition(); spaceSeen = true; continue; case '#': /* it's a comment */ if (preserveSpaces) { // Skip to end of the comment while ((c = src.read()) != '\n') { if (c == EOF) break; } yaccValue = new Token("line-comment", getPosition()); setSpaceSeen = spaceSeen; // Ensure that commandStart and lex_state is updated // as it otherwise would have if preserveSpaces was false if (!(lex_state == LexState.EXPR_BEG || lex_state == LexState.EXPR_FNAME || lex_state == LexState.EXPR_DOT || lex_state == LexState.EXPR_CLASS)) { commandStart = true; setState(LexState.EXPR_BEG); } return Tokens.tCOMMENT; } else { // FIXME: Need to detect magic_comment in 1.9 here for encoding if (readComment(c) == EOF) return EOF; } /* fall through */ case '\n': if (isOneEight) { // Replace a string of newlines with a single one while((c = src.read()) == '\n'); } else { switch (lex_state) { case EXPR_BEG: case EXPR_FNAME: case EXPR_DOT: case EXPR_CLASS: case EXPR_VALUE: getPosition(); continue loop; } boolean done = false; while(!done) { c = src.read(); switch (c) { case ' ': case '\t': case '\f': case '\r': case '\13': /* '\v' */ spaceSeen = true; continue; case '.': { if ((c = src.read()) != '.') { src.unread(c); src.unread('.'); continue loop; } } default: case -1: // EOF (ENEBO: After default? done = true; } } } if (c == -1 && !preserveSpaces) return EOF; src.unread(c); getPosition(); if (preserveSpaces) { src.setIsANewLine(true); yaccValue = new Token("whitespace", getPosition()); // Ensure that commandStart and lex_state is updated // as it otherwise would have if preserveSpaces was false if (!(lex_state == LexState.EXPR_BEG || lex_state == LexState.EXPR_FNAME || lex_state == LexState.EXPR_DOT || lex_state == LexState.EXPR_CLASS)) { commandStart = true; setState(LexState.EXPR_BEG); } return Tokens.tWHITESPACE; } switch (lex_state) { case EXPR_BEG: case EXPR_FNAME: case EXPR_DOT: case EXPR_CLASS: continue loop; } commandStart = true; setState(LexState.EXPR_BEG); return '\n'; case '*': return star(spaceSeen); case '!': return bang(); case '=': // documentation nodes if (src.wasBeginOfLine()) { - boolean doComments = preserveSpaces; if (src.matchMarker(BEGIN_DOC_MARKER, false, false)) { + SourcePosition startPosition = src.getPosition(); if (doComments) { tokenBuffer.setLength(0); + tokenBuffer.append('='); tokenBuffer.append(BEGIN_DOC_MARKER); } c = src.read(); if (Character.isWhitespace(c)) { // In case last next was the newline. src.unread(c); for (;;) { c = src.read(); if (doComments) tokenBuffer.append(c); // If a line is followed by a blank line put // it back. while (c == '\n') { c = src.read(); if (doComments) tokenBuffer.append(c); } if (c == EOF) { throw new SyntaxException(PID.STRING_HITS_EOF, getPosition(), getCurrentLine(), "embedded document meets end of file"); } if (c != '=') continue; if (src.wasBeginOfLine() && src.matchMarker(END_DOC_MARKER, false, false)) { if (doComments) tokenBuffer.append(END_DOC_MARKER); String list = src.readLineBytes(); if (doComments) tokenBuffer.append(list); src.unread('\n'); break; } } if (doComments) { - yaccValue = new Token("here-doc", getPosition()); + // Store away each comment to parser result so IDEs can do whatever they want with them. + SourcePosition position = startPosition.union(getPosition()); + parserSupport.getResult().addComment(new CommentNode(position, tokenBuffer.toString())); + } + if (preserveSpaces) { + yaccValue = new Token("here-doc", getPosition()); return Tokens.tDOCUMENTATION; -// parserSupport.getResult().addComment(new CommentNode(getPosition(), tokenBuffer.toString())); } continue; } src.unread(c); } } determineExpressionState(); c = src.read(); if (c == '=') { c = src.read(); if (c == '=') { yaccValue = new Token("===", getPosition()); return Tokens.tEQQ; } src.unread(c); yaccValue = new Token("==", getPosition()); return Tokens.tEQ; } if (c == '~') { yaccValue = new Token("=~", getPosition()); return Tokens.tMATCH; } else if (c == '>') { yaccValue = new Token("=>", getPosition()); return Tokens.tASSOC; } src.unread(c); yaccValue = new Token("=", getPosition()); return '='; case '<': return lessThan(spaceSeen); case '>': return greaterThan(); case '"': return doubleQuote(); case '`': return backtick(commandState); case '\'': return singleQuote(); case '?': return questionMark(); case '&': return ampersand(spaceSeen); case '|': return pipe(); case '+': return plus(spaceSeen); case '-': return minus(spaceSeen); case '.': return dot(); case '0' : case '1' : case '2' : case '3' : case '4' : case '5' : case '6' : case '7' : case '8' : case '9' : return parseNumber(c); case ')': return rightParen(); case ']': return rightBracket(); case '}': return rightCurly(); case ':': return colon(spaceSeen); case '/': return slash(spaceSeen); case '^': return caret(); case ';': commandStart = true; if (!isOneEight) { setState(LexState.EXPR_BEG); yaccValue = new Token(";", getPosition()); return ';'; } case ',': return comma(c); case '~': return tilde(); case '(': return leftParen(spaceSeen); case '[': return leftBracket(spaceSeen); case '{': return leftCurly(); case '\\': c = src.read(); if (c == '\n') { spaceSeen = true; continue; } src.unread(c); yaccValue = new Token("\\", getPosition()); return '\\'; case '%': return percent(spaceSeen); case '$': return dollar(); case '@': return at(); case '_': if (src.wasBeginOfLine() && src.matchMarker(END_MARKER, false, true)) { if (parserSupport != null) parserSupport.getResult().setEndOffset(src.getOffset()); return EOF; } return identifier(c, commandState); default: return identifier(c, commandState); } } } private int identifierToken(LexState last_state, int result, String value) { // FIXME: Parsersupport should always be hooked up. No need for null check if (result == Tokens.tIDENTIFIER && last_state != LexState.EXPR_DOT && parserSupport != null && parserSupport.getCurrentScope().isDefined(value) >= 0) { setState(LexState.EXPR_END); } yaccValue = new Token(value, result, getPosition()); return result; } private int getIdentifier(int c) throws IOException { do { tokenBuffer.append(c); /* no special multibyte character handling is needed in Java * if (ismbchar(c)) { int i, len = mbclen(c)-1; for (i = 0; i < len; i++) { c = src.read(); tokenBuffer.append(c); } }*/ c = src.read(); } while (isIdentifierChar(c)); return c; } private int ampersand(boolean spaceSeen) throws IOException { int c = src.read(); switch (c) { case '&': setState(LexState.EXPR_BEG); if ((c = src.read()) == '=') { yaccValue = new Token("&&", getPosition()); setState(LexState.EXPR_BEG); return Tokens.tOP_ASGN; } src.unread(c); yaccValue = new Token("&&", getPosition()); return Tokens.tANDOP; case '=': yaccValue = new Token("&", getPosition()); setState(LexState.EXPR_BEG); return Tokens.tOP_ASGN; } src.unread(c); //tmpPosition is required because getPosition()'s side effects. //if the warning is generated, the getPosition() on line 954 (this line + 18) will create //a wrong position if the "inclusive" flag is not set. SourcePosition tmpPosition = getPosition(); if (isARG() && spaceSeen && !Character.isWhitespace(c)) { if (warnings.isVerbose()) warnings.warning(ID.ARGUMENT_AS_PREFIX, tmpPosition, "`&' interpreted as argument prefix", "&"); c = Tokens.tAMPER; } else if (isBEG()) { c = Tokens.tAMPER; } else { c = Tokens.tAMPER2; } determineExpressionState(); yaccValue = new Token("&", tmpPosition); return c; } private int at() throws IOException { int c = src.read(); int result; tokenBuffer.setLength(0); tokenBuffer.append('@'); if (c == '@') { tokenBuffer.append('@'); c = src.read(); result = Tokens.tCVAR; } else { result = Tokens.tIVAR; } if (Character.isDigit(c)) { if (tokenBuffer.length() == 1) { throw new SyntaxException(PID.IVAR_BAD_NAME, getPosition(), getCurrentLine(), "`@" + c + "' is not allowed as an instance variable name"); } throw new SyntaxException(PID.CVAR_BAD_NAME, getPosition(), getCurrentLine(), "`@@" + c + "' is not allowed as a class variable name"); } if (!isIdentifierChar(c)) { src.unread(c); yaccValue = new Token("@", getPosition()); return '@'; } c = getIdentifier(c); src.unread(c); LexState last_state = lex_state; setState(LexState.EXPR_END); return identifierToken(last_state, result, tokenBuffer.toString().intern()); } private int backtick(boolean commandState) throws IOException { yaccValue = new Token("`", getPosition()); switch (lex_state) { case EXPR_FNAME: setState(isOneEight ? LexState.EXPR_END : LexState.EXPR_ENDFN); return Tokens.tBACK_REF2; case EXPR_DOT: setState(commandState ? LexState.EXPR_CMDARG : LexState.EXPR_ARG); return Tokens.tBACK_REF2; default: lex_strterm = new StringTerm(str_xquote, '\0', '`'); return Tokens.tXSTRING_BEG; } } private int bang() throws IOException { int c = src.read(); if (!isOneEight && (lex_state == LexState.EXPR_FNAME || lex_state == LexState.EXPR_DOT)) { setState(LexState.EXPR_ARG); if (c == '@') { yaccValue = new Token("!",getPosition()); return Tokens.tBANG; } } else { setState(LexState.EXPR_BEG); } switch (c) { case '=': yaccValue = new Token("!=",getPosition()); return Tokens.tNEQ; case '~': yaccValue = new Token("!~",getPosition()); return Tokens.tNMATCH; default: // Just a plain bang src.unread(c); yaccValue = new Token("!",getPosition()); return Tokens.tBANG; } } private int caret() throws IOException { int c = src.read(); if (c == '=') { setState(LexState.EXPR_BEG); yaccValue = new Token("^", getPosition()); return Tokens.tOP_ASGN; } determineExpressionState(); src.unread(c); yaccValue = new Token("^", getPosition()); return Tokens.tCARET; } private int colon(boolean spaceSeen) throws IOException { int c = src.read(); if (c == ':') { if (isBEG() || lex_state == LexState.EXPR_CLASS || (isARG() && spaceSeen)) { setState(LexState.EXPR_BEG); yaccValue = new Token("::", getPosition()); return Tokens.tCOLON3; } setState(LexState.EXPR_DOT); yaccValue = new Token(":",getPosition()); return Tokens.tCOLON2; } if (isEND() || Character.isWhitespace(c)) { src.unread(c); setState(LexState.EXPR_BEG); yaccValue = new Token(":",getPosition()); return ':'; } switch (c) { case '\'': lex_strterm = new StringTerm(str_ssym, '\0', c); break; case '"': lex_strterm = new StringTerm(str_dsym, '\0', c); break; default: src.unread(c); break; } setState(LexState.EXPR_FNAME); yaccValue = new Token(":", getPosition()); return Tokens.tSYMBEG; } private int comma(int c) throws IOException { setState(LexState.EXPR_BEG); yaccValue = new Token(",", getPosition()); return c; } private int doKeyword(LexState state) { commandStart = true; if (!isOneEight && leftParenBegin > 0 && leftParenBegin == parenNest) { leftParenBegin = 0; parenNest--; return Tokens.kDO_LAMBDA; } if (conditionState.isInState()) return Tokens.kDO_COND; if (state != LexState.EXPR_CMDARG && cmdArgumentState.isInState()) { return Tokens.kDO_BLOCK; } if (state == LexState.EXPR_ENDARG || (!isOneEight && state == LexState.EXPR_BEG)) { return Tokens.kDO_BLOCK; } return Tokens.kDO; } private int dollar() throws IOException { LexState last_state = lex_state; setState(LexState.EXPR_END); int c = src.read(); switch (c) { case '_': /* $_: last read line string */ c = src.read(); if (isIdentifierChar(c)) { tokenBuffer.setLength(0); tokenBuffer.append("$_"); c = getIdentifier(c); src.unread(c); last_state = lex_state; setState(LexState.EXPR_END); return identifierToken(last_state, Tokens.tGVAR, tokenBuffer.toString().intern()); } src.unread(c); c = '_'; // fall through case '~': /* $~: match-data */ case '*': /* $*: argv */ case '$': /* $$: pid */ case '?': /* $?: last status */ case '!': /* $!: error string */ case '@': /* $@: error position */ case '/': /* $/: input record separator */ case '\\': /* $\: output record separator */ case ';': /* $;: field separator */ case ',': /* $,: output field separator */ case '.': /* $.: last read line number */ case '=': /* $=: ignorecase */ case ':': /* $:: load path */ case '<': /* $<: reading filename */ case '>': /* $>: default output handle */ case '\"': /* $": already loaded files */ yaccValue = new Token("$" + (char) c, Tokens.tGVAR, getPosition()); return Tokens.tGVAR; case '-': tokenBuffer.setLength(0); tokenBuffer.append('$'); tokenBuffer.append(c); c = src.read(); if (isIdentifierChar(c)) { tokenBuffer.append(c); } else { src.unread(c); } yaccValue = new Token(tokenBuffer.toString(), Tokens.tGVAR, getPosition()); /* xxx shouldn't check if valid option variable */ return Tokens.tGVAR; case '&': /* $&: last match */ case '`': /* $`: string before last match */ case '\'': /* $': string after last match */ case '+': /* $+: string matches last paren. */ // Explicit reference to these vars as symbols... if (last_state == LexState.EXPR_FNAME) { yaccValue = new Token("$" + (char) c, Tokens.tGVAR, getPosition()); return Tokens.tGVAR; } yaccValue = new BackRefNode(getPosition(), c); return Tokens.tBACK_REF; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': tokenBuffer.setLength(0); tokenBuffer.append('$'); do { tokenBuffer.append(c); c = src.read(); } while (Character.isDigit(c)); src.unread(c); if (last_state == LexState.EXPR_FNAME) { yaccValue = new Token(tokenBuffer.toString(), Tokens.tGVAR, getPosition()); return Tokens.tGVAR; } yaccValue = new NthRefNode(getPosition(), Integer.parseInt(tokenBuffer.substring(1))); return Tokens.tNTH_REF; case '0': setState(LexState.EXPR_END); return identifierToken(last_state, Tokens.tGVAR, ("$" + (char) c).intern()); default: if (!isIdentifierChar(c)) { src.unread(c); yaccValue = new Token("$", getPosition()); return '$'; } // $blah tokenBuffer.setLength(0); tokenBuffer.append('$'); int d = getIdentifier(c); src.unread(d); last_state = lex_state; setState(LexState.EXPR_END); return identifierToken(last_state, Tokens.tGVAR, tokenBuffer.toString().intern()); } } private int dot() throws IOException { int c; setState(LexState.EXPR_BEG); if ((c = src.read()) == '.') { if ((c = src.read()) == '.') { yaccValue = new Token("...", getPosition()); return Tokens.tDOT3; } src.unread(c); yaccValue = new Token("..", getPosition()); return Tokens.tDOT2; } src.unread(c); if (Character.isDigit(c)) { throw new SyntaxException(PID.FLOAT_MISSING_ZERO, getPosition(), getCurrentLine(), "no .<digit> floating literal anymore; put 0 before dot"); } setState(LexState.EXPR_DOT); yaccValue = new Token(".", getPosition()); return Tokens.tDOT; } private int doubleQuote() throws IOException { lex_strterm = new StringTerm(str_dquote, '\0', '"'); yaccValue = new Token("\"", getPosition()); return Tokens.tSTRING_BEG; } private int greaterThan() throws IOException { determineExpressionState(); int c = src.read(); switch (c) { case '=': yaccValue = new Token(">=", getPosition()); return Tokens.tGEQ; case '>': if ((c = src.read()) == '=') { setState(LexState.EXPR_BEG); yaccValue = new Token(">>", getPosition()); return Tokens.tOP_ASGN; } src.unread(c); yaccValue = new Token(">>", getPosition()); return Tokens.tRSHFT; default: src.unread(c); yaccValue = new Token(">", getPosition()); return Tokens.tGT; } } private int identifier(int c, boolean commandState) throws IOException { if (!isIdentifierChar(c)) { String badChar = "\\" + Integer.toOctalString(c & 0xff); throw new SyntaxException(PID.CHARACTER_BAD, getPosition(), getCurrentLine(), "Invalid char `" + badChar + "' ('" + (char) c + "') in expression", badChar); } tokenBuffer.setLength(0); int first = c; // Need to undo newline status after reading too far boolean wasNewline = src.wasBeginOfLine(); c = getIdentifier(c); boolean lastBangOrPredicate = false; // methods 'foo!' and 'foo?' are possible but if followed by '=' it is relop if (c == '!' || c == '?') { if (!src.peek('=')) { lastBangOrPredicate = true; tokenBuffer.append(c); } else { src.unread(c); } } else { src.unread(c); } src.setIsANewLine(wasNewline); int result = 0; LexState last_state = lex_state; if (lastBangOrPredicate) { result = Tokens.tFID; } else { if (lex_state == LexState.EXPR_FNAME) { if ((c = src.read()) == '=') { int c2 = src.read(); if (c2 != '~' && c2 != '>' && (c2 != '=' || (c2 == '\n' && src.peek('>')))) { result = Tokens.tIDENTIFIER; tokenBuffer.append(c); src.unread(c2); } else { src.unread(c2); src.unread(c); } } else { src.unread(c); } } if (result == 0 && Character.isUpperCase(first)) { result = Tokens.tCONSTANT; } else { result = Tokens.tIDENTIFIER; } } String tempVal = tokenBuffer.toString().intern(); if (!isOneEight && ((lex_state == LexState.EXPR_BEG && !commandState) || lex_state == LexState.EXPR_ARG || lex_state == LexState.EXPR_CMDARG)) { int c2 = src.read(); if (c2 == ':' && !src.peek(':')) { src.unread(c2); setState(LexState.EXPR_BEG); src.read(); yaccValue = new Token(tempVal, getPosition()); return Tokens.tLABEL; } src.unread(c2); } if (lex_state != LexState.EXPR_DOT) { Keyword keyword = getKeyword(tempVal); // Is it is a keyword? if (keyword != null && (keyword != Keyword.__ENCODING__ || !isOneEight)) { LexState state = lex_state; // Save state at time keyword is encountered if (!isOneEight && keyword == Keyword.NOT) { setState(LexState.EXPR_ARG); } else { setState(keyword.state); } if (state == LexState.EXPR_FNAME) { yaccValue = new Token(keyword.name, getPosition()); } else { yaccValue = new Token(tempVal, getPosition()); if (keyword.id0 == Tokens.kDO) return doKeyword(state); } if (state == LexState.EXPR_BEG || (!isOneEight && state == LexState.EXPR_VALUE)) return keyword.id0; if (keyword.id0 != keyword.id1) setState(LexState.EXPR_BEG); return keyword.id1; } } if (isBEG() || lex_state == LexState.EXPR_DOT || isARG()) { setState(commandState ? LexState.EXPR_CMDARG : LexState.EXPR_ARG); } else if (!isOneEight && lex_state == LexState.EXPR_ENDFN) { setState(LexState.EXPR_ENDFN); } else { setState(LexState.EXPR_END); } return identifierToken(last_state, result, tempVal); } private int leftBracket(boolean spaceSeen) throws IOException { parenNest++; int c = '['; if (lex_state == LexState.EXPR_FNAME || lex_state == LexState.EXPR_DOT) { setState(LexState.EXPR_ARG); if ((c = src.read()) == ']') { if (src.peek('=')) { c = src.read(); yaccValue = new Token("[]=", getPosition()); return Tokens.tASET; } yaccValue = new Token("[]", getPosition()); return Tokens.tAREF; } src.unread(c); yaccValue = new Token("[", getPosition()); return '['; } else if (isBEG() || (isARG() && spaceSeen)) { c = Tokens.tLBRACK; } setState(LexState.EXPR_BEG); conditionState.stop(); cmdArgumentState.stop(); yaccValue = new Token("[", getPosition()); return c; } private int leftCurly() { if (!isOneEight && leftParenBegin > 0 && leftParenBegin == parenNest) { setState(LexState.EXPR_BEG); leftParenBegin = 0; parenNest--; conditionState.stop(); cmdArgumentState.stop(); yaccValue = new Token("{", getPosition()); return Tokens.tLAMBEG; } char c; if (isARG() || lex_state == LexState.EXPR_END || (!isOneEight && lex_state == LexState.EXPR_ENDFN)) { // block (primary) c = Tokens.tLCURLY; } else if (lex_state == LexState.EXPR_ENDARG) { // block (expr) c = Tokens.tLBRACE_ARG; } else { // hash c = Tokens.tLBRACE; } conditionState.stop(); cmdArgumentState.stop(); setState(LexState.EXPR_BEG); yaccValue = new Token("{", getPosition()); if (!isOneEight && c != Tokens.tLBRACE) commandStart = true; return c; } private int leftParen(boolean spaceSeen) throws IOException { if (isOneEight) commandStart = true; int result = Tokens.tLPAREN2; if (isBEG()) { result = Tokens.tLPAREN; } else if (spaceSeen) { // ENEBO: 1.9 is IS_ARG, but we need to break apart for 1.8 support. if (lex_state == LexState.EXPR_CMDARG) { result = Tokens.tLPAREN_ARG; } else if (lex_state == LexState.EXPR_ARG) { if (isOneEight) { warnings.warn(ID.ARGUMENT_EXTRA_SPACE, getPosition(), "don't put space before argument parentheses"); result = Tokens.tLPAREN2; } else { result = Tokens.tLPAREN_ARG; } } } parenNest++; conditionState.stop(); cmdArgumentState.stop(); setState(LexState.EXPR_BEG); yaccValue = new Token("(", getPosition()); return result; } private int lessThan(boolean spaceSeen) throws IOException { int c = src.read(); if (c == '<' && lex_state != LexState.EXPR_DOT && lex_state != LexState.EXPR_CLASS && !isEND() && (!isARG() || spaceSeen)) { int tok = hereDocumentIdentifier(); if (tok != 0) return tok; } determineExpressionState(); switch (c) { case '=': if ((c = src.read()) == '>') { yaccValue = new Token("<=>", getPosition()); return Tokens.tCMP; } src.unread(c); yaccValue = new Token("<=", getPosition()); return Tokens.tLEQ; case '<': if ((c = src.read()) == '=') { setState(LexState.EXPR_BEG); yaccValue = new Token("<<", getPosition()); return Tokens.tOP_ASGN; } src.unread(c); yaccValue = new Token("<<", getPosition()); return Tokens.tLSHFT; default: yaccValue = new Token("<", getPosition()); src.unread(c); return Tokens.tLT; } } private int minus(boolean spaceSeen) throws IOException { int c = src.read(); if (lex_state == LexState.EXPR_FNAME || lex_state == LexState.EXPR_DOT) { setState(LexState.EXPR_ARG); if (c == '@') { yaccValue = new Token("-@", getPosition()); return Tokens.tUMINUS; } src.unread(c); yaccValue = new Token("-", getPosition()); return Tokens.tMINUS; } if (c == '=') { setState(LexState.EXPR_BEG); yaccValue = new Token("-", getPosition()); return Tokens.tOP_ASGN; } if (!isOneEight && c == '>') { setState(LexState.EXPR_ARG); yaccValue = new Token("->", getPosition()); return Tokens.tLAMBDA; } if (isBEG() || (isARG() && spaceSeen && !Character.isWhitespace(c))) { if (isARG()) arg_ambiguous(); setState(LexState.EXPR_BEG); src.unread(c); yaccValue = new Token("-", getPosition()); if (Character.isDigit(c)) { return Tokens.tUMINUS_NUM; } return Tokens.tUMINUS; } setState(LexState.EXPR_BEG); src.unread(c); yaccValue = new Token("-", getPosition()); return Tokens.tMINUS; } private int percent(boolean spaceSeen) throws IOException { if (isBEG()) return parseQuote(src.read()); int c = src.read(); if (c == '=') { setState(LexState.EXPR_BEG); yaccValue = new Token("%", getPosition()); return Tokens.tOP_ASGN; } if (isARG() && spaceSeen && !Character.isWhitespace(c)) return parseQuote(c); determineExpressionState(); src.unread(c); yaccValue = new Token("%", getPosition()); return Tokens.tPERCENT; } private int pipe() throws IOException { int c = src.read(); switch (c) { case '|': setState(LexState.EXPR_BEG); if ((c = src.read()) == '=') { setState(LexState.EXPR_BEG); yaccValue = new Token("||", getPosition()); return Tokens.tOP_ASGN; } src.unread(c); yaccValue = new Token("||", getPosition()); return Tokens.tOROP; case '=': setState(LexState.EXPR_BEG); yaccValue = new Token("|", getPosition()); return Tokens.tOP_ASGN; default: determineExpressionState(); src.unread(c); yaccValue = new Token("|", getPosition()); return Tokens.tPIPE; } } private int plus(boolean spaceSeen) throws IOException { int c = src.read(); if (lex_state == LexState.EXPR_FNAME || lex_state == LexState.EXPR_DOT) { setState(LexState.EXPR_ARG); if (c == '@') { yaccValue = new Token("+@", getPosition()); return Tokens.tUPLUS; } src.unread(c); yaccValue = new Token("+", getPosition()); return Tokens.tPLUS; } if (c == '=') { setState(LexState.EXPR_BEG); yaccValue = new Token("+", getPosition()); return Tokens.tOP_ASGN; } if (isBEG() || (isARG() && spaceSeen && !Character.isWhitespace(c))) { if (isARG()) arg_ambiguous(); setState(LexState.EXPR_BEG); src.unread(c); if (Character.isDigit(c)) { c = '+'; return parseNumber(c); } yaccValue = new Token("+", getPosition()); return Tokens.tUPLUS; } setState(LexState.EXPR_BEG); src.unread(c); yaccValue = new Token("+", getPosition()); return Tokens.tPLUS; } private int questionMark() throws IOException { int c; if (isEND()) { setState(isOneEight ? LexState.EXPR_BEG : LexState.EXPR_VALUE); yaccValue = new Token("?",getPosition()); return '?'; } c = src.read(); if (c == EOF) throw new SyntaxException(PID.INCOMPLETE_CHAR_SYNTAX, getPosition(), getCurrentLine(), "incomplete character syntax"); if (Character.isWhitespace(c)){ if (!isARG()) { int c2 = 0; switch (c) { case ' ': c2 = 's'; break; case '\n': c2 = 'n'; break; case '\t': c2 = 't'; break; /* What is \v in C? case '\v': c2 = 'v'; break; */ case '\r': c2 = 'r'; break; case '\f': c2 = 'f'; break; } if (c2 != 0) { warnings.warn(ID.INVALID_CHAR_SEQUENCE, getPosition(), "invalid character syntax; use ?\\" + c2); } } src.unread(c); setState(isOneEight ? LexState.EXPR_BEG : LexState.EXPR_VALUE); yaccValue = new Token("?", getPosition()); return '?'; /*} else if (ismbchar(c)) { // ruby - we don't support them either? rb_warn("multibyte character literal not supported yet; use ?\\" + c); support.unread(c); lexState = LexState.EXPR_BEG; return '?';*/ } else if (isIdentifierChar(c) && !src.peek('\n') && isNext_identchar()) { src.unread(c); setState(isOneEight ? LexState.EXPR_BEG : LexState.EXPR_VALUE); yaccValue = new Token("?", getPosition()); return '?'; } else if (c == '\\') { // FIXME: peek('u') utf8 stuff for 1.9 c = readEscape(); } setState(LexState.EXPR_END); if (isOneEight) { c &= 0xff; yaccValue = new FixnumNode(getPosition(), c); } else { String oneCharBL = "" + (char) c; yaccValue = new StrNode(getPosition(), oneCharBL); } // TODO: This should be something else like a tCHAR return Tokens.tINTEGER; } private int rightBracket() { parenNest--; conditionState.restart(); cmdArgumentState.restart(); setState(isOneEight ? LexState.EXPR_END : LexState.EXPR_ENDARG); yaccValue = new Token(")", getPosition()); return Tokens.tRBRACK; } private int rightCurly() { conditionState.restart(); cmdArgumentState.restart(); setState(isOneEight ? LexState.EXPR_END : LexState.EXPR_ENDARG); yaccValue = new Token("}",getPosition()); return Tokens.tRCURLY; } private int rightParen() { parenNest--; conditionState.restart(); cmdArgumentState.restart(); setState(isOneEight ? LexState.EXPR_END : LexState.EXPR_ENDFN); yaccValue = new Token(")", getPosition()); return Tokens.tRPAREN; } private int singleQuote() throws IOException { lex_strterm = new StringTerm(str_squote, '\0', '\''); yaccValue = new Token("'", getPosition()); return Tokens.tSTRING_BEG; } private int slash(boolean spaceSeen) throws IOException { if (isBEG()) { lex_strterm = new StringTerm(str_regexp, '\0', '/'); yaccValue = new Token("/",getPosition()); return Tokens.tREGEXP_BEG; } int c = src.read(); if (c == '=') { yaccValue = new Token("/", getPosition()); setState(LexState.EXPR_BEG); return Tokens.tOP_ASGN; } src.unread(c); if (isARG() && spaceSeen) { if (!Character.isWhitespace(c)) { arg_ambiguous(); lex_strterm = new StringTerm(str_regexp, '\0', '/'); yaccValue = new Token("/",getPosition()); return Tokens.tREGEXP_BEG; } } determineExpressionState(); yaccValue = new Token("/", getPosition()); return Tokens.tDIVIDE; } private int star(boolean spaceSeen) throws IOException { int c = src.read(); switch (c) { case '*': if ((c = src.read()) == '=') { setState(LexState.EXPR_BEG); yaccValue = new Token("**", getPosition()); return Tokens.tOP_ASGN; } src.unread(c); yaccValue = new Token("**", getPosition()); c = Tokens.tPOW; break; case '=': setState(LexState.EXPR_BEG); yaccValue = new Token("*", getPosition()); return Tokens.tOP_ASGN; default: src.unread(c); if (isARG() && spaceSeen && !Character.isWhitespace(c)) { if (warnings.isVerbose()) warnings.warning(ID.ARGUMENT_AS_PREFIX, getPosition(), "`*' interpreted as argument prefix", "*"); c = Tokens.tSTAR; } else if (isBEG()) { c = Tokens.tSTAR; } else { c = Tokens.tSTAR2; } yaccValue = new Token("*", getPosition()); } determineExpressionState(); return c; } private int tilde() throws IOException { int c; if (lex_state == LexState.EXPR_FNAME || lex_state == LexState.EXPR_DOT) { if ((c = src.read()) != '@') src.unread(c); setState(LexState.EXPR_ARG); } else { setState(LexState.EXPR_BEG); } yaccValue = new Token("~", getPosition()); return Tokens.tTILDE; } /** * Parse a number from the input stream. * *@param c The first character of the number. *@return A int constant wich represents a token. */ private int parseNumber(int c) throws IOException { setState(LexState.EXPR_END); tokenBuffer.setLength(0); if (c == '-') { tokenBuffer.append(c); c = src.read(); } else if (c == '+') { // We don't append '+' since Java number parser gets confused c = src.read(); } int nondigit = 0; if (c == '0') { int startLen = tokenBuffer.length(); switch (c = src.read()) { case 'x' : case 'X' : // hexadecimal c = src.read(); if (isHexChar(c)) { for (;; c = src.read()) { if (c == '_') { if (nondigit != '\0') break; nondigit = c; } else if (isHexChar(c)) { nondigit = '\0'; tokenBuffer.append(c); } else { break; } } } src.unread(c); if (tokenBuffer.length() == startLen) { throw new SyntaxException(PID.BAD_HEX_NUMBER, getPosition(), getCurrentLine(), "Hexadecimal number without hex-digits."); } else if (nondigit != '\0') { throw new SyntaxException(PID.TRAILING_UNDERSCORE_IN_NUMBER, getPosition(), getCurrentLine(), "Trailing '_' in number."); } yaccValue = getInteger(tokenBuffer.toString(), 16); return Tokens.tINTEGER; case 'b' : case 'B' : // binary c = src.read(); if (c == '0' || c == '1') { for (;; c = src.read()) { if (c == '_') { if (nondigit != '\0') break; nondigit = c; } else if (c == '0' || c == '1') { nondigit = '\0'; tokenBuffer.append(c); } else { break; } } } src.unread(c); if (tokenBuffer.length() == startLen) { throw new SyntaxException(PID.EMPTY_BINARY_NUMBER, getPosition(), getCurrentLine(), "Binary number without digits."); } else if (nondigit != '\0') { throw new SyntaxException(PID.TRAILING_UNDERSCORE_IN_NUMBER, getPosition(), getCurrentLine(), "Trailing '_' in number."); } yaccValue = getInteger(tokenBuffer.toString(), 2); return Tokens.tINTEGER; case 'd' : case 'D' : // decimal c = src.read(); if (Character.isDigit(c)) { for (;; c = src.read()) { if (c == '_') { if (nondigit != '\0') break; nondigit = c; } else if (Character.isDigit(c)) { nondigit = '\0'; tokenBuffer.append(c); } else { break; } } } src.unread(c); if (tokenBuffer.length() == startLen) { throw new SyntaxException(PID.EMPTY_BINARY_NUMBER, getPosition(), getCurrentLine(), "Binary number without digits."); } else if (nondigit != '\0') { throw new SyntaxException(PID.TRAILING_UNDERSCORE_IN_NUMBER, getPosition(), getCurrentLine(), "Trailing '_' in number."); } yaccValue = getInteger(tokenBuffer.toString(), 10); return Tokens.tINTEGER; case 'o': case 'O': c = src.read(); case '0': case '1': case '2': case '3': case '4': //Octal case '5': case '6': case '7': case '_': for (;; c = src.read()) { if (c == '_') { if (nondigit != '\0') break; nondigit = c; } else if (c >= '0' && c <= '7') { nondigit = '\0'; tokenBuffer.append(c); } else { break; } } if (tokenBuffer.length() > startLen) { src.unread(c); if (nondigit != '\0') { throw new SyntaxException(PID.TRAILING_UNDERSCORE_IN_NUMBER, getPosition(), getCurrentLine(), "Trailing '_' in number."); } yaccValue = getInteger(tokenBuffer.toString(), 8); return Tokens.tINTEGER; } case '8' : case '9' : throw new SyntaxException(PID.BAD_OCTAL_DIGIT, getPosition(), getCurrentLine(), "Illegal octal digit."); case '.' : case 'e' : case 'E' : tokenBuffer.append('0'); break; default : src.unread(c); yaccValue = new FixnumNode(getPosition(), 0); return Tokens.tINTEGER; } } boolean seen_point = false; boolean seen_e = false; for (;; c = src.read()) { switch (c) { case '0' : case '1' : case '2' : case '3' : case '4' : case '5' : case '6' : case '7' : case '8' : case '9' : nondigit = '\0'; tokenBuffer.append(c); break; case '.' : if (nondigit != '\0') { src.unread(c); throw new SyntaxException(PID.TRAILING_UNDERSCORE_IN_NUMBER, getPosition(), getCurrentLine(), "Trailing '_' in number."); } else if (seen_point || seen_e) { src.unread(c); return getNumberToken(tokenBuffer.toString(), true, nondigit); } else { int c2; if (!Character.isDigit(c2 = src.read())) { src.unread(c2); src.unread('.'); if (c == '_') { // Enebo: c can never be antrhign but '.' // Why did I put this here? } else { yaccValue = getInteger(tokenBuffer.toString(), 10); return Tokens.tINTEGER; } } else { tokenBuffer.append('.'); tokenBuffer.append(c2); seen_point = true; nondigit = '\0'; } } break; case 'e' : case 'E' : if (nondigit != '\0') { throw new SyntaxException(PID.TRAILING_UNDERSCORE_IN_NUMBER, getPosition(), getCurrentLine(), "Trailing '_' in number."); } else if (seen_e) { src.unread(c); return getNumberToken(tokenBuffer.toString(), true, nondigit); } else { tokenBuffer.append(c); seen_e = true; nondigit = c; c = src.read(); if (c == '-' || c == '+') { tokenBuffer.append(c); nondigit = c; } else { src.unread(c); } } break; case '_' : // '_' in number just ignored if (nondigit != '\0') { throw new SyntaxException(PID.TRAILING_UNDERSCORE_IN_NUMBER, getPosition(), getCurrentLine(), "Trailing '_' in number."); } nondigit = c; break; default : src.unread(c); return getNumberToken(tokenBuffer.toString(), seen_e || seen_point, nondigit); } } } private int getNumberToken(String number, boolean isFloat, int nondigit) { if (nondigit != '\0') { throw new SyntaxException(PID.TRAILING_UNDERSCORE_IN_NUMBER, getPosition(), getCurrentLine(), "Trailing '_' in number."); } else if (isFloat) { return getFloatToken(number); } yaccValue = getInteger(number, 10); return Tokens.tINTEGER; } // Note: parser_tokadd_utf8 variant just for regexp literal parsing. This variant is to be // called when string_literal and regexp_literal. public void readUTFEscapeRegexpLiteral(CStringBuilder buffer) throws IOException { buffer.append('\\'); buffer.append('u'); if (src.peek('{')) { // handle \\u{...} do { buffer.append(src.read()); if (scanHexLiteral(buffer, 6, false, "invalid Unicode escape") > 0x10ffff) { throw new SyntaxException(PID.INVALID_ESCAPE_SYNTAX, getPosition(), getCurrentLine(), "invalid Unicode codepoint (too large)"); } } while (src.peek(' ') || src.peek('\t')); int c = src.read(); if (c != '}') { throw new SyntaxException(PID.INVALID_ESCAPE_SYNTAX, getPosition(), getCurrentLine(), "unterminated Unicode escape"); } buffer.append((char) c); } else { // handle \\uxxxx scanHexLiteral(buffer, 4, true, "Invalid Unicode escape"); } } private byte[] mbcBuf = new byte[6]; //FIXME: This seems like it could be more efficient to ensure size in bytelist and then pass // in bytelists byte backing store. This method would look ugly since realSize would need // to be tweaked and I don't know how many bytes this codepoint has up front so I would need // to grow by 6 (which may be wasteful). Another idea is to make Encoding accept an interface // for populating bytes and then make ByteList implement that interface. I like this last idea // since it would not leak bytelist impl details all over the place. public int tokenAddMBC(int codepoint, CStringBuilder buffer) { // int length = buffer.getEncoding().codeToMbc(codepoint, mbcBuf, 0); // if (length <= 0) return EOF; // buffer.append(mbcBuf, 0, length); buffer.append(codepoint); // return length; return 1; } public void tokenAddMBCFromSrc(int c, CStringBuilder buffer) throws IOException { // read bytes for length of character int length = 1; //buffer.getEncoding().length((byte)c); buffer.append((char)c); // for (int off = 0; off < length - 1; off++) { // buffer.append((byte)src.read()); // } } // MRI: parser_tokadd_utf8 sans regexp literal parsing public int readUTFEscape(CStringBuilder buffer, boolean stringLiteral, boolean symbolLiteral) throws IOException { int codepoint; int c; if (src.peek('{')) { // handle \\u{...} do { src.read(); // Eat curly or whitespace codepoint = scanHex(6, false, "invalid Unicode escape"); if (codepoint > 0x10ffff) { throw new SyntaxException(PID.INVALID_ESCAPE_SYNTAX, getPosition(), getCurrentLine(), "invalid Unicode codepoint (too large)"); } if (codepoint >= 0x80) { // buffer.setEncoding("UTF-8"); if (stringLiteral) tokenAddMBC(codepoint, buffer); } else if (stringLiteral) { if (codepoint == 0 && symbolLiteral) { throw new SyntaxException(PID.INVALID_ESCAPE_SYNTAX, getPosition(), getCurrentLine(), "symbol cannot contain '\\u0000'"); } buffer.append((char) codepoint); } } while (src.peek(' ') || src.peek('\t')); c = src.read(); if (c != '}') { throw new SyntaxException(PID.INVALID_ESCAPE_SYNTAX, getPosition(), getCurrentLine(), "unterminated Unicode escape"); } } else { // handle \\uxxxx codepoint = scanHex(4, true, "Invalid Unicode escape"); if (codepoint >= 0x80) { // buffer.setEncoding("UTF-8"); if (stringLiteral) tokenAddMBC(codepoint, buffer); } else if (stringLiteral) { if (codepoint == 0 && symbolLiteral) { throw new SyntaxException(PID.INVALID_ESCAPE_SYNTAX, getPosition(), getCurrentLine(), "symbol cannot contain '\\u0000'"); } buffer.append((char) codepoint); } } return codepoint; } public int readEscape() throws IOException { int c = src.read(); switch (c) { case '\\' : // backslash return c; case 'n' : // newline return '\n'; case 't' : // horizontal tab return '\t'; case 'r' : // carriage return return '\r'; case 'f' : // form feed return '\f'; case 'v' : // vertical tab return '\u000B'; case 'a' : // alarm(bell) return '\u0007'; case 'e' : // escape return '\u001B'; case '0' : case '1' : case '2' : case '3' : // octal constant case '4' : case '5' : case '6' : case '7' : src.unread(c); return scanOct(3); case 'x' : // hex constant int i = 0; //char hexValue = scanHex(2); char hexValue = '\0'; for (; i < 2; i++) { int h1 = src.read(); if (!isHexChar(h1)) { src.unread(h1); break; } hexValue <<= 4; hexValue |= Integer.parseInt(""+(char)h1, 16) & 15; } // No hex value after the 'x'. if (i == 0) { throw new SyntaxException(PID.INVALID_ESCAPE_SYNTAX, getPosition(), getCurrentLine(), "Invalid escape character syntax"); } return hexValue; case 'b' : // backspace return '\010'; case 's' : // space return ' '; case 'M' : if ((c = src.read()) != '-') { throw new SyntaxException(PID.INVALID_ESCAPE_SYNTAX, getPosition(), getCurrentLine(), "Invalid escape character syntax"); } else if ((c = src.read()) == '\\') { return (char) (readEscape() | 0x80); } else if (c == EOF) { throw new SyntaxException(PID.INVALID_ESCAPE_SYNTAX, getPosition(), getCurrentLine(), "Invalid escape character syntax"); } return (char) ((c & 0xff) | 0x80); case 'C' : if ((c = src.read()) != '-') { throw new SyntaxException(PID.INVALID_ESCAPE_SYNTAX, getPosition(), getCurrentLine(), "Invalid escape character syntax"); } case 'c' : if ((c = src.read()) == '\\') { c = readEscape(); } else if (c == '?') { return '\u0177'; } else if (c == EOF) { throw new SyntaxException(PID.INVALID_ESCAPE_SYNTAX, getPosition(), getCurrentLine(), "Invalid escape character syntax"); } return (char) (c & 0x9f); case EOF : throw new SyntaxException(PID.INVALID_ESCAPE_SYNTAX, getPosition(), getCurrentLine(), "Invalid escape character syntax"); default : return c; } } /** * Read up to count hexadecimal digits and store those digits in a token buffer. If strict is * provided then count number of hex digits must be present. If no digits can be read a syntax * exception will be thrown. This will also return the codepoint as a value so codepoint * ranges can be checked. */ private char scanHexLiteral(CStringBuilder buffer, int count, boolean strict, String errorMessage) throws IOException { int i = 0; char hexValue = '\0'; for (; i < count; i++) { int h1 = src.read(); if (!isHexChar(h1)) { src.unread(h1); break; } buffer.append(h1); hexValue <<= 4; hexValue |= Integer.parseInt("" + (char) h1, 16) & 15; } // No hex value after the 'x'. if (i == 0 || strict && count != i) { throw new SyntaxException(PID.INVALID_ESCAPE_SYNTAX, getPosition(), getCurrentLine(), errorMessage); } return hexValue; } /** * Read up to count hexadecimal digits. If strict is provided then count number of hex * digits must be present. If no digits can be read a syntax exception will be thrown. */ private int scanHex(int count, boolean strict, String errorMessage) throws IOException { int i = 0; int hexValue = '\0'; for (; i < count; i++) { int h1 = src.read(); if (!isHexChar(h1)) { src.unread(h1); break; } hexValue <<= 4; hexValue |= Integer.parseInt("" + (char) h1, 16) & 15; } // No hex value after the 'x'. if (i == 0 || (strict && count != i)) { throw new SyntaxException(PID.INVALID_ESCAPE_SYNTAX, getPosition(), getCurrentLine(), errorMessage); } return hexValue; } private char scanOct(int count) throws IOException { char value = '\0'; for (int i = 0; i < count; i++) { int c = src.read(); if (!isOctChar(c)) { src.unread(c); break; } value <<= 3; value |= Integer.parseInt("" + (char) c, 8); } return value; } }
false
true
private int yylex() throws IOException { int c; boolean spaceSeen = false; boolean commandState; if (setSpaceSeen) { spaceSeen = true; setSpaceSeen = false; } // On new lines, possibly resume heredoc processing (see docs for newlineTerms for more) if (heredocContext != null) { if (heredocContext.isLookingForEnd()) { lex_strterm = heredocContext.getTerm(); } else if (src.isANewLine()) { lex_strterm = heredocContext.getTerm(); heredocContext = heredocContext.pop(); } } if (lex_strterm != null) { try { int tok = lex_strterm.parseString(this, src); if (tok == Tokens.tSTRING_END || tok == Tokens.tREGEXP_END) { lex_strterm = null; setState(LexState.EXPR_END); if (heredocContext != null && heredocContext.isLookingForEnd()) { heredocContext = heredocContext.pop(); } } return tok; } catch (SyntaxException se) { // If we abort in string parsing, throw away the str term // such that we don't try again on restart lex_strterm = null; setState(LexState.EXPR_END); throw se; } } commandState = commandStart; commandStart = false; loop: for(;;) { c = src.read(); switch(c) { case '\004': /* ^D */ case '\032': /* ^Z */ case EOF: /* end of script. */ return EOF; /* white spaces */ case ' ': case '\t': case '\f': case '\r': case '\13': /* '\v' */ if (preserveSpaces) { // Collapse all whitespace into one token while (true) { c = src.read(); if (c != ' ' && c != '\t' && c != '\f' && c != '\r' && c != '\13') break; } src.unread(c); yaccValue = new Token("whitespace", getPosition()); setSpaceSeen = true; return Tokens.tWHITESPACE; } getPosition(); spaceSeen = true; continue; case '#': /* it's a comment */ if (preserveSpaces) { // Skip to end of the comment while ((c = src.read()) != '\n') { if (c == EOF) break; } yaccValue = new Token("line-comment", getPosition()); setSpaceSeen = spaceSeen; // Ensure that commandStart and lex_state is updated // as it otherwise would have if preserveSpaces was false if (!(lex_state == LexState.EXPR_BEG || lex_state == LexState.EXPR_FNAME || lex_state == LexState.EXPR_DOT || lex_state == LexState.EXPR_CLASS)) { commandStart = true; setState(LexState.EXPR_BEG); } return Tokens.tCOMMENT; } else { // FIXME: Need to detect magic_comment in 1.9 here for encoding if (readComment(c) == EOF) return EOF; } /* fall through */ case '\n': if (isOneEight) { // Replace a string of newlines with a single one while((c = src.read()) == '\n'); } else { switch (lex_state) { case EXPR_BEG: case EXPR_FNAME: case EXPR_DOT: case EXPR_CLASS: case EXPR_VALUE: getPosition(); continue loop; } boolean done = false; while(!done) { c = src.read(); switch (c) { case ' ': case '\t': case '\f': case '\r': case '\13': /* '\v' */ spaceSeen = true; continue; case '.': { if ((c = src.read()) != '.') { src.unread(c); src.unread('.'); continue loop; } } default: case -1: // EOF (ENEBO: After default? done = true; } } } if (c == -1 && !preserveSpaces) return EOF; src.unread(c); getPosition(); if (preserveSpaces) { src.setIsANewLine(true); yaccValue = new Token("whitespace", getPosition()); // Ensure that commandStart and lex_state is updated // as it otherwise would have if preserveSpaces was false if (!(lex_state == LexState.EXPR_BEG || lex_state == LexState.EXPR_FNAME || lex_state == LexState.EXPR_DOT || lex_state == LexState.EXPR_CLASS)) { commandStart = true; setState(LexState.EXPR_BEG); } return Tokens.tWHITESPACE; } switch (lex_state) { case EXPR_BEG: case EXPR_FNAME: case EXPR_DOT: case EXPR_CLASS: continue loop; } commandStart = true; setState(LexState.EXPR_BEG); return '\n'; case '*': return star(spaceSeen); case '!': return bang(); case '=': // documentation nodes if (src.wasBeginOfLine()) { boolean doComments = preserveSpaces; if (src.matchMarker(BEGIN_DOC_MARKER, false, false)) { if (doComments) { tokenBuffer.setLength(0); tokenBuffer.append(BEGIN_DOC_MARKER); } c = src.read(); if (Character.isWhitespace(c)) { // In case last next was the newline. src.unread(c); for (;;) { c = src.read(); if (doComments) tokenBuffer.append(c); // If a line is followed by a blank line put // it back. while (c == '\n') { c = src.read(); if (doComments) tokenBuffer.append(c); } if (c == EOF) { throw new SyntaxException(PID.STRING_HITS_EOF, getPosition(), getCurrentLine(), "embedded document meets end of file"); } if (c != '=') continue; if (src.wasBeginOfLine() && src.matchMarker(END_DOC_MARKER, false, false)) { if (doComments) tokenBuffer.append(END_DOC_MARKER); String list = src.readLineBytes(); if (doComments) tokenBuffer.append(list); src.unread('\n'); break; } } if (doComments) { yaccValue = new Token("here-doc", getPosition()); return Tokens.tDOCUMENTATION; // parserSupport.getResult().addComment(new CommentNode(getPosition(), tokenBuffer.toString())); } continue; } src.unread(c); } } determineExpressionState(); c = src.read(); if (c == '=') { c = src.read(); if (c == '=') { yaccValue = new Token("===", getPosition()); return Tokens.tEQQ; } src.unread(c); yaccValue = new Token("==", getPosition()); return Tokens.tEQ; } if (c == '~') { yaccValue = new Token("=~", getPosition()); return Tokens.tMATCH; } else if (c == '>') { yaccValue = new Token("=>", getPosition()); return Tokens.tASSOC; } src.unread(c); yaccValue = new Token("=", getPosition()); return '='; case '<': return lessThan(spaceSeen); case '>': return greaterThan(); case '"': return doubleQuote(); case '`': return backtick(commandState); case '\'': return singleQuote(); case '?': return questionMark(); case '&': return ampersand(spaceSeen); case '|': return pipe(); case '+': return plus(spaceSeen); case '-': return minus(spaceSeen); case '.': return dot(); case '0' : case '1' : case '2' : case '3' : case '4' : case '5' : case '6' : case '7' : case '8' : case '9' : return parseNumber(c); case ')': return rightParen(); case ']': return rightBracket(); case '}': return rightCurly(); case ':': return colon(spaceSeen); case '/': return slash(spaceSeen); case '^': return caret(); case ';': commandStart = true; if (!isOneEight) { setState(LexState.EXPR_BEG); yaccValue = new Token(";", getPosition()); return ';'; } case ',': return comma(c); case '~': return tilde(); case '(': return leftParen(spaceSeen); case '[': return leftBracket(spaceSeen); case '{': return leftCurly(); case '\\': c = src.read(); if (c == '\n') { spaceSeen = true; continue; } src.unread(c); yaccValue = new Token("\\", getPosition()); return '\\'; case '%': return percent(spaceSeen); case '$': return dollar(); case '@': return at(); case '_': if (src.wasBeginOfLine() && src.matchMarker(END_MARKER, false, true)) { if (parserSupport != null) parserSupport.getResult().setEndOffset(src.getOffset()); return EOF; } return identifier(c, commandState); default: return identifier(c, commandState); } } }
private int yylex() throws IOException { int c; boolean spaceSeen = false; boolean commandState; if (setSpaceSeen) { spaceSeen = true; setSpaceSeen = false; } // On new lines, possibly resume heredoc processing (see docs for newlineTerms for more) if (heredocContext != null) { if (heredocContext.isLookingForEnd()) { lex_strterm = heredocContext.getTerm(); } else if (src.isANewLine()) { lex_strterm = heredocContext.getTerm(); heredocContext = heredocContext.pop(); } } if (lex_strterm != null) { try { int tok = lex_strterm.parseString(this, src); if (tok == Tokens.tSTRING_END || tok == Tokens.tREGEXP_END) { lex_strterm = null; setState(LexState.EXPR_END); if (heredocContext != null && heredocContext.isLookingForEnd()) { heredocContext = heredocContext.pop(); } } return tok; } catch (SyntaxException se) { // If we abort in string parsing, throw away the str term // such that we don't try again on restart lex_strterm = null; setState(LexState.EXPR_END); throw se; } } commandState = commandStart; commandStart = false; loop: for(;;) { c = src.read(); switch(c) { case '\004': /* ^D */ case '\032': /* ^Z */ case EOF: /* end of script. */ return EOF; /* white spaces */ case ' ': case '\t': case '\f': case '\r': case '\13': /* '\v' */ if (preserveSpaces) { // Collapse all whitespace into one token while (true) { c = src.read(); if (c != ' ' && c != '\t' && c != '\f' && c != '\r' && c != '\13') break; } src.unread(c); yaccValue = new Token("whitespace", getPosition()); setSpaceSeen = true; return Tokens.tWHITESPACE; } getPosition(); spaceSeen = true; continue; case '#': /* it's a comment */ if (preserveSpaces) { // Skip to end of the comment while ((c = src.read()) != '\n') { if (c == EOF) break; } yaccValue = new Token("line-comment", getPosition()); setSpaceSeen = spaceSeen; // Ensure that commandStart and lex_state is updated // as it otherwise would have if preserveSpaces was false if (!(lex_state == LexState.EXPR_BEG || lex_state == LexState.EXPR_FNAME || lex_state == LexState.EXPR_DOT || lex_state == LexState.EXPR_CLASS)) { commandStart = true; setState(LexState.EXPR_BEG); } return Tokens.tCOMMENT; } else { // FIXME: Need to detect magic_comment in 1.9 here for encoding if (readComment(c) == EOF) return EOF; } /* fall through */ case '\n': if (isOneEight) { // Replace a string of newlines with a single one while((c = src.read()) == '\n'); } else { switch (lex_state) { case EXPR_BEG: case EXPR_FNAME: case EXPR_DOT: case EXPR_CLASS: case EXPR_VALUE: getPosition(); continue loop; } boolean done = false; while(!done) { c = src.read(); switch (c) { case ' ': case '\t': case '\f': case '\r': case '\13': /* '\v' */ spaceSeen = true; continue; case '.': { if ((c = src.read()) != '.') { src.unread(c); src.unread('.'); continue loop; } } default: case -1: // EOF (ENEBO: After default? done = true; } } } if (c == -1 && !preserveSpaces) return EOF; src.unread(c); getPosition(); if (preserveSpaces) { src.setIsANewLine(true); yaccValue = new Token("whitespace", getPosition()); // Ensure that commandStart and lex_state is updated // as it otherwise would have if preserveSpaces was false if (!(lex_state == LexState.EXPR_BEG || lex_state == LexState.EXPR_FNAME || lex_state == LexState.EXPR_DOT || lex_state == LexState.EXPR_CLASS)) { commandStart = true; setState(LexState.EXPR_BEG); } return Tokens.tWHITESPACE; } switch (lex_state) { case EXPR_BEG: case EXPR_FNAME: case EXPR_DOT: case EXPR_CLASS: continue loop; } commandStart = true; setState(LexState.EXPR_BEG); return '\n'; case '*': return star(spaceSeen); case '!': return bang(); case '=': // documentation nodes if (src.wasBeginOfLine()) { if (src.matchMarker(BEGIN_DOC_MARKER, false, false)) { SourcePosition startPosition = src.getPosition(); if (doComments) { tokenBuffer.setLength(0); tokenBuffer.append('='); tokenBuffer.append(BEGIN_DOC_MARKER); } c = src.read(); if (Character.isWhitespace(c)) { // In case last next was the newline. src.unread(c); for (;;) { c = src.read(); if (doComments) tokenBuffer.append(c); // If a line is followed by a blank line put // it back. while (c == '\n') { c = src.read(); if (doComments) tokenBuffer.append(c); } if (c == EOF) { throw new SyntaxException(PID.STRING_HITS_EOF, getPosition(), getCurrentLine(), "embedded document meets end of file"); } if (c != '=') continue; if (src.wasBeginOfLine() && src.matchMarker(END_DOC_MARKER, false, false)) { if (doComments) tokenBuffer.append(END_DOC_MARKER); String list = src.readLineBytes(); if (doComments) tokenBuffer.append(list); src.unread('\n'); break; } } if (doComments) { // Store away each comment to parser result so IDEs can do whatever they want with them. SourcePosition position = startPosition.union(getPosition()); parserSupport.getResult().addComment(new CommentNode(position, tokenBuffer.toString())); } if (preserveSpaces) { yaccValue = new Token("here-doc", getPosition()); return Tokens.tDOCUMENTATION; } continue; } src.unread(c); } } determineExpressionState(); c = src.read(); if (c == '=') { c = src.read(); if (c == '=') { yaccValue = new Token("===", getPosition()); return Tokens.tEQQ; } src.unread(c); yaccValue = new Token("==", getPosition()); return Tokens.tEQ; } if (c == '~') { yaccValue = new Token("=~", getPosition()); return Tokens.tMATCH; } else if (c == '>') { yaccValue = new Token("=>", getPosition()); return Tokens.tASSOC; } src.unread(c); yaccValue = new Token("=", getPosition()); return '='; case '<': return lessThan(spaceSeen); case '>': return greaterThan(); case '"': return doubleQuote(); case '`': return backtick(commandState); case '\'': return singleQuote(); case '?': return questionMark(); case '&': return ampersand(spaceSeen); case '|': return pipe(); case '+': return plus(spaceSeen); case '-': return minus(spaceSeen); case '.': return dot(); case '0' : case '1' : case '2' : case '3' : case '4' : case '5' : case '6' : case '7' : case '8' : case '9' : return parseNumber(c); case ')': return rightParen(); case ']': return rightBracket(); case '}': return rightCurly(); case ':': return colon(spaceSeen); case '/': return slash(spaceSeen); case '^': return caret(); case ';': commandStart = true; if (!isOneEight) { setState(LexState.EXPR_BEG); yaccValue = new Token(";", getPosition()); return ';'; } case ',': return comma(c); case '~': return tilde(); case '(': return leftParen(spaceSeen); case '[': return leftBracket(spaceSeen); case '{': return leftCurly(); case '\\': c = src.read(); if (c == '\n') { spaceSeen = true; continue; } src.unread(c); yaccValue = new Token("\\", getPosition()); return '\\'; case '%': return percent(spaceSeen); case '$': return dollar(); case '@': return at(); case '_': if (src.wasBeginOfLine() && src.matchMarker(END_MARKER, false, true)) { if (parserSupport != null) parserSupport.getResult().setEndOffset(src.getOffset()); return EOF; } return identifier(c, commandState); default: return identifier(c, commandState); } } }
diff --git a/src/com/takipi/keygen/instructions/InstructionsBuilder.java b/src/com/takipi/keygen/instructions/InstructionsBuilder.java index 47360c0..57a49f0 100644 --- a/src/com/takipi/keygen/instructions/InstructionsBuilder.java +++ b/src/com/takipi/keygen/instructions/InstructionsBuilder.java @@ -1,57 +1,57 @@ package com.takipi.keygen.instructions; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; public class InstructionsBuilder { private static final char[] FILE_ILLEGAL_CHARACTERS = { '/', '\n', '\r', '\t', '\0', '\f', '`', '?', '*', '\\', '<', '>', '|', '\"', ':' }; public static void buildInstructionsFile(String username, String secretKey, String proxy) { String installInstructions = InstructionsVelocity.generateText(username, secretKey, proxy); - String id = secretKey.substring(0, secretKey.indexOf('#')); + String serverId = secretKey.substring(0, secretKey.indexOf('#')); - String filenamePrefix = username+"-"+id; + String filenamePrefix = username + "-" + serverId; String filename = getFilenameForDownload(filenamePrefix, proxy); System.out.println(""); System.out.println(installInstructions); try { FileUtils.writeStringToFile(new File(filename), installInstructions); System.out.println(""); System.out.println("File saved as: " + filename); } catch (IOException e) { System.err.println("Can't create file '" + filename + "' with install instructions"); } } private static String getFilenameForDownload(String input, String proxy) { String helper = input; for (char c : FILE_ILLEGAL_CHARACTERS) { helper = helper.replace(c, '-'); } if ((proxy != null) && (!proxy.isEmpty())) { helper = helper + "-behind-proxy"; } helper = helper + "-takipi.key.txt"; return helper; } }
false
true
public static void buildInstructionsFile(String username, String secretKey, String proxy) { String installInstructions = InstructionsVelocity.generateText(username, secretKey, proxy); String id = secretKey.substring(0, secretKey.indexOf('#')); String filenamePrefix = username+"-"+id; String filename = getFilenameForDownload(filenamePrefix, proxy); System.out.println(""); System.out.println(installInstructions); try { FileUtils.writeStringToFile(new File(filename), installInstructions); System.out.println(""); System.out.println("File saved as: " + filename); } catch (IOException e) { System.err.println("Can't create file '" + filename + "' with install instructions"); } }
public static void buildInstructionsFile(String username, String secretKey, String proxy) { String installInstructions = InstructionsVelocity.generateText(username, secretKey, proxy); String serverId = secretKey.substring(0, secretKey.indexOf('#')); String filenamePrefix = username + "-" + serverId; String filename = getFilenameForDownload(filenamePrefix, proxy); System.out.println(""); System.out.println(installInstructions); try { FileUtils.writeStringToFile(new File(filename), installInstructions); System.out.println(""); System.out.println("File saved as: " + filename); } catch (IOException e) { System.err.println("Can't create file '" + filename + "' with install instructions"); } }
diff --git a/src/be/ibridge/kettle/trans/step/tableoutput/TableOutputMeta.java b/src/be/ibridge/kettle/trans/step/tableoutput/TableOutputMeta.java index c8340c72..4c0208fc 100644 --- a/src/be/ibridge/kettle/trans/step/tableoutput/TableOutputMeta.java +++ b/src/be/ibridge/kettle/trans/step/tableoutput/TableOutputMeta.java @@ -1,725 +1,725 @@ /********************************************************************** ** ** ** This code belongs to the KETTLE project. ** ** ** ** Kettle, from version 2.2 on, is released into the public domain ** ** under the Lesser GNU Public License (LGPL). ** ** ** ** For more details, please read the document LICENSE.txt, included ** ** in this project ** ** ** ** http://www.kettle.be ** ** [email protected] ** ** ** **********************************************************************/ package be.ibridge.kettle.trans.step.tableoutput; import java.util.ArrayList; import java.util.Hashtable; import org.eclipse.swt.widgets.Shell; import org.w3c.dom.Node; import be.ibridge.kettle.core.CheckResult; import be.ibridge.kettle.core.Const; import be.ibridge.kettle.core.Row; import be.ibridge.kettle.core.SQLStatement; import be.ibridge.kettle.core.XMLHandler; import be.ibridge.kettle.core.database.Database; import be.ibridge.kettle.core.database.DatabaseMeta; import be.ibridge.kettle.core.exception.KettleDatabaseException; import be.ibridge.kettle.core.exception.KettleException; import be.ibridge.kettle.core.exception.KettleXMLException; import be.ibridge.kettle.core.value.Value; import be.ibridge.kettle.repository.Repository; import be.ibridge.kettle.trans.DatabaseImpact; import be.ibridge.kettle.trans.Trans; import be.ibridge.kettle.trans.TransMeta; import be.ibridge.kettle.trans.step.BaseStepMeta; import be.ibridge.kettle.trans.step.StepDataInterface; import be.ibridge.kettle.trans.step.StepDialogInterface; import be.ibridge.kettle.trans.step.StepInterface; import be.ibridge.kettle.trans.step.StepMeta; import be.ibridge.kettle.trans.step.StepMetaInterface; /* * Created on 2-jun-2003 * */ public class TableOutputMeta extends BaseStepMeta implements StepMetaInterface { private DatabaseMeta database; private String tablename; private int commitSize; private boolean truncateTable; private boolean ignoreErrors; private boolean useBatchUpdate; private boolean partitioningEnabled; private String partitioningField; private boolean partitioningDaily; private boolean partitioningMonthly; private boolean tableNameInField; private String tableNameField; private boolean tableNameInTable; /** * @return Returns the tableNameInTable. */ public boolean isTableNameInTable() { return tableNameInTable; } /** * @param tableNameInTable The tableNameInTable to set. */ public void setTableNameInTable(boolean tableNameInTable) { this.tableNameInTable = tableNameInTable; } /** * @return Returns the tableNameField. */ public String getTableNameField() { return tableNameField; } /** * @param tableNameField The tableNameField to set. */ public void setTableNameField(String tableNameField) { this.tableNameField = tableNameField; } /** * @return Returns the tableNameInField. */ public boolean isTableNameInField() { return tableNameInField; } /** * @param tableNameInField The tableNameInField to set. */ public void setTableNameInField(boolean tableNameInField) { this.tableNameInField = tableNameInField; } /** * @return Returns the partitioningDaily. */ public boolean isPartitioningDaily() { return partitioningDaily; } /** * @param partitioningDaily The partitioningDaily to set. */ public void setPartitioningDaily(boolean partitioningDaily) { this.partitioningDaily = partitioningDaily; } /** * @return Returns the partitioningMontly. */ public boolean isPartitioningMonthly() { return partitioningMonthly; } /** * @param partitioningMontly The partitioningMontly to set. */ public void setPartitioningMonthly(boolean partitioningMontly) { this.partitioningMonthly = partitioningMontly; } /** * @return Returns the partitioningEnabled. */ public boolean isPartitioningEnabled() { return partitioningEnabled; } /** * @param partitioningEnabled The partitioningEnabled to set. */ public void setPartitioningEnabled(boolean partitioningEnabled) { this.partitioningEnabled = partitioningEnabled; } /** * @return Returns the partitioningField. */ public String getPartitioningField() { return partitioningField; } /** * @param partitioningField The partitioningField to set. */ public void setPartitioningField(String partitioningField) { this.partitioningField = partitioningField; } public TableOutputMeta() { super(); // allocate BaseStepMeta useBatchUpdate=true; commitSize=100; } public void loadXML(Node stepnode, ArrayList databases, Hashtable counters) throws KettleXMLException { readData(stepnode, databases); } public Object clone() { TableOutputMeta retval = (TableOutputMeta)super.clone(); return retval; } /** * @return Returns the database. */ public DatabaseMeta getDatabase() { return database; } /** * @param database The database to set. */ public void setDatabase(DatabaseMeta database) { this.database = database; } /** * @return Returns the commitSize. */ public int getCommitSize() { return commitSize; } /** * @param commitSize The commitSize to set. */ public void setCommitSize(int commitSize) { this.commitSize = commitSize; } /** * @return Returns the tablename. */ public String getTablename() { return tablename; } /** * @param tablename The tablename to set. */ public void setTablename(String tablename) { this.tablename = tablename; } /** * @return Returns the truncate table flag. */ public boolean truncateTable() { return truncateTable; } /** * @param truncateTable The truncate table flag to set. */ public void setTruncateTable(boolean truncateTable) { this.truncateTable = truncateTable; } /** * @param ignoreErrors The ignore errors flag to set. */ public void setIgnoreErrors(boolean ignoreErrors) { this.ignoreErrors = ignoreErrors; } /** * @return Returns the ignore errors flag. */ public boolean ignoreErrors() { return ignoreErrors; } /** * @param useBatchUpdate The useBatchUpdate flag to set. */ public void setUseBatchUpdate(boolean useBatchUpdate) { this.useBatchUpdate = useBatchUpdate; } /** * @return Returns the useBatchUpdate flag. */ public boolean useBatchUpdate() { return useBatchUpdate; } private void readData(Node stepnode, ArrayList databases) throws KettleXMLException { try { String commit; String con = XMLHandler.getTagValue(stepnode, "connection"); database = Const.findDatabase(databases, con); tablename = XMLHandler.getTagValue(stepnode, "table"); commit = XMLHandler.getTagValue(stepnode, "commit"); commitSize = Const.toInt(commit, 0); truncateTable = "Y".equalsIgnoreCase(XMLHandler.getTagValue(stepnode, "truncate")); ignoreErrors = "Y".equalsIgnoreCase(XMLHandler.getTagValue(stepnode, "ignore_errors")); useBatchUpdate= "Y".equalsIgnoreCase(XMLHandler.getTagValue(stepnode, "use_batch")); partitioningEnabled = "Y".equalsIgnoreCase(XMLHandler.getTagValue(stepnode, "partitioning_enabled")); partitioningField = XMLHandler.getTagValue(stepnode, "partitioning_field"); partitioningDaily = "Y".equalsIgnoreCase(XMLHandler.getTagValue(stepnode, "partitioning_daily")); partitioningMonthly = "Y".equalsIgnoreCase(XMLHandler.getTagValue(stepnode, "partitioning_monthly")); tableNameInField = "Y".equalsIgnoreCase(XMLHandler.getTagValue(stepnode, "tablename_in_field")); tableNameField = XMLHandler.getTagValue(stepnode, "tablename_field"); tableNameInTable = "Y".equalsIgnoreCase(XMLHandler.getTagValue(stepnode, "tablename_in_table")); } catch(Exception e) { throw new KettleXMLException("Unable to load step info from XML", e); } } public void setDefault() { database = null; tablename = ""; commitSize = 0; partitioningEnabled = false; partitioningMonthly = true; partitioningField = ""; tableNameInTable = true; tableNameField = ""; } public String getXML() { String retval=new String(); retval+=" "+XMLHandler.addTagValue("connection", database==null?"":database.getName()); retval+=" "+XMLHandler.addTagValue("table", tablename); retval+=" "+XMLHandler.addTagValue("commit", commitSize); retval+=" "+XMLHandler.addTagValue("truncate", truncateTable); retval+=" "+XMLHandler.addTagValue("ignore_errors", ignoreErrors); retval+=" "+XMLHandler.addTagValue("use_batch", useBatchUpdate); retval+=" "+XMLHandler.addTagValue("partitioning_enabled", partitioningEnabled); retval+=" "+XMLHandler.addTagValue("partitioning_field", partitioningField); retval+=" "+XMLHandler.addTagValue("partitioning_daily", partitioningDaily); retval+=" "+XMLHandler.addTagValue("partitioning_monthly", partitioningMonthly); retval+=" "+XMLHandler.addTagValue("tablename_in_field", tableNameInField); retval+=" "+XMLHandler.addTagValue("tablename_field", tableNameField); retval+=" "+XMLHandler.addTagValue("tablename_in_table", tableNameInTable); return retval; } public void readRep(Repository rep, long id_step, ArrayList databases, Hashtable counters) throws KettleException { try { long id_connection = rep.getStepAttributeInteger(id_step, "id_connection"); database = Const.findDatabase( databases, id_connection); tablename = rep.getStepAttributeString (id_step, "table"); commitSize = (int)rep.getStepAttributeInteger(id_step, "commit"); truncateTable = rep.getStepAttributeBoolean(id_step, "truncate"); ignoreErrors = rep.getStepAttributeBoolean(id_step, "ignore_errors"); useBatchUpdate = rep.getStepAttributeBoolean(id_step, "use_batch"); partitioningEnabled = rep.getStepAttributeBoolean(id_step, "partitioning_enabled"); partitioningField = rep.getStepAttributeString (id_step, "partitioning_field"); partitioningDaily = rep.getStepAttributeBoolean(id_step, "partitioning_daily"); partitioningMonthly = rep.getStepAttributeBoolean(id_step, "partitioning_monthly"); tableNameInField = rep.getStepAttributeBoolean(id_step, "tablename_in_field"); tableNameField = rep.getStepAttributeString (id_step, "tablename_field"); tableNameInTable = rep.getStepAttributeBoolean(id_step, "tablename_in_table"); } catch(Exception e) { throw new KettleException("Unexpected error reading step information from the repository", e); } } public void saveRep(Repository rep, long id_transformation, long id_step) throws KettleException { try { rep.saveStepAttribute(id_transformation, id_step, "id_connection", database==null?-1:database.getID()); rep.saveStepAttribute(id_transformation, id_step, "table", tablename); rep.saveStepAttribute(id_transformation, id_step, "commit", commitSize); rep.saveStepAttribute(id_transformation, id_step, "truncate", truncateTable); rep.saveStepAttribute(id_transformation, id_step, "ignore_errors", ignoreErrors); rep.saveStepAttribute(id_transformation, id_step, "use_batch", useBatchUpdate); rep.saveStepAttribute(id_transformation, id_step, "partitioning_enabled", partitioningEnabled); rep.saveStepAttribute(id_transformation, id_step, "partitioning_field", partitioningField); rep.saveStepAttribute(id_transformation, id_step, "partitioning_daily", partitioningDaily); rep.saveStepAttribute(id_transformation, id_step, "partitioning_monthly", partitioningMonthly); rep.saveStepAttribute(id_transformation, id_step, "tablename_in_field", tableNameInField); rep.saveStepAttribute(id_transformation, id_step, "tablename_field" , tableNameField); rep.saveStepAttribute(id_transformation, id_step, "tablename_in_table", tableNameInTable); // Also, save the step-database relationship! if (database!=null) rep.insertStepDatabase(id_transformation, id_step, database.getID()); } catch(Exception e) { throw new KettleException("Unable to save step information to the repository for id_step="+id_step, e); } } public void check(ArrayList remarks, StepMeta stepMeta, Row prev, String input[], String output[], Row info) { if (database!=null) { CheckResult cr = new CheckResult(CheckResult.TYPE_RESULT_OK, "Connection exists", stepMeta); remarks.add(cr); Database db = new Database(database); try { db.connect(); cr = new CheckResult(CheckResult.TYPE_RESULT_OK, "Connection to database OK", stepMeta); remarks.add(cr); if (tablename!=null && tablename.length()!=0) { // Check if this table exists... if (db.checkTableExists(tablename)) { cr = new CheckResult(CheckResult.TYPE_RESULT_OK, "Table ["+tablename+"] exists and is accessible", stepMeta); remarks.add(cr); Row r = db.getTableFields(tablename); if (r!=null) { cr = new CheckResult(CheckResult.TYPE_RESULT_OK, "Table ["+tablename+"] is readeable and we got the fields from it.", stepMeta); remarks.add(cr); String error_message = ""; boolean error_found = false; // OK, we have the table fields. // Now see what we can find as previous step... if (prev!=null && prev.size()>0) { cr = new CheckResult(CheckResult.TYPE_RESULT_OK, "Step is connected to previous one, receiving "+prev.size()+" fields", stepMeta); remarks.add(cr); // Starting from prev... for (int i=0;i<prev.size();i++) { Value pv = prev.getValue(i); int idx = r.searchValueIndex(pv.getName()); if (idx<0) { error_message+="\t\t"+pv.getName()+" ("+pv.getTypeDesc()+")"+Const.CR; error_found=true; } } if (error_found) { error_message="Fields in input stream, not found in output table:"+Const.CR+Const.CR+error_message; - cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, error_message, stepMeta); + cr = new CheckResult(CheckResult.TYPE_RESULT_WARNING, error_message, stepMeta); remarks.add(cr); } else { cr = new CheckResult(CheckResult.TYPE_RESULT_OK, "All fields, coming from previous steps, are found in the output table", stepMeta); remarks.add(cr); } // Starting from table fields in r... for (int i=0;i<r.size();i++) { Value rv = r.getValue(i); int idx = prev.searchValueIndex(rv.getName()); if (idx<0) { error_message+="\t\t"+rv.getName()+" ("+rv.getTypeDesc()+")"+Const.CR; error_found=true; } } if (error_found) { error_message="Fields in table, not found in input stream:"+Const.CR+Const.CR+error_message; cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, error_message, stepMeta); remarks.add(cr); } else { cr = new CheckResult(CheckResult.TYPE_RESULT_OK, "All fields in the table are found in the input stream, coming from previous steps", stepMeta); remarks.add(cr); } } else { cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, "Couldn't find fields from previous steps, check the hops...!", stepMeta); remarks.add(cr); } } else { cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, "Couldn't read the table info, please check the table-name & permissions.", stepMeta); remarks.add(cr); } } else { cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, "Table ["+tablename+"] doesn't exist or can't be read on this database connection.", stepMeta); remarks.add(cr); } } else { cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, "No table name was entered in this step.", stepMeta); remarks.add(cr); } } catch(KettleException e) { cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, "An error occurred: "+e.getMessage(), stepMeta); remarks.add(cr); } finally { db.disconnect(); } } else { CheckResult cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, "Please select or create a connection to use", stepMeta); remarks.add(cr); } // See if we have input streams leading to this step! if (input.length>0) { CheckResult cr = new CheckResult(CheckResult.TYPE_RESULT_OK, "Step is receiving info from other steps.", stepMeta); remarks.add(cr); } else { CheckResult cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, "No input received from other steps!", stepMeta); remarks.add(cr); } } public StepDialogInterface getDialog(Shell shell, StepMetaInterface info, TransMeta transMeta, String name) { return new TableOutputDialog(shell, info, transMeta, name); } public StepInterface getStep(StepMeta stepMeta, StepDataInterface stepDataInterface, int cnr, TransMeta transMeta, Trans trans) { return new TableOutput(stepMeta, stepDataInterface, cnr, transMeta, trans); } public StepDataInterface getStepData() { return new TableOutputData(); } public void analyseImpact(ArrayList impact, TransMeta transMeta, StepMeta stepMeta, Row prev, String input[], String output[], Row info) { if (truncateTable) { DatabaseImpact ii = new DatabaseImpact( DatabaseImpact.TYPE_IMPACT_TRUNCATE, transMeta.getName(), stepMeta.getName(), database.getDatabaseName(), tablename, "", "", "", "", "Truncate of table" ); impact.add(ii); } // The values that are entering this step are in "prev": if (prev!=null) { for (int i=0;i<prev.size();i++) { Value v = prev.getValue(i); DatabaseImpact ii = new DatabaseImpact( DatabaseImpact.TYPE_IMPACT_WRITE, transMeta.getName(), stepMeta.getName(), database.getDatabaseName(), tablename, v.getName(), v.getName(), v!=null?v.getOrigin():"?", "", "Type = "+v.toStringMeta() ); impact.add(ii); } } } public SQLStatement getSQLStatements(TransMeta transMeta, StepMeta stepMeta, Row prev) { SQLStatement retval = new SQLStatement(stepMeta.getName(), database, null); // default: nothing to do! if (database!=null) { if (prev!=null && prev.size()>0) { if (tablename!=null && tablename.length()>0) { Database db = new Database(database); try { db.connect(); String cr_table = db.getDDL(tablename, prev); // Empty string means: nothing to do: set it to null... if (cr_table==null || cr_table.length()==0) cr_table=null; retval.setSQL(cr_table); } catch(KettleDatabaseException dbe) { retval.setError("I was unable to connect to the database to verify the status of the table: "+dbe.getMessage()); } finally { db.disconnect(); } } else { retval.setError("No table is defined on this connection."); } } else { retval.setError("Not receiving any fields from previous steps. Check the previous steps for errors & the connecting hops."); } } else { retval.setError("There is no connection defined in this step."); } return retval; } public Row getRequiredFields() throws KettleException { if (database!=null) { Database db = new Database(database); try { db.connect(); if (tablename!=null && tablename.length()!=0) { // Check if this table exists... if (db.checkTableExists(tablename)) { return db.getTableFields(tablename); } else { throw new KettleException("Unable to determine the required fields because the specified database table couldn't be found."); } } else { throw new KettleException("Unable to determine the required fields because the database table name wasn't specified."); } } catch(Exception e) { throw new KettleException("Unable to determine the required fields.", e); } finally { db.disconnect(); } } else { throw new KettleException("Unable to determine the required fields because the database connection wasn't defined."); } } public DatabaseMeta[] getUsedDatabaseConnections() { if (database!=null) { return new DatabaseMeta[] { database }; } else { return super.getUsedDatabaseConnections(); } } }
true
true
public void check(ArrayList remarks, StepMeta stepMeta, Row prev, String input[], String output[], Row info) { if (database!=null) { CheckResult cr = new CheckResult(CheckResult.TYPE_RESULT_OK, "Connection exists", stepMeta); remarks.add(cr); Database db = new Database(database); try { db.connect(); cr = new CheckResult(CheckResult.TYPE_RESULT_OK, "Connection to database OK", stepMeta); remarks.add(cr); if (tablename!=null && tablename.length()!=0) { // Check if this table exists... if (db.checkTableExists(tablename)) { cr = new CheckResult(CheckResult.TYPE_RESULT_OK, "Table ["+tablename+"] exists and is accessible", stepMeta); remarks.add(cr); Row r = db.getTableFields(tablename); if (r!=null) { cr = new CheckResult(CheckResult.TYPE_RESULT_OK, "Table ["+tablename+"] is readeable and we got the fields from it.", stepMeta); remarks.add(cr); String error_message = ""; boolean error_found = false; // OK, we have the table fields. // Now see what we can find as previous step... if (prev!=null && prev.size()>0) { cr = new CheckResult(CheckResult.TYPE_RESULT_OK, "Step is connected to previous one, receiving "+prev.size()+" fields", stepMeta); remarks.add(cr); // Starting from prev... for (int i=0;i<prev.size();i++) { Value pv = prev.getValue(i); int idx = r.searchValueIndex(pv.getName()); if (idx<0) { error_message+="\t\t"+pv.getName()+" ("+pv.getTypeDesc()+")"+Const.CR; error_found=true; } } if (error_found) { error_message="Fields in input stream, not found in output table:"+Const.CR+Const.CR+error_message; cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, error_message, stepMeta); remarks.add(cr); } else { cr = new CheckResult(CheckResult.TYPE_RESULT_OK, "All fields, coming from previous steps, are found in the output table", stepMeta); remarks.add(cr); } // Starting from table fields in r... for (int i=0;i<r.size();i++) { Value rv = r.getValue(i); int idx = prev.searchValueIndex(rv.getName()); if (idx<0) { error_message+="\t\t"+rv.getName()+" ("+rv.getTypeDesc()+")"+Const.CR; error_found=true; } } if (error_found) { error_message="Fields in table, not found in input stream:"+Const.CR+Const.CR+error_message; cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, error_message, stepMeta); remarks.add(cr); } else { cr = new CheckResult(CheckResult.TYPE_RESULT_OK, "All fields in the table are found in the input stream, coming from previous steps", stepMeta); remarks.add(cr); } } else { cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, "Couldn't find fields from previous steps, check the hops...!", stepMeta); remarks.add(cr); } } else { cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, "Couldn't read the table info, please check the table-name & permissions.", stepMeta); remarks.add(cr); } } else { cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, "Table ["+tablename+"] doesn't exist or can't be read on this database connection.", stepMeta); remarks.add(cr); } } else { cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, "No table name was entered in this step.", stepMeta); remarks.add(cr); } } catch(KettleException e) { cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, "An error occurred: "+e.getMessage(), stepMeta); remarks.add(cr); } finally { db.disconnect(); } } else { CheckResult cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, "Please select or create a connection to use", stepMeta); remarks.add(cr); } // See if we have input streams leading to this step! if (input.length>0) { CheckResult cr = new CheckResult(CheckResult.TYPE_RESULT_OK, "Step is receiving info from other steps.", stepMeta); remarks.add(cr); } else { CheckResult cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, "No input received from other steps!", stepMeta); remarks.add(cr); } }
public void check(ArrayList remarks, StepMeta stepMeta, Row prev, String input[], String output[], Row info) { if (database!=null) { CheckResult cr = new CheckResult(CheckResult.TYPE_RESULT_OK, "Connection exists", stepMeta); remarks.add(cr); Database db = new Database(database); try { db.connect(); cr = new CheckResult(CheckResult.TYPE_RESULT_OK, "Connection to database OK", stepMeta); remarks.add(cr); if (tablename!=null && tablename.length()!=0) { // Check if this table exists... if (db.checkTableExists(tablename)) { cr = new CheckResult(CheckResult.TYPE_RESULT_OK, "Table ["+tablename+"] exists and is accessible", stepMeta); remarks.add(cr); Row r = db.getTableFields(tablename); if (r!=null) { cr = new CheckResult(CheckResult.TYPE_RESULT_OK, "Table ["+tablename+"] is readeable and we got the fields from it.", stepMeta); remarks.add(cr); String error_message = ""; boolean error_found = false; // OK, we have the table fields. // Now see what we can find as previous step... if (prev!=null && prev.size()>0) { cr = new CheckResult(CheckResult.TYPE_RESULT_OK, "Step is connected to previous one, receiving "+prev.size()+" fields", stepMeta); remarks.add(cr); // Starting from prev... for (int i=0;i<prev.size();i++) { Value pv = prev.getValue(i); int idx = r.searchValueIndex(pv.getName()); if (idx<0) { error_message+="\t\t"+pv.getName()+" ("+pv.getTypeDesc()+")"+Const.CR; error_found=true; } } if (error_found) { error_message="Fields in input stream, not found in output table:"+Const.CR+Const.CR+error_message; cr = new CheckResult(CheckResult.TYPE_RESULT_WARNING, error_message, stepMeta); remarks.add(cr); } else { cr = new CheckResult(CheckResult.TYPE_RESULT_OK, "All fields, coming from previous steps, are found in the output table", stepMeta); remarks.add(cr); } // Starting from table fields in r... for (int i=0;i<r.size();i++) { Value rv = r.getValue(i); int idx = prev.searchValueIndex(rv.getName()); if (idx<0) { error_message+="\t\t"+rv.getName()+" ("+rv.getTypeDesc()+")"+Const.CR; error_found=true; } } if (error_found) { error_message="Fields in table, not found in input stream:"+Const.CR+Const.CR+error_message; cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, error_message, stepMeta); remarks.add(cr); } else { cr = new CheckResult(CheckResult.TYPE_RESULT_OK, "All fields in the table are found in the input stream, coming from previous steps", stepMeta); remarks.add(cr); } } else { cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, "Couldn't find fields from previous steps, check the hops...!", stepMeta); remarks.add(cr); } } else { cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, "Couldn't read the table info, please check the table-name & permissions.", stepMeta); remarks.add(cr); } } else { cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, "Table ["+tablename+"] doesn't exist or can't be read on this database connection.", stepMeta); remarks.add(cr); } } else { cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, "No table name was entered in this step.", stepMeta); remarks.add(cr); } } catch(KettleException e) { cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, "An error occurred: "+e.getMessage(), stepMeta); remarks.add(cr); } finally { db.disconnect(); } } else { CheckResult cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, "Please select or create a connection to use", stepMeta); remarks.add(cr); } // See if we have input streams leading to this step! if (input.length>0) { CheckResult cr = new CheckResult(CheckResult.TYPE_RESULT_OK, "Step is receiving info from other steps.", stepMeta); remarks.add(cr); } else { CheckResult cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, "No input received from other steps!", stepMeta); remarks.add(cr); } }
diff --git a/src/minecraft/co/uk/flansmods/client/tmt/ModelRendererTurbo.java b/src/minecraft/co/uk/flansmods/client/tmt/ModelRendererTurbo.java index 95ae6760..8e116593 100644 --- a/src/minecraft/co/uk/flansmods/client/tmt/ModelRendererTurbo.java +++ b/src/minecraft/co/uk/flansmods/client/tmt/ModelRendererTurbo.java @@ -1,2256 +1,2256 @@ package co.uk.flansmods.client.tmt; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import net.minecraft.client.model.ModelBase; import net.minecraft.client.model.ModelRenderer; import net.minecraft.client.model.TexturedQuad; import net.minecraft.client.renderer.GLAllocation; import net.minecraft.client.renderer.texture.TextureManager; import net.minecraft.client.renderer.entity.RenderManager; import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; import org.lwjgl.opengl.GL11; /** * An extension to the ModelRenderer class. It basically is a copy to ModelRenderer, * however, it contains various new methods to make your models. * <br /><br /> * Since the ModelRendererTurbo class gets loaded during startup, the models made * can be very complex. This is why I can afford to add, for example, Wavefont OBJ * support or have the addSprite method, methods that add a lot of vertices and * polygons. * @author GaryCXJk * */ public class ModelRendererTurbo extends ModelRenderer { public ModelRendererTurbo(ModelBase modelbase, String s) { super(modelbase, s); flip = false; compiled = false; displayList = 0; mirror = false; showModel = true; field_1402_i = false; vertices = new PositionTextureVertex[0]; faces = new TexturedPolygon[0]; forcedRecompile = false; transformGroup = new HashMap<String, TransformGroup>(); transformGroup.put("0", new TransformGroupBone(new Bone(0, 0, 0, 0), 1D)); textureGroup = new HashMap<String, TextureGroup>(); textureGroup.put("0", new TextureGroup()); currentTextureGroup = textureGroup.get("0"); boxName = s; defaultTexture = ""; useLegacyCompiler = false; } public ModelRendererTurbo(ModelBase modelbase) { this(modelbase, null); } /** * Creates a new ModelRenderTurbo object. It requires the coordinates of the * position of the texture. * @param modelbase * @param textureX the x-coordinate on the texture * @param textureY the y-coordinate on the texture */ public ModelRendererTurbo(ModelBase modelbase, int textureX, int textureY) { this(modelbase, textureX, textureY, 64, 32); } /** * Creates a new ModelRenderTurbo object. It requires the coordinates of the * position of the texture, but also allows you to specify the width and height * of the texture, allowing you to use bigger textures instead. * @param modelbase * @param textureX * @param textureY * @param textureU * @param textureV */ public ModelRendererTurbo(ModelBase modelbase, int textureX, int textureY, int textureU, int textureV) { this(modelbase); textureOffsetX = textureX; textureOffsetY = textureY; textureWidth = textureU; textureHeight = textureV; } /** * Creates a new polygon. * @param verts an array of vertices */ public void addPolygon(PositionTextureVertex[] verts) { copyTo(verts, new TexturedPolygon[] {new TexturedPolygon(verts)}); } /** * Creates a new polygon, and adds UV mapping to it. * @param verts an array of vertices * @param uv an array of UV coordinates */ public void addPolygon(PositionTextureVertex[] verts, int[][] uv) { try { for(int i = 0; i < verts.length; i++) { verts[i] = verts[i].setTexturePosition((float)uv[i][0] / textureWidth, (float)uv[i][1] / textureHeight); } } finally { addPolygon(verts); } } /** * Creates a new polygon with a given UV. * @param verts an array of vertices * @param u1 * @param v1 * @param u2 * @param v2 */ public void addPolygon(PositionTextureVertex[] verts, int u1, int v1, int u2, int v2) { copyTo(verts, new TexturedPolygon[] {addPolygonReturn(verts, u1, v1, u2, v2)}); } private TexturedPolygon addPolygonReturn(PositionTextureVertex[] verts, int u1, int v1, int u2, int v2, float q1, float q2, float q3, float q4) { if(verts.length < 3) return null; float uOffs = 1.0F / ((float) textureWidth * 10.0F); float vOffs = 1.0F / ((float) textureHeight * 10.0F); if(verts.length < 4) { float xMin = -1; float yMin = -1; float xMax = 0; float yMax = 0; for(int i = 0; i < verts.length; i++) { float xPos = verts[i].texturePositionX; float yPos = verts[i].texturePositionY; xMax = Math.max(xMax, xPos); xMin = (xMin < -1 ? xPos : Math.min(xMin, xPos)); yMax = Math.max(yMax, yPos); yMin = (yMin < -1 ? yPos : Math.min(yMin, yPos)); } float uMin = (float) u1 / (float) textureWidth + uOffs; float vMin = (float) v1 / (float) textureHeight + vOffs; float uSize = (float) (u2 - u1) / (float) textureWidth - uOffs * 2; float vSize = (float) (v2 - v1) / (float) textureHeight - vOffs * 2; float xSize = xMax - xMin; float ySize = yMax - yMin; for(int i = 0; i < verts.length; i++) { float xPos = verts[i].texturePositionX; float yPos = verts[i].texturePositionY; xPos = (xPos - xMin) / xSize; yPos = (yPos - yMin) / ySize; verts[i] = verts[i].setTexturePosition(uMin + (xPos * uSize), vMin + (yPos * vSize)); } } else { verts[0] = verts[0].setTexturePosition(((float)u2 / (float) textureWidth - uOffs)*q1, ((float)v1 / (float)textureHeight + vOffs)*q1, q1); verts[1] = verts[1].setTexturePosition(((float)u1 / (float) textureWidth + uOffs)*q2, ((float)v1 / (float)textureHeight + vOffs)*q2, q2); verts[2] = verts[2].setTexturePosition(((float)u1 / (float) textureWidth + uOffs)*q3, ((float)v2 / (float)textureHeight - vOffs)*q3, q3); verts[3] = verts[3].setTexturePosition(((float)u2 / (float) textureWidth - uOffs)*q4, ((float)v2 / (float)textureHeight - vOffs)*q4, q4); } return new TexturedPolygon(verts); } private TexturedPolygon addPolygonReturn(PositionTextureVertex[] verts, int u1, int v1, int u2, int v2) { if(verts.length < 3) return null; float uOffs = 1.0F / ((float) textureWidth * 10.0F); float vOffs = 1.0F / ((float) textureHeight * 10.0F); if(verts.length < 4) { float xMin = -1; float yMin = -1; float xMax = 0; float yMax = 0; for(int i = 0; i < verts.length; i++) { float xPos = verts[i].texturePositionX; float yPos = verts[i].texturePositionY; xMax = Math.max(xMax, xPos); xMin = (xMin < -1 ? xPos : Math.min(xMin, xPos)); yMax = Math.max(yMax, yPos); yMin = (yMin < -1 ? yPos : Math.min(yMin, yPos)); } float uMin = (float) u1 / (float) textureWidth + uOffs; float vMin = (float) v1 / (float) textureHeight + vOffs; float uSize = (float) (u2 - u1) / (float) textureWidth - uOffs * 2; float vSize = (float) (v2 - v1) / (float) textureHeight - vOffs * 2; float xSize = xMax - xMin; float ySize = yMax - yMin; for(int i = 0; i < verts.length; i++) { float xPos = verts[i].texturePositionX; float yPos = verts[i].texturePositionY; xPos = (xPos - xMin) / xSize; yPos = (yPos - yMin) / ySize; verts[i] = verts[i].setTexturePosition(uMin + (xPos * uSize), vMin + (yPos * vSize)); } } else { verts[0] = verts[0].setTexturePosition((float)u2 / (float) textureWidth - uOffs, (float)v1 / (float)textureHeight + vOffs); verts[1] = verts[1].setTexturePosition((float)u1 / (float) textureWidth + uOffs, (float)v1 / (float)textureHeight + vOffs); verts[2] = verts[2].setTexturePosition((float)u1 / (float) textureWidth + uOffs, (float)v2 / (float)textureHeight - vOffs); verts[3] = verts[3].setTexturePosition((float)u2 / (float) textureWidth - uOffs, (float)v2 / (float)textureHeight - vOffs); } return new TexturedPolygon(verts); } /** * Adds a rectangular shape. Basically, you can make any eight-pointed shape you want, * as the method requires eight vector coordinates. * @param v a float array with three values, the x, y and z coordinates of the vertex * @param v1 a float array with three values, the x, y and z coordinates of the vertex * @param v2 a float array with three values, the x, y and z coordinates of the vertex * @param v3 a float array with three values, the x, y and z coordinates of the vertex * @param v4 a float array with three values, the x, y and z coordinates of the vertex * @param v5 a float array with three values, the x, y and z coordinates of the vertex * @param v6 a float array with three values, the x, y and z coordinates of the vertex * @param v7 a float array with three values, the x, y and z coordinates of the vertex * @param w the width of the shape, used in determining the texture * @param h the height of the shape, used in determining the texture * @param d the depth of the shape, used in determining the texture */ public void addRectShape(float[] v, float[] v1, float[] v2, float[] v3, float[] v4, float[] v5, float[] v6, float[] v7, int w, int h, int d) { float[] var1 = new float[] {1,1,1,1,1,1,1,1,1,1,1,1}; addRectShape(v, v1, v2, v3, v4, v5, v6, v7, w, h, d, var1); } /** * Adds a rectangular shape. Basically, you can make any eight-pointed shape you want, * as the method requires eight vector coordinates. Also does some special texture mapping. * @param v a float array with three values, the x, y and z coordinates of the vertex * @param v1 a float array with three values, the x, y and z coordinates of the vertex * @param v2 a float array with three values, the x, y and z coordinates of the vertex * @param v3 a float array with three values, the x, y and z coordinates of the vertex * @param v4 a float array with three values, the x, y and z coordinates of the vertex * @param v5 a float array with three values, the x, y and z coordinates of the vertex * @param v6 a float array with three values, the x, y and z coordinates of the vertex * @param v7 a float array with three values, the x, y and z coordinates of the vertex * @param w the width of the shape, used in determining the texture * @param h the height of the shape, used in determining the texture * @param d the depth of the shape, used in determining the texture * @param qParam Array containing the q parameters in the order xBack, xBottom, xFront, xTop, yBack, yFront, yLeft, yRight, zBottom, zLeft, zRight, zTop */ public void addRectShape(float[] v, float[] v1, float[] v2, float[] v3, float[] v4, float[] v5, float[] v6, float[] v7, int w, int h, int d, float[] qParam) { PositionTextureVertex[] verts = new PositionTextureVertex[8]; TexturedPolygon[] poly = new TexturedPolygon[6]; PositionTextureVertex positionTexturevertex = new PositionTextureVertex(v[0], v[1], v[2], 0.0F, 0.0F); PositionTextureVertex positionTexturevertex1 = new PositionTextureVertex(v1[0], v1[1], v1[2], 0.0F, 8F); PositionTextureVertex positionTexturevertex2 = new PositionTextureVertex(v2[0], v2[1], v2[2], 8F, 8F); PositionTextureVertex positionTexturevertex3 = new PositionTextureVertex(v3[0], v3[1], v3[2], 8F, 0.0F); PositionTextureVertex positionTexturevertex4 = new PositionTextureVertex(v4[0], v4[1], v4[2], 0.0F, 0.0F); PositionTextureVertex positionTexturevertex5 = new PositionTextureVertex(v5[0], v5[1], v5[2], 0.0F, 8F); PositionTextureVertex positionTexturevertex6 = new PositionTextureVertex(v6[0], v6[1], v6[2], 8F, 8F); PositionTextureVertex positionTexturevertex7 = new PositionTextureVertex(v7[0], v7[1], v7[2], 8F, 0.0F); verts[0] = positionTexturevertex; verts[1] = positionTexturevertex1; verts[2] = positionTexturevertex2; verts[3] = positionTexturevertex3; verts[4] = positionTexturevertex4; verts[5] = positionTexturevertex5; verts[6] = positionTexturevertex6; verts[7] = positionTexturevertex7; poly[0] = addPolygonReturn(new PositionTextureVertex[] { positionTexturevertex5, positionTexturevertex1, positionTexturevertex2, positionTexturevertex6 }, textureOffsetX + d + w, textureOffsetY + d, textureOffsetX + d + w + d, textureOffsetY + d + h, 1F, qParam[7], qParam[10]*qParam[7], qParam[10]); poly[1] = addPolygonReturn(new PositionTextureVertex[] { positionTexturevertex, positionTexturevertex4, positionTexturevertex7, positionTexturevertex3 }, textureOffsetX + 0, textureOffsetY + d, textureOffsetX + d, textureOffsetY + d + h, qParam[9]*qParam[6], qParam[9], 1F, qParam[6]); poly[2] = addPolygonReturn(new PositionTextureVertex[] { positionTexturevertex5, positionTexturevertex4, positionTexturevertex, positionTexturevertex1 }, textureOffsetX + d, textureOffsetY + 0, textureOffsetX + d + w, textureOffsetY + d, 1F, qParam[8], qParam[1]*qParam[8], qParam[1]); poly[3] = addPolygonReturn(new PositionTextureVertex[] { positionTexturevertex2, positionTexturevertex3, positionTexturevertex7, positionTexturevertex6 }, textureOffsetX + d + w, textureOffsetY + 0, textureOffsetX + d + w + w, textureOffsetY + d, qParam[3], qParam[3]*qParam[11], qParam[11], 1F); poly[4] = addPolygonReturn(new PositionTextureVertex[] { positionTexturevertex1, positionTexturevertex, positionTexturevertex3, positionTexturevertex2 }, textureOffsetX + d, textureOffsetY + d, textureOffsetX + d + w, textureOffsetY + d + h, qParam[0], qParam[0]*qParam[4], qParam[4], 1F); poly[5] = addPolygonReturn(new PositionTextureVertex[] { positionTexturevertex4, positionTexturevertex5, positionTexturevertex6, positionTexturevertex7 }, textureOffsetX + d + w + d, textureOffsetY + d, textureOffsetX + d + w + d + w, textureOffsetY + d + h, qParam[2]*qParam[5], qParam[2], 1F, qParam[5]); if(mirror ^ flip) { for(int l = 0; l < poly.length; l++) { poly[l].flipFace(); } } copyTo(verts, poly); } /** * Adds a new box to the model. * @param x the starting x-position * @param y the starting y-position * @param z the starting z-position * @param w the width (over the x-direction) * @param h the height (over the y-direction) * @param d the depth (over the z-direction) */ public ModelRendererTurbo addBox(float x, float y, float z, int w, int h, int d) { addBox(x, y, z, w, h, d, 0.0F); return this; } /** * Adds a new box to the model. * @param x the starting x-position * @param y the starting y-position * @param z the starting z-position * @param w the width (over the x-direction) * @param h the height (over the y-direction) * @param d the depth (over the z-direction) * @param expansion the expansion of the box. It increases the size in each direction by that many. */ public void addBox(float x, float y, float z, int w, int h, int d, float expansion) { addBox(x, y, z, w, h, d, expansion, 1F); } /** * Adds a new box to the model. * @param x the starting x-position * @param y the starting y-position * @param z the starting z-position * @param w the width (over the x-direction) * @param h the height (over the y-direction) * @param d the depth (over the z-direction) * @param expansion the expansion of the box. It increases the size in each direction by that many. It's independent from the scale. * @param scale */ public void addBox(float x, float y, float z, int w, int h, int d, float expansion, float scale) { float scaleX = (float)w * scale; float scaleY = (float)h * scale; float scaleZ = (float)d * scale; float x1 = x + scaleX; float y1 = y + scaleY; float z1 = z + scaleZ; float expX = expansion + scaleX - (float)w; float expY = expansion + scaleY - (float)h; float expZ = expansion + scaleZ - (float)d; x -= expX; y -= expY; z -= expZ; x1 += expansion; y1 += expansion; z1 += expansion; if(mirror) { float xTemp = x1; x1 = x; x = xTemp; } float[] v = {x, y, z}; float[] v1 = {x1, y, z}; float[] v2 = {x1, y1, z}; float[] v3 = {x, y1, z}; float[] v4 = {x, y, z1}; float[] v5 = {x1, y, z1}; float[] v6 = {x1, y1, z1}; float[] v7 = {x, y1, z1}; addRectShape(v, v1, v2, v3, v4, v5, v6, v7, w, h, d); } /** * Adds a trapezoid-like shape. It's achieved by expanding the shape on one side. * You can use the static variables <code>MR_RIGHT</code>, <code>MR_LEFT</code>, * <code>MR_FRONT</code>, <code>MR_BACK</code>, <code>MR_TOP</code> and * <code>MR_BOTTOM</code>. * @param x the starting x-position * @param y the starting y-position * @param z the starting z-position * @param w the width (over the x-direction) * @param h the height (over the y-direction) * @param d the depth (over the z-direction) * @param scale the "scale" of the box. It only increases the size in each direction by that many. * @param bottomScale the "scale" of the bottom * @param dir the side the scaling is applied to */ public void addTrapezoid(float x, float y, float z, int w, int h, int d, float scale, float bottomScale, int dir) { float f4 = x + (float)w; float f5 = y + (float)h; float f6 = z + (float)d; x -= scale; y -= scale; z -= scale; f4 += scale; f5 += scale; f6 += scale; int m = (mirror ? -1 : 1); if(mirror) { float f7 = f4; f4 = x; x = f7; } float[] v = {x, y, z}; float[] v1 = {f4, y, z}; float[] v2 = {f4, f5, z}; float[] v3 = {x, f5, z}; float[] v4 = {x, y, f6}; float[] v5 = {f4, y, f6}; float[] v6 = {f4, f5, f6}; float[] v7 = {x, f5, f6}; switch(dir) { case MR_RIGHT: v[1] -= bottomScale; v[2] -= bottomScale; v3[1] += bottomScale; v3[2] -= bottomScale; v4[1] -= bottomScale; v4[2] += bottomScale; v7[1] += bottomScale; v7[2] += bottomScale; break; case MR_LEFT: v1[1] -= bottomScale; v1[2] -= bottomScale; v2[1] += bottomScale; v2[2] -= bottomScale; v5[1] -= bottomScale; v5[2] += bottomScale; v6[1] += bottomScale; v6[2] += bottomScale; break; case MR_FRONT: v[0] -= m * bottomScale; v[1] -= bottomScale; v1[0] += m * bottomScale; v1[1] -= bottomScale; v2[0] += m * bottomScale; v2[1] += bottomScale; v3[0] -= m * bottomScale; v3[1] += bottomScale; break; case MR_BACK: v4[0] -= m * bottomScale; v4[1] -= bottomScale; v5[0] += m * bottomScale; v5[1] -= bottomScale; v6[0] += m * bottomScale; v6[1] += bottomScale; v7[0] -= m * bottomScale; v7[1] += bottomScale; break; case MR_TOP: v[0] -= m * bottomScale; v[2] -= bottomScale; v1[0] += m * bottomScale; v1[2] -= bottomScale; v4[0] -= m * bottomScale; v4[2] += bottomScale; v5[0] += m * bottomScale; v5[2] += bottomScale; break; case MR_BOTTOM: v2[0] += m * bottomScale; v2[2] -= bottomScale; v3[0] -= m * bottomScale; v3[2] -= bottomScale; v6[0] += m * bottomScale; v6[2] += bottomScale; v7[0] -= m * bottomScale; v7[2] += bottomScale; break; } float[] qValues = new float[] { Math.abs((v[0] - v1[0])/(v3[0]-v2[0])), Math.abs((v[0] - v1[0])/(v4[0]-v5[0])), Math.abs((v4[0] - v5[0])/(v7[0]-v6[0])), Math.abs((v3[0] - v2[0])/(v7[0]-v6[0])), Math.abs((v[1] - v3[1])/(v1[1]-v2[1])), Math.abs((v4[1] - v7[1])/(v5[1]-v6[1])), Math.abs((v[1] - v3[1])/(v4[1]-v7[1])), Math.abs((v1[1] - v2[1])/(v5[1]-v6[1])), Math.abs((v[2] - v4[2])/(v1[2]-v5[2])), Math.abs((v[2] - v4[2])/(v3[2]-v7[2])), Math.abs((v1[2] - v5[2])/(v2[2]-v6[2])), Math.abs((v3[2] - v7[2])/(v2[2]-v6[2])) }; addRectShape(v, v1, v2, v3, v4, v5, v6, v7, w, h, d, qValues); } /** * Adds a trapezoid-like shape. It's achieved by expanding the shape on one side. * You can use the static variables <code>MR_RIGHT</code>, <code>MR_LEFT</code>, * <code>MR_FRONT</code>, <code>MR_BACK</code>, <code>MR_TOP</code> and * <code>MR_BOTTOM</code>. * @param x the starting x-position * @param y the starting y-position * @param z the starting z-position * @param w the width (over the x-direction) * @param h the height (over the y-direction) * @param d the depth (over the z-direction) * @param scale the "scale" of the box. It only increases the size in each direction by that many. * @param bScale1 the "scale" of the bottom - Top * @param bScale2 the "scale" of the bottom - Bottom * @param bScale3 the "scale" of the bottom - Left * @param bScale4 the "scale" of the bottom - Right * @param dir the side the scaling is applied to */ public void addFlexBox(float x, float y, float z, int w, int h, int d, float scale, float bScale1, float bScale2, float bScale3, float bScale4, int dir) { float f4 = x + (float)w; float f5 = y + (float)h; float f6 = z + (float)d; x -= scale; y -= scale; z -= scale; f4 += scale; f5 += scale; f6 += scale; int m = (mirror ? -1 : 1); if(mirror) { float f7 = f4; f4 = x; x = f7; } float[] v = {x, y, z}; float[] v1 = {f4, y, z}; float[] v2 = {f4, f5, z}; float[] v3 = {x, f5, z}; float[] v4 = {x, y, f6}; float[] v5 = {f4, y, f6}; float[] v6 = {f4, f5, f6}; float[] v7 = {x, f5, f6}; switch(dir) { case MR_RIGHT: v[1] -= bScale1; v[2] -= bScale3; v3[1] += bScale2; v3[2] -= bScale3; v4[1] -= bScale1; v4[2] += bScale4; v7[1] += bScale2; v7[2] += bScale4; break; case MR_LEFT: v1[1] -= bScale1; v1[2] -= bScale3; v2[1] += bScale2; v2[2] -= bScale3; v5[1] -= bScale1; v5[2] += bScale4; v6[1] += bScale2; v6[2] += bScale4; break; case MR_FRONT: v[0] -= m * bScale4; v[1] -= bScale1; v1[0] += m * bScale3; v1[1] -= bScale1; v2[0] += m * bScale3; v2[1] += bScale2; v3[0] -= m * bScale4; v3[1] += bScale2; break; case MR_BACK: v4[0] -= m * bScale4; v4[1] -= bScale1; v5[0] += m * bScale3; v5[1] -= bScale1; v6[0] += m * bScale3; v6[1] += bScale2; v7[0] -= m * bScale4; v7[1] += bScale2; break; case MR_TOP: v[0] -= m * bScale1; v[2] -= bScale3; v1[0] += m * bScale2; v1[2] -= bScale3; v4[0] -= m * bScale1; v4[2] += bScale4; v5[0] += m * bScale2; v5[2] += bScale4; break; case MR_BOTTOM: v2[0] += m * bScale2; v2[2] -= bScale3; v3[0] -= m * bScale1; v3[2] -= bScale3; v6[0] += m * bScale2; v6[2] += bScale4; v7[0] -= m * bScale1; v7[2] += bScale4; break; } float[] qValues = new float[] { Math.abs((v[0] - v1[0])/(v3[0]-v2[0])), Math.abs((v[0] - v1[0])/(v4[0]-v5[0])), Math.abs((v4[0] - v5[0])/(v7[0]-v6[0])), Math.abs((v3[0] - v2[0])/(v7[0]-v6[0])), Math.abs((v[1] - v3[1])/(v1[1]-v2[1])), Math.abs((v4[1] - v7[1])/(v5[1]-v6[1])), Math.abs((v[1] - v3[1])/(v4[1]-v7[1])), Math.abs((v1[1] - v2[1])/(v5[1]-v6[1])), Math.abs((v[2] - v4[2])/(v1[2]-v5[2])), Math.abs((v[2] - v4[2])/(v3[2]-v7[2])), Math.abs((v1[2] - v5[2])/(v2[2]-v6[2])), Math.abs((v3[2] - v7[2])/(v2[2]-v6[2])) }; addRectShape(v, v1, v2, v3, v4, v5, v6, v7, w, h, d, qValues); } /** * Adds a trapezoid-like shape. It's achieved by expanding the shape on one side. * You can use the static variables <code>MR_RIGHT</code>, <code>MR_LEFT</code>, * <code>MR_FRONT</code>, <code>MR_BACK</code>, <code>MR_TOP</code> and * <code>MR_BOTTOM</code>. * @param x the starting x-position * @param y the starting y-position * @param z the starting z-position * @param w the width (over the x-direction) * @param h the height (over the y-direction) * @param d the depth (over the z-direction) * @param scale the "scale" of the box. It only increases the size in each direction by that many. * @param bScale1 the "scale" of the bottom - Top * @param bScale2 the "scale" of the bottom - Bottom * @param bScale3 the "scale" of the bottom - Left * @param bScale4 the "scale" of the bottom - Right * @param fScale1 the "scale" of the top - Left * @param fScale2 the "scale" of the top - Right * @param dir the side the scaling is applied to */ public void addFlexTrapezoid(float x, float y, float z, int w, int h, int d, float scale, float bScale1, float bScale2, float bScale3, float bScale4, float fScale1, float fScale2, int dir) { float f4 = x + (float)w; float f5 = y + (float)h; float f6 = z + (float)d; x -= scale; y -= scale; z -= scale; f4 += scale; f5 += scale; f6 += scale; int m = (mirror ? -1 : 1); if(mirror) { float f7 = f4; f4 = x; x = f7; } float[] v = {x, y, z}; float[] v1 = {f4, y, z}; float[] v2 = {f4, f5, z}; float[] v3 = {x, f5, z}; float[] v4 = {x, y, f6}; float[] v5 = {f4, y, f6}; float[] v6 = {f4, f5, f6}; float[] v7 = {x, f5, f6}; switch(dir) { case MR_RIGHT: v[2] -= fScale1; v1[2] -= fScale1; v4[2] += fScale2; v5[2] += fScale2; v[1] -= bScale1; v[2] -= bScale3; v3[1] += bScale2; v3[2] -= bScale3; v4[1] -= bScale1; v4[2] += bScale4; v7[1] += bScale2; v7[2] += bScale4; break; case MR_LEFT: v[2] -= fScale1; v1[2] -= fScale1; v4[2] += fScale2; v5[2] += fScale2; v1[1] -= bScale1; v1[2] -= bScale3; v2[1] += bScale2; v2[2] -= bScale3; v5[1] -= bScale1; v5[2] += bScale4; v6[1] += bScale2; v6[2] += bScale4; break; case MR_FRONT: - v2[1] += fScale1; - v3[1] += fScale2; + v1[1] -= fScale1; + v5[1] -= fScale1; + v2[1] += fScale2; v6[1] += fScale2; - v7[1] += fScale1; v[0] -= m * bScale4; v[1] -= bScale1; v1[0] += m * bScale3; v1[1] -= bScale1; v2[0] += m * bScale3; v2[1] += bScale2; v3[0] -= m * bScale4; v3[1] += bScale2; break; case MR_BACK: - v2[1] += fScale1; - v3[1] += fScale2; + v1[1] -= fScale1; + v5[1] -= fScale1; + v2[1] += fScale2; v6[1] += fScale2; - v7[1] += fScale1; v4[0] -= m * bScale4; v4[1] -= bScale1; v5[0] += m * bScale3; v5[1] -= bScale1; v6[0] += m * bScale3; v6[1] += bScale2; v7[0] -= m * bScale4; v7[1] += bScale2; break; case MR_TOP: v1[2] -= fScale1; v2[2] -= fScale1; v5[2] += fScale2; v6[2] += fScale2; v[0] -= m * bScale1; v[2] -= bScale3; v1[0] += m * bScale2; v1[2] -= bScale3; v4[0] -= m * bScale1; v4[2] += bScale4; v5[0] += m * bScale2; v5[2] += bScale4; break; case MR_BOTTOM: v1[2] -= fScale1; v2[2] -= fScale1; v5[2] += fScale2; v6[2] += fScale2; v2[0] += m * bScale2; v2[2] -= bScale3; v3[0] -= m * bScale1; v3[2] -= bScale3; v6[0] += m * bScale2; v6[2] += bScale4; v7[0] -= m * bScale1; v7[2] += bScale4; break; } float[] qValues = new float[] { Math.abs((v[0] - v1[0])/(v3[0]-v2[0])), Math.abs((v[0] - v1[0])/(v4[0]-v5[0])), Math.abs((v4[0] - v5[0])/(v7[0]-v6[0])), Math.abs((v3[0] - v2[0])/(v7[0]-v6[0])), Math.abs((v[1] - v3[1])/(v1[1]-v2[1])), Math.abs((v4[1] - v7[1])/(v5[1]-v6[1])), Math.abs((v[1] - v3[1])/(v4[1]-v7[1])), Math.abs((v1[1] - v2[1])/(v5[1]-v6[1])), Math.abs((v[2] - v4[2])/(v1[2]-v5[2])), Math.abs((v[2] - v4[2])/(v3[2]-v7[2])), Math.abs((v1[2] - v5[2])/(v2[2]-v6[2])), Math.abs((v3[2] - v7[2])/(v2[2]-v6[2])) }; addRectShape(v, v1, v2, v3, v4, v5, v6, v7, w, h, d, qValues); } /** * Adds a trapezoid-like shape. It's achieved by expanding the shape on one side. * You can use the static variables <code>MR_RIGHT</code>, <code>MR_LEFT</code>, * <code>MR_FRONT</code>, <code>MR_BACK</code>, <code>MR_TOP</code> and * <code>MR_BOTTOM</code>. * @param x the starting x-position * @param y the starting y-position * @param z the starting z-position * @param w the width (over the x-direction) * @param h the height (over the y-direction) * @param d the depth (over the z-direction) * @param scale the "scale" of the box. It only increases the size in each direction by that many. * @param x0,y0,z0 - x7,y7,z7 the modifiers of the box corners. each corner can changed seperat by x/y/z values */ public void addShapeBox(float x, float y, float z, int w, int h, int d, float scale, float x0, float y0, float z0, float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3, float x4, float y4, float z4, float x5, float y5, float z5, float x6, float y6, float z6, float x7, float y7, float z7) { float f4 = x + (float)w; float f5 = y + (float)h; float f6 = z + (float)d; x -= scale; y -= scale; z -= scale; f4 += scale; f5 += scale; f6 += scale; int m = (mirror ? -1 : 1); if(mirror) { float f7 = f4; f4 = x; x = f7; } float[] v = {x - x0, y - y0, z - z0}; float[] v1 = {f4 + x1, y - y1, z - z1}; float[] v2 = {f4 + x5, f5 + y5, z - z5}; float[] v3 = {x - x4, f5 + y4, z - z4}; float[] v4 = {x - x3, y - y3, f6 + z3}; float[] v5 = {f4 + x2, y - y2, f6 + z2}; float[] v6 = {f4 + x6, f5 + y6, f6 + z6}; float[] v7 = {x - x7, f5 + y7, f6 + z7}; float[] qValues = new float[] { Math.abs((v[0] - v1[0])/(v3[0]-v2[0])), Math.abs((v[0] - v1[0])/(v4[0]-v5[0])), Math.abs((v4[0] - v5[0])/(v7[0]-v6[0])), Math.abs((v3[0] - v2[0])/(v7[0]-v6[0])), Math.abs((v[1] - v3[1])/(v1[1]-v2[1])), Math.abs((v4[1] - v7[1])/(v5[1]-v6[1])), Math.abs((v[1] - v3[1])/(v4[1]-v7[1])), Math.abs((v1[1] - v2[1])/(v5[1]-v6[1])), Math.abs((v[2] - v4[2])/(v1[2]-v5[2])), Math.abs((v[2] - v4[2])/(v3[2]-v7[2])), Math.abs((v1[2] - v5[2])/(v2[2]-v6[2])), Math.abs((v3[2] - v7[2])/(v2[2]-v6[2])) }; addRectShape(v, v1, v2, v3, v4, v5, v6, v7, w, h, d, qValues); } /** * Creates a shape from a 2D vector shape. * @param x the starting x position * @param y the starting y position * @param z the starting z position * @param coordinates an array of coordinates that form the shape * @param depth the depth of the shape * @param shapeTextureWidth the width of the texture of one side of the shape * @param shapeTextureHeight the height of the texture the shape * @param sideTextureWidth the width of the texture of the side of the shape * @param sideTextureHeight the height of the texture of the side of the shape * @param direction the direction the starting point of the shape is facing */ public void addShape3D(float x, float y, float z, Coord2D[] coordinates, float depth, int shapeTextureWidth, int shapeTextureHeight, int sideTextureWidth, int sideTextureHeight, int direction) { addShape3D(x, y, z, coordinates, depth, shapeTextureWidth, shapeTextureHeight, sideTextureWidth, sideTextureHeight, direction, null); } /** * Creates a shape from a 2D vector shape. * @param x the starting x position * @param y the starting y position * @param z the starting z position * @param coordinates an array of coordinates that form the shape * @param depth the depth of the shape * @param shapeTextureWidth the width of the texture of one side of the shape * @param shapeTextureHeight the height of the texture the shape * @param sideTextureWidth the width of the texture of the side of the shape * @param sideTextureHeight the height of the texture of the side of the shape * @param direction the direction the starting point of the shape is facing * @param faceLengths An array with the length of each face. Used to set * the texture width of each face on the side manually. */ public void addShape3D(float x, float y, float z, Coord2D[] coordinates, float depth, int shapeTextureWidth, int shapeTextureHeight, int sideTextureWidth, int sideTextureHeight, int direction, float[] faceLengths) { addShape3D(x, y, z, new Shape2D(coordinates), depth, shapeTextureWidth, shapeTextureHeight, sideTextureWidth, sideTextureHeight, direction, faceLengths); } /** * Creates a shape from a 2D vector shape. * @param x the starting x position * @param y the starting y position * @param z the starting z position * @param coordinates an ArrayList of coordinates that form the shape * @param depth the depth of the shape * @param shapeTextureWidth the width of the texture of one side of the shape * @param shapeTextureHeight the height of the texture the shape * @param sideTextureWidth the width of the texture of the side of the shape * @param sideTextureHeight the height of the texture of the side of the shape * @param direction the direction the starting point of the shape is facing */ public void addShape3D(float x, float y, float z, ArrayList<Coord2D> coordinates, float depth, int shapeTextureWidth, int shapeTextureHeight, int sideTextureWidth, int sideTextureHeight, int direction) { addShape3D(x, y, z, coordinates, depth, shapeTextureWidth, shapeTextureHeight, sideTextureWidth, sideTextureHeight, direction, null); } /** * Creates a shape from a 2D vector shape. * @param x the starting x position * @param y the starting y position * @param z the starting z position * @param coordinates an ArrayList of coordinates that form the shape * @param depth the depth of the shape * @param shapeTextureWidth the width of the texture of one side of the shape * @param shapeTextureHeight the height of the texture the shape * @param sideTextureWidth the width of the texture of the side of the shape * @param sideTextureHeight the height of the texture of the side of the shape * @param direction the direction the starting point of the shape is facing * @param faceLengths An array with the length of each face. Used to set * the texture width of each face on the side manually. */ public void addShape3D(float x, float y, float z, ArrayList<Coord2D> coordinates, float depth, int shapeTextureWidth, int shapeTextureHeight, int sideTextureWidth, int sideTextureHeight, int direction, float[] faceLengths) { addShape3D(x, y, z, new Shape2D(coordinates), depth, shapeTextureWidth, shapeTextureHeight, sideTextureWidth, sideTextureHeight, direction, faceLengths); } /** * Creates a shape from a 2D vector shape. * @param x the starting x position * @param y the starting y position * @param z the starting z position * @param shape a Shape2D which contains the coordinates of the shape points * @param depth the depth of the shape * @param shapeTextureWidth the width of the texture of one side of the shape * @param shapeTextureHeight the height of the texture the shape * @param sideTextureWidth the width of the texture of the side of the shape * @param sideTextureHeight the height of the texture of the side of the shape * @param direction the direction the starting point of the shape is facing */ public void addShape3D(float x, float y, float z, Shape2D shape, float depth, int shapeTextureWidth, int shapeTextureHeight, int sideTextureWidth, int sideTextureHeight, int direction) { addShape3D(x, y, z, shape, depth, shapeTextureWidth, shapeTextureHeight, sideTextureWidth, sideTextureHeight, direction, null); } /** * Creates a shape from a 2D vector shape. * @param x the starting x position * @param y the starting y position * @param z the starting z position * @param shape a Shape2D which contains the coordinates of the shape points * @param depth the depth of the shape * @param shapeTextureWidth the width of the texture of one side of the shape * @param shapeTextureHeight the height of the texture the shape * @param sideTextureWidth the width of the texture of the side of the shape * @param sideTextureHeight the height of the texture of the side of the shape * @param direction the direction the starting point of the shape is facing * @param faceLengths An array with the length of each face. Used to set * the texture width of each face on the side manually. */ public void addShape3D(float x, float y, float z, Shape2D shape, float depth, int shapeTextureWidth, int shapeTextureHeight, int sideTextureWidth, int sideTextureHeight, int direction, float[] faceLengths) { float rotX = 0; float rotY = 0; float rotZ = 0; switch(direction) { case MR_LEFT: rotY = pi / 2; break; case MR_RIGHT: rotY = -pi / 2; break; case MR_TOP: rotX = pi / 2; break; case MR_BOTTOM: rotX = -pi / 2; break; case MR_FRONT: rotY = pi; break; case MR_BACK: break; } addShape3D(x, y, z, shape, depth, shapeTextureWidth, shapeTextureHeight, sideTextureWidth, sideTextureHeight, rotX, rotY, rotZ, faceLengths); } /** * Creates a shape from a 2D vector shape. * @param x the starting x position * @param y the starting y position * @param z the starting z position * @param shape a Shape2D which contains the coordinates of the shape points * @param depth the depth of the shape * @param shapeTextureWidth the width of the texture of one side of the shape * @param shapeTextureHeight the height of the texture the shape * @param sideTextureWidth the width of the texture of the side of the shape * @param sideTextureHeight the height of the texture of the side of the shape * @param rotX the rotation around the x-axis * @param rotY the rotation around the y-axis * @param rotZ the rotation around the z-axis */ public void addShape3D(float x, float y, float z, Shape2D shape, float depth, int shapeTextureWidth, int shapeTextureHeight, int sideTextureWidth, int sideTextureHeight, float rotX, float rotY, float rotZ) { addShape3D(x, y, z, shape, depth, shapeTextureWidth, shapeTextureHeight, sideTextureWidth, sideTextureHeight, rotX, rotY, rotZ, null); } public void addShape3D(float x, float y, float z, Shape2D shape, float depth, int shapeTextureWidth, int shapeTextureHeight, int sideTextureWidth, int sideTextureHeight, float rotX, float rotY, float rotZ, float[] faceLengths) { Shape3D shape3D = shape.extrude(x, y, z, rotX, rotY, rotZ, depth, textureOffsetX, textureOffsetY, textureWidth, textureHeight, shapeTextureWidth, shapeTextureHeight, sideTextureWidth, sideTextureHeight, faceLengths); if(flip) { for(int idx = 0; idx < shape3D.faces.length; idx++) { shape3D.faces[idx].flipFace(); } } copyTo(shape3D.vertices, shape3D.faces); } /** * Adds a cube the size of one pixel. It will take a pixel from the texture and * uses that as the texture of said cube. The accurate name would actually be * "addVoxel". This method has been added to make it more compatible with Techne, * and allows for easy single-colored boxes. * @param x the starting x-position * @param y the starting y-position * @param z the starting z-position * @param width the width of the box * @param height the height of the box * @param length the length of the box */ public void addPixel(float x, float y, float z, float width, float height, float length) { addPixel(x, y, z, new float[] {width, height, length}, textureOffsetX, textureOffsetY); } /** * Adds a cube the size of one pixel. It will take a pixel from the texture and * uses that as the texture of said cube. The accurate name would actually be * "addVoxel". It will not overwrite the model data, but rather, it will add to * the model. * @param x the starting x-position * @param y the starting y-position * @param z the starting z-position * @param scale the "scale" of the cube, where scale is a float integer consisting of three values * @param w the x-coordinate on the texture * @param h the y-coordinate on the texture */ public void addPixel(float x, float y, float z, float[] scale, int w, int h) { PositionTextureVertex[] verts = new PositionTextureVertex[8]; TexturedPolygon[] poly = new TexturedPolygon[6]; float x1 = x + scale[0]; float y1 = y + scale[1]; float z1 = z + scale[2]; float[] f = {x, y, z}; float[] f1 = {x1, y, z}; float[] f2 = {x1, y1, z}; float[] f3 = {x, y1, z}; float[] f4 = {x, y, z1}; float[] f5 = {x1, y, z1}; float[] f6 = {x1, y1, z1}; float[] f7 = {x, y1, z1}; PositionTextureVertex positionTexturevertex = new PositionTextureVertex(f[0], f[1], f[2], 0.0F, 0.0F); PositionTextureVertex positionTexturevertex1 = new PositionTextureVertex(f1[0], f1[1], f1[2], 0.0F, 8F); PositionTextureVertex positionTexturevertex2 = new PositionTextureVertex(f2[0], f2[1], f2[2], 8F, 8F); PositionTextureVertex positionTexturevertex3 = new PositionTextureVertex(f3[0], f3[1], f3[2], 8F, 0.0F); PositionTextureVertex positionTexturevertex4 = new PositionTextureVertex(f4[0], f4[1], f4[2], 0.0F, 0.0F); PositionTextureVertex positionTexturevertex5 = new PositionTextureVertex(f5[0], f5[1], f5[2], 0.0F, 8F); PositionTextureVertex positionTexturevertex6 = new PositionTextureVertex(f6[0], f6[1], f6[2], 8F, 8F); PositionTextureVertex positionTexturevertex7 = new PositionTextureVertex(f7[0], f7[1], f7[2], 8F, 0.0F); verts[0] = positionTexturevertex; verts[1] = positionTexturevertex1; verts[2] = positionTexturevertex2; verts[3] = positionTexturevertex3; verts[4] = positionTexturevertex4; verts[5] = positionTexturevertex5; verts[6] = positionTexturevertex6; verts[7] = positionTexturevertex7; poly[0] = addPolygonReturn(new PositionTextureVertex[] { positionTexturevertex5, positionTexturevertex1, positionTexturevertex2, positionTexturevertex6 }, w, h, w + 1, h + 1); poly[1] = addPolygonReturn(new PositionTextureVertex[] { positionTexturevertex, positionTexturevertex4, positionTexturevertex7, positionTexturevertex3 }, w, h, w + 1, h + 1); poly[2] = addPolygonReturn(new PositionTextureVertex[] { positionTexturevertex5, positionTexturevertex4, positionTexturevertex, positionTexturevertex1 }, w, h, w + 1, h + 1); poly[3] = addPolygonReturn(new PositionTextureVertex[] { positionTexturevertex2, positionTexturevertex3, positionTexturevertex7, positionTexturevertex6 }, w, h, w + 1, h + 1); poly[4] = addPolygonReturn(new PositionTextureVertex[] { positionTexturevertex1, positionTexturevertex, positionTexturevertex3, positionTexturevertex2 }, w, h, w + 1, h + 1); poly[5] = addPolygonReturn(new PositionTextureVertex[] { positionTexturevertex4, positionTexturevertex5, positionTexturevertex6, positionTexturevertex7 }, w, h, w + 1, h + 1); copyTo(verts, poly); } /** * Creates a model shaped like the exact image on the texture. Note that this method will * increase the amount of quads on your model, which could effectively slow down your * PC, so unless it is really a necessity to use it, I'd suggest you avoid using this * method to create your model. * @param x the starting x-position * @param y the starting y-position * @param z the starting z-position * @param w the width of the sprite * @param h the height of the sprite * @param expansion the expansion of the sprite. It only increases the size in each direction by that many. */ public void addSprite(float x, float y, float z, int w, int h, float expansion) { addSprite(x, y, z, w, h, 1, false, false, false, false, false, expansion); } /** * Creates a model shaped like the exact image on the texture. Note that this method will * increase the amount of quads on your model, which could effectively slow down your * PC, so unless it is really a necessity to use it, I'd suggest you avoid using this * method to create your model. * @param x the starting x-position * @param y the starting y-position * @param z the starting z-position * @param w the width of the sprite * @param h the height of the sprite * @param rotX a boolean to define if it rotates 90 degrees around its yaw-axis * @param rotY a boolean to define if it rotates 90 degrees around its pitch-axis * @param rotZ a boolean to define if it rotates 90 degrees around its roll-axis * @param mirrorX a boolean to define if the sprite should be mirrored * @param mirrorY a boolean to define if the sprite should be flipped * @param expansion the expansion of the sprite. It only increases the size in each direction by that many. */ public void addSprite(float x, float y, float z, int w, int h, boolean rotX, boolean rotY, boolean rotZ, boolean mirrorX, boolean mirrorY, float expansion) { addSprite(x, y, z, w, h, 1, rotX, rotY, rotZ, mirrorX, mirrorY, expansion); } /** * Creates a model shaped like the exact image on the texture. Note that this method will * increase the amount of quads on your model, which could effectively slow down your * PC, so unless it is really a necessity to use it, I'd suggest you avoid using this * method to create your model. * @param x the starting x-position * @param y the starting y-position * @param z the starting z-position * @param w the width of the sprite * @param h the height of the sprite * @param d the depth of the shape itself * @param rotX a boolean to define if it rotates 90 degrees around its yaw-axis * @param rotY a boolean to define if it rotates 90 degrees around its pitch-axis * @param rotZ a boolean to define if it rotates 90 degrees around its roll-axis * @param mirrorX a boolean to define if the sprite should be mirrored * @param mirrorY a boolean to define if the sprite should be flipped * @param expansion the expansion of the sprite. It only increases the size in each direction by that many. */ public void addSprite(float x, float y, float z, int w, int h, int d, boolean rotX, boolean rotY, boolean rotZ, boolean mirrorX, boolean mirrorY, float expansion) { addSprite(x, y, z, w, h, d, 1.0F, rotX, rotY, rotZ, mirrorX, mirrorY, expansion); } /** * Creates a model shaped like the exact image on the texture. Note that this method will * increase the amount of quads on your model, which could effectively slow down your * PC, so unless it is really a necessity to use it, I'd suggest you avoid using this * method to create your model. * @param x the starting x-position * @param y the starting y-position * @param z the starting z-position * @param w the width of the sprite * @param h the height of the sprite * @param d the depth of the shape itself * @param pixelScale the scale of each individual pixel * @param rotX a boolean to define if it rotates 90 degrees around its yaw-axis * @param rotY a boolean to define if it rotates 90 degrees around its pitch-axis * @param rotZ a boolean to define if it rotates 90 degrees around its roll-axis * @param mirrorX a boolean to define if the sprite should be mirrored * @param mirrorY a boolean to define if the sprite should be flipped * @param expansion the expansion of the sprite. It only increases the size in each direction by that many. */ public void addSprite(float x, float y, float z, int w, int h, int d, float pixelScale, boolean rotX, boolean rotY, boolean rotZ, boolean mirrorX, boolean mirrorY, float expansion) { String[] mask = new String[h]; char[] str = new char[w]; Arrays.fill(str, '1'); Arrays.fill(mask, new String(str)); addSprite(x, y, z, mask, d, pixelScale, rotX, rotY, rotZ, mirrorX, mirrorY, expansion); } /** * Creates a model shaped like the exact image on the texture. Note that this method will * increase the amount of quads on your model, which could effectively slow down your * PC, so unless it is really a necessity to use it, I'd suggest you avoid using this * method to create your model. * <br /><br /> * This method uses a mask string. This way you can reduce the amount of quads used. To * use this, create a String array, where you use a 1 to signify that the pixel will be * drawn. Any other character will cause that pixel to not be drawn. * @param x the starting x-position * @param y the starting y-position * @param z the starting z-position * @param mask an array with the mask string * @param d the depth of the shape itself * @param pixelScale the scale of each individual pixel * @param rotX a boolean to define if it rotates 90 degrees around its yaw-axis * @param rotY a boolean to define if it rotates 90 degrees around its pitch-axis * @param rotZ a boolean to define if it rotates 90 degrees around its roll-axis * @param mirrorX a boolean to define if the sprite should be mirrored * @param mirrorY a boolean to define if the sprite should be flipped * @param expansion the expansion of the sprite. It only increases the size in each direction by that many. */ public void addSprite(float x, float y, float z, String[] mask, int d, float pixelScale, boolean rotX, boolean rotY, boolean rotZ, boolean mirrorX, boolean mirrorY, float expansion) { int w = mask[0].length(); int h = mask.length; float x1 = x - expansion; float y1 = y - expansion; float z1 = z - expansion; int wDir = 0; int hDir = 0; int dDir = 0; float wScale = 1F + (expansion / ((float) w * pixelScale)); float hScale = 1F + (expansion / ((float) h * pixelScale)); if(!rotX) { if(!rotY) { if(!rotZ) { wDir = 0; hDir = 1; dDir = 2; } else { wDir = 1; hDir = 0; dDir = 2; } } else { if(!rotZ) { wDir = 2; hDir = 1; dDir = 0; } else { wDir = 2; hDir = 0; dDir = 1; } } } else { if(!rotY) { if(!rotZ) { wDir = 0; hDir = 2; dDir = 1; } else { wDir = 1; hDir = 2; dDir = 0; } } else { if(!rotZ) { wDir = 2; hDir = 0; dDir = 1; } else { wDir = 2; hDir = 1; dDir = 0; } } } int texStartX = textureOffsetX + (mirrorX ? w * 1 - 1 : 0); int texStartY = textureOffsetY + (mirrorY ? h * 1 - 1 : 0); int texDirX = (mirrorX ? -1 : 1); int texDirY = (mirrorY ? -1 : 1); float wVoxSize = getPixelSize(wScale, hScale, d * pixelScale + expansion * 2, 0, 1, wDir, 1, 1); float hVoxSize = getPixelSize(wScale, hScale, d * pixelScale + expansion * 2, 0, 1, hDir, 1, 1); float dVoxSize = getPixelSize(wScale, hScale, d * pixelScale + expansion * 2, 0, 1, dDir, 1, 1); for(int i = 0; i < w; i++) { for(int j = 0; j < h; j++) { if(mask[j].charAt(i) == '1') { addPixel(x1 + getPixelSize(wScale, hScale, 0, wDir, hDir, 0, i, j), y1 + getPixelSize(wScale, hScale, 0, wDir, hDir, 1, i, j), z1 + getPixelSize(wScale, hScale, 0, wDir, hDir, 2, i, j), new float[] {wVoxSize, hVoxSize, dVoxSize}, texStartX + texDirX * i, texStartY + texDirY * j); } } } } private float getPixelSize(float wScale, float hScale, float dScale, int wDir, int hDir, int checkDir, int texPosX, int texPosY) { return (wDir == checkDir ? wScale * texPosX : (hDir == checkDir ? hScale * texPosY : dScale)); } /** * Adds a spherical shape. * @param x * @param y * @param z * @param r * @param segs * @param rings * @param textureW * @param textureH */ public void addSphere(float x, float y, float z, float r, int segs, int rings, int textureW, int textureH) { if(segs < 3) segs = 3; rings++; PositionTextureVertex[] tempVerts = new PositionTextureVertex[segs * (rings - 1) + 2]; TexturedPolygon[] poly = new TexturedPolygon[segs * rings]; tempVerts[0] = new PositionTextureVertex(x, y - r, z, 0, 0); tempVerts[tempVerts.length - 1] = new PositionTextureVertex(x, y + r, z, 0, 0); float uOffs = 1.0F / ((float) textureWidth * 10.0F); float vOffs = 1.0F / ((float) textureHeight * 10.0F); float texW = (float) textureW / (float)textureWidth - 2F * uOffs; float texH = (float) textureH / (float)textureHeight - 2F * vOffs; float segW = texW / (float) segs; float segH = texH / (float) rings; float startU = (float) textureOffsetX / (float) textureWidth; float startV = (float) textureOffsetY / (float) textureHeight; int currentFace = 0; for(int j = 1; j < rings; j++) { for(int i = 0; i < segs; i++) { float yWidth = MathHelper.cos(-pi / 2 + (pi / (float)rings) * (float) j); float yHeight = MathHelper.sin(-pi / 2 + (pi / (float)rings) * (float) j); float xSize = MathHelper.sin((pi / (float)segs) * i * 2F + pi) * yWidth; float zSize = -MathHelper.cos((pi / (float)segs) * i * 2F + pi) * yWidth; int curVert = 1 + i + segs * (j - 1); tempVerts[curVert] = new PositionTextureVertex(x + xSize * r, y + yHeight * r, z + zSize * r, 0, 0); if(i > 0) { PositionTextureVertex[] verts; if(j == 1) { verts = new PositionTextureVertex[4]; verts[0] = tempVerts[curVert].setTexturePosition(startU + segW * i, startV + segH * j); verts[1] = tempVerts[curVert - 1].setTexturePosition(startU + segW * (i - 1), startV + segH * j); verts[2] = tempVerts[0].setTexturePosition(startU + segW * (i - 1), startV); verts[3] = tempVerts[0].setTexturePosition(startU + segW + segW * i, startV); } else { verts = new PositionTextureVertex[4]; verts[0] = tempVerts[curVert].setTexturePosition(startU + segW * i, startV + segH * j); verts[1] = tempVerts[curVert - 1].setTexturePosition(startU + segW * (i - 1), startV + segH * j); verts[2] = tempVerts[curVert - 1 - segs].setTexturePosition(startU + segW * (i - 1), startV + segH * (j - 1)); verts[3] = tempVerts[curVert - segs].setTexturePosition(startU + segW * i, startV + segH * (j - 1)); } poly[currentFace] = new TexturedPolygon(verts); currentFace++; } } PositionTextureVertex[] verts; if(j == 1) { verts = new PositionTextureVertex[4]; verts[0] = tempVerts[1].setTexturePosition(startU + segW * segs, startV + segH * j); verts[1] = tempVerts[segs].setTexturePosition(startU + segW * (segs - 1), startV + segH * j); verts[2] = tempVerts[0].setTexturePosition(startU + segW * (segs - 1), startV); verts[3] = tempVerts[0].setTexturePosition(startU + segW * segs, startV); } else { verts = new PositionTextureVertex[4]; verts[0] = tempVerts[1 + segs * (j - 1)].setTexturePosition(startU + texW, startV + segH * j); verts[1] = tempVerts[segs * (j - 1) + segs].setTexturePosition(startU + texW - segW, startV + segH * j); verts[2] = tempVerts[segs * (j - 1)].setTexturePosition(startU + texW - segW, startV + segH * (j - 1)); verts[3] = tempVerts[1 + segs * (j - 1) - segs].setTexturePosition(startU + texW, startV + segH * (j - 1)); } poly[currentFace] = new TexturedPolygon(verts); currentFace++; } for(int i = 0; i < segs; i++) { PositionTextureVertex[] verts = new PositionTextureVertex[3]; int curVert = tempVerts.length - (segs + 1); verts[0] = tempVerts[tempVerts.length - 1].setTexturePosition(startU + segW * (i + 0.5F), startV + texH); verts[1] = tempVerts[curVert + i].setTexturePosition(startU + segW * i, startV + texH - segH); verts[2] = tempVerts[curVert + ((i + 1) % segs)].setTexturePosition(startU + segW * (i + 1), startV + texH - segH); poly[currentFace] = new TexturedPolygon(verts); currentFace++; } copyTo(tempVerts, poly); } /** * Adds a cone. * @param x the x-position of the base * @param y the y-position of the base * @param z the z-position of the base * @param radius the radius of the cylinder * @param length the length of the cylinder * @param segments the amount of segments the cylinder is made of */ public void addCone(float x, float y, float z, float radius, float length, int segments) { addCone(x, y, z, radius, length, segments, 1F); } /** * Adds a cone. * * baseScale cannot be zero. If it is, it will automatically be set to 1F. * * @param x the x-position of the base * @param y the y-position of the base * @param z the z-position of the base * @param radius the radius of the cylinder * @param length the length of the cylinder * @param segments the amount of segments the cylinder is made of * @param baseScale the scaling of the base. Can be negative. */ public void addCone(float x, float y, float z, float radius, float length, int segments, float baseScale) { addCone(x, y, z, radius, length, segments, baseScale, MR_TOP); } /** * Adds a cone. * * baseScale cannot be zero. If it is, it will automatically be set to 1F. * * Setting the baseDirection to either MR_LEFT, MR_BOTTOM or MR_BACK will result in * the top being placed at the (x,y,z). * * @param x the x-position of the base * @param y the y-position of the base * @param z the z-position of the base * @param radius the radius of the cylinder * @param length the length of the cylinder * @param segments the amount of segments the cylinder is made of * @param baseScale the scaling of the base. Can be negative. * @param baseDirection the direction it faces */ public void addCone(float x, float y, float z, float radius, float length, int segments, float baseScale, int baseDirection) { addCone(x, y, z, radius, length, segments, baseScale, baseDirection, (int)Math.floor(radius * 2F), (int)Math.floor(radius * 2F)); } /** * Adds a cone. * * baseScale cannot be zero. If it is, it will automatically be set to 1F. * * Setting the baseDirection to either MR_LEFT, MR_BOTTOM or MR_BACK will result in * the top being placed at the (x,y,z). * * The textures for the sides are placed next to each other. * * @param x the x-position of the base * @param y the y-position of the base * @param z the z-position of the base * @param radius the radius of the cylinder * @param length the length of the cylinder * @param segments the amount of segments the cylinder is made of * @param baseScale the scaling of the base. Can be negative. * @param baseDirection the direction it faces * @param textureCircleDiameterW the diameter width of the circle on the texture * @param textureCircleDiameterH the diameter height of the circle on the texture */ public void addCone(float x, float y, float z, float radius, float length, int segments, float baseScale, int baseDirection, int textureCircleDiameterW, int textureCircleDiameterH) { addCylinder(x, y, z, radius, length, segments, baseScale, 0.0F, baseDirection, textureCircleDiameterW, textureCircleDiameterH, 1); } /** * Adds a cylinder. * @param x the x-position of the base * @param y the y-position of the base * @param z the z-position of the base * @param radius the radius of the cylinder * @param length the length of the cylinder * @param segments the amount of segments the cylinder is made of */ public void addCylinder(float x, float y, float z, float radius, float length, int segments) { addCylinder(x, y, z, radius, length, segments, 1F, 1F); } /** * Adds a cylinder. * * You can make cones by either setting baseScale or topScale to zero. Setting both * to zero will set the baseScale to 1F. * * @param x the x-position of the base * @param y the y-position of the base * @param z the z-position of the base * @param radius the radius of the cylinder * @param length the length of the cylinder * @param segments the amount of segments the cylinder is made of * @param baseScale the scaling of the base. Can be negative. * @param topScale the scaling of the top. Can be negative. */ public void addCylinder(float x, float y, float z, float radius, float length, int segments, float baseScale, float topScale) { addCylinder(x, y, z, radius, length, segments, baseScale, topScale, MR_TOP); } /** * Adds a cylinder. * * You can make cones by either setting baseScale or topScale to zero. Setting both * to zero will set the baseScale to 1F. * * Setting the baseDirection to either MR_LEFT, MR_BOTTOM or MR_BACK will result in * the top being placed at the (x,y,z). * * @param x the x-position of the base * @param y the y-position of the base * @param z the z-position of the base * @param radius the radius of the cylinder * @param length the length of the cylinder * @param segments the amount of segments the cylinder is made of * @param baseScale the scaling of the base. Can be negative. * @param topScale the scaling of the top. Can be negative. * @param baseDirection the direction it faces */ public void addCylinder(float x, float y, float z, float radius, float length, int segments, float baseScale, float topScale, int baseDirection) { addCylinder(x, y, z, radius, length, segments, baseScale, topScale, baseDirection, (int)Math.floor(radius * 2F), (int)Math.floor(radius * 2F), (int)Math.floor(length)); } /** * Adds a cylinder. * * You can make cones by either setting baseScale or topScale to zero. Setting both * to zero will set the baseScale to 1F. * * Setting the baseDirection to either MR_LEFT, MR_BOTTOM or MR_BACK will result in * the top being placed at the (x,y,z). * * The textures for the base and top are placed next to each other, while the body * will be placed below the circles. * * @param x the x-position of the base * @param y the y-position of the base * @param z the z-position of the base * @param radius the radius of the cylinder * @param length the length of the cylinder * @param segments the amount of segments the cylinder is made of * @param baseScale the scaling of the base. Can be negative. * @param topScale the scaling of the top. Can be negative. * @param baseDirection the direction it faces * @param textureCircleDiameterW the diameter width of the circle on the texture * @param textureCircleDiameterH the diameter height of the circle on the texture * @param textureH the height of the texture of the body */ public void addCylinder(float x, float y, float z, float radius, float length, int segments, float baseScale, float topScale, int baseDirection, int textureCircleDiameterW, int textureCircleDiameterH, int textureH) { boolean dirTop = (baseDirection == MR_TOP || baseDirection == MR_BOTTOM); boolean dirSide = (baseDirection == MR_RIGHT || baseDirection == MR_LEFT); boolean dirFront = (baseDirection == MR_FRONT || baseDirection == MR_BACK); boolean dirMirror = (baseDirection == MR_LEFT || baseDirection == MR_BOTTOM || baseDirection == MR_BACK); boolean coneBase = (baseScale == 0); boolean coneTop = (topScale == 0); if(coneBase && coneTop) { baseScale = 1F; coneBase = false; } PositionTextureVertex[] tempVerts = new PositionTextureVertex[segments * (coneBase || coneTop ? 1 : 2) + 2]; TexturedPolygon[] poly = new TexturedPolygon[segments * (coneBase || coneTop ? 2 : 3)]; float xLength = (dirSide ? length : 0); float yLength = (dirTop ? length : 0); float zLength = (dirFront ? length : 0); float xStart = (dirMirror ? x + xLength : x); float yStart = (dirMirror ? y + yLength : y); float zStart = (dirMirror ? z + zLength : z); float xEnd = (!dirMirror ? x + xLength : x); float yEnd = (!dirMirror ? y + yLength : y); float zEnd = (!dirMirror ? z + zLength : z); tempVerts[0] = new PositionTextureVertex(xStart, yStart, zStart, 0, 0); tempVerts[tempVerts.length - 1] = new PositionTextureVertex(xEnd, yEnd, zEnd, 0, 0); float xCur = xStart; float yCur = yStart; float zCur = zStart; float sCur = (coneBase ? topScale : baseScale); for(int repeat = 0; repeat < (coneBase || coneTop ? 1 : 2); repeat++) { for(int index = 0; index < segments; index++) { float xSize = (mirror ^ dirMirror ? -1 : 1) * MathHelper.sin((pi / (float)segments) * index * 2F + pi) * radius * sCur; float zSize = -MathHelper.cos((pi / (float)segments) * index * 2F + pi) * radius * sCur; float xPlace = xCur + (!dirSide ? xSize : 0); float yPlace = yCur + (!dirTop ? zSize : 0); float zPlace = zCur + (dirSide ? xSize : (dirTop ? zSize : 0)); tempVerts[1 + index + repeat * segments] = new PositionTextureVertex(xPlace, yPlace, zPlace, 0, 0 ); } xCur = xEnd; yCur = yEnd; zCur = zEnd; sCur = topScale; } float uScale = 1.0F / (float) textureWidth; float vScale = 1.0F / (float) textureHeight; float uOffset = uScale / 20.0F; float vOffset = vScale / 20.0F; float uCircle = (float)textureCircleDiameterW * uScale; float vCircle = (float)textureCircleDiameterH * vScale; float uWidth = (uCircle * 2F - uOffset * 2F) / (float) segments; float vHeight = (float)textureH * vScale - uOffset * 2f; float uStart = (float)textureOffsetX * uScale; float vStart = (float)textureOffsetY * vScale; PositionTextureVertex[] vert; for(int index = 0; index < segments; index++) { int index2 = (index + 1) % segments; float uSize = MathHelper.sin((pi / (float)segments) * index * 2F + (!dirTop ? 0 : pi)) * (0.5F * uCircle - 2F * uOffset); float vSize = MathHelper.cos((pi / (float)segments) * index * 2F + (!dirTop ? 0 : pi)) * (0.5F * vCircle - 2F * vOffset); float uSize1 = MathHelper.sin((pi / (float)segments) * index2 * 2F + (!dirTop ? 0 : pi)) * (0.5F * uCircle - 2F * uOffset); float vSize1 = MathHelper.cos((pi / (float)segments) * index2 * 2F + (!dirTop ? 0 : pi)) * (0.5F * vCircle - 2F * vOffset); vert = new PositionTextureVertex[3]; vert[0] = tempVerts[0].setTexturePosition(uStart + 0.5F * uCircle, vStart + 0.5F * vCircle); vert[1] = tempVerts[1 + index2].setTexturePosition(uStart + 0.5F * uCircle + uSize1, vStart + 0.5F * vCircle + vSize1); vert[2] = tempVerts[1 + index].setTexturePosition(uStart + 0.5F * uCircle + uSize, vStart + 0.5F * vCircle + vSize); poly[index] = new TexturedPolygon(vert); if(mirror ^ flip) poly[index].flipFace(); if(!coneBase && !coneTop) { vert = new PositionTextureVertex[4]; vert[0] = tempVerts[1 + index].setTexturePosition(uStart + uOffset + uWidth * (float)index, vStart + vOffset + vCircle); vert[1] = tempVerts[1 + index2].setTexturePosition(uStart + uOffset + uWidth * (float)(index + 1), vStart + vOffset + vCircle); vert[2] = tempVerts[1 + segments + index2].setTexturePosition(uStart + uOffset + uWidth * (float)(index + 1), vStart + vOffset + vCircle + vHeight); vert[3] = tempVerts[1 + segments + index].setTexturePosition(uStart + uOffset + uWidth * (float)index, vStart + vOffset + vCircle + vHeight); poly[index + segments] = new TexturedPolygon(vert); if(mirror ^ flip) poly[index + segments].flipFace(); } vert = new PositionTextureVertex[3]; vert[0] = tempVerts[tempVerts.length - 1].setTexturePosition(uStart + 1.5F * uCircle, vStart + 0.5F * vCircle); vert[1] = tempVerts[tempVerts.length - 2 - index].setTexturePosition(uStart + 1.5F * uCircle + uSize1, vStart + 0.5F * vCircle + vSize1); vert[2] = tempVerts[tempVerts.length - (1 + segments) + ((segments - index) % segments)].setTexturePosition(uStart + 1.5F * uCircle + uSize, vStart + 0.5F * vCircle + vSize); poly[poly.length - segments + index] = new TexturedPolygon(vert); if(mirror ^ flip) poly[poly.length - segments + index].flipFace(); } copyTo(tempVerts, poly); } /** * Adds a Waveform .obj file as a model. Model files use the entire texture file. * @param file the location of the .obj file. The location is relative to the base directories, * which are either resources/models or resources/mods/models. */ public void addObj(String file) { addModel(file, ModelPool.OBJ); } /** * Adds model format support. Model files use the entire texture file. * @param file the location of the model file. The location is relative to the base directories, * which are either resources/models or resources/mods/models. * @param modelFormat the class of the model format interpreter */ public void addModel(String file, Class modelFormat) { ModelPoolEntry entry = ModelPool.addFile(file, modelFormat, transformGroup, textureGroup); if(entry == null) return; PositionTextureVertex[] verts = Arrays.copyOf(entry.vertices, entry.vertices.length); TexturedPolygon[] poly = Arrays.copyOf(entry.faces, entry.faces.length); if(flip) { for(int l = 0; l < faces.length; l++) { faces[l].flipFace(); } } copyTo(verts, poly, false); } /** * Sets a new position for the texture offset. * @param x the x-coordinate of the texture start * @param y the y-coordinate of the texture start */ public ModelRendererTurbo setTextureOffset(int x, int y) { textureOffsetX = x; textureOffsetY = y; return this; } /** * Sets the position of the shape, relative to the model's origins. Note that changing * the offsets will not change the pivot of the model. * @param x the x-position of the shape * @param y the y-position of the shape * @param z the z-position of the shape */ public void setPosition(float x, float y, float z) { rotationPointX = x; rotationPointY = y; rotationPointZ = z; } /** * Mirrors the model in any direction. * @param x whether the model should be mirrored in the x-direction * @param y whether the model should be mirrored in the y-direction * @param z whether the model should be mirrored in the z-direction */ public void doMirror(boolean x, boolean y, boolean z) { for(int i = 0; i < faces.length; i++) { PositionTextureVertex[] verts = faces[i].vertexPositions; for(int j = 0; j < verts.length; j++) { verts[j].vector3D.xCoord *= (x ? -1 : 1); verts[j].vector3D.yCoord *= (y ? -1 : 1); verts[j].vector3D.zCoord *= (z ? -1 : 1); } if(x^y^z) faces[i].flipFace(); } } /** * Sets whether the shape is mirrored or not. This has effect on the way the textures * get displayed. When working with addSprite, addPixel and addObj, it will be ignored. * @param isMirrored a boolean to define whether the shape is mirrored */ public void setMirrored(boolean isMirrored) { mirror = isMirrored; } /** * Sets whether the shape's faces are flipped or not. When GL_CULL_FACE is enabled, * it won't render the back faces, effectively giving you the possibility to make * "hollow" shapes. When working with addSprite and addPixel, it will be ignored. * @param isFlipped a boolean to define whether the shape is flipped */ public void setFlipped(boolean isFlipped) { flip = isFlipped; } /** * Clears the current shape. Since all shapes are stacked into one shape, you can't * just replace a shape by overwriting the shape with another one. In this case you * would need to clear the shape first. */ public void clear() { vertices = new PositionTextureVertex[0]; faces = new TexturedPolygon[0]; transformGroup.clear(); transformGroup.put("0", new TransformGroupBone(new Bone(0, 0, 0, 0), 1D)); currentGroup = transformGroup.get("0"); } /** * Copies an array of vertices and polygons to the current shape. This mainly is * used to copy each shape to the main class, but you can just use it to copy * your own shapes, for example from other classes, into the current class. * @param verts the array of vertices you want to copy * @param poly the array of polygons you want to copy */ public void copyTo(PositionTextureVertex[] verts, TexturedPolygon[] poly) { copyTo(verts, poly, true); } public void copyTo(PositionTextureVertex[] verts, TexturedPolygon[] poly, boolean copyGroup) { vertices = Arrays.copyOf(vertices, vertices.length + verts.length); faces = Arrays.copyOf(faces, faces.length + poly.length); for(int idx = 0; idx < verts.length; idx++) { vertices[vertices.length - verts.length + idx] = verts[idx]; if(copyGroup && verts[idx] instanceof PositionTransformVertex) ((PositionTransformVertex)verts[idx]).addGroup(currentGroup); } for(int idx = 0; idx < poly.length; idx++) { faces[faces.length - poly.length + idx] = poly[idx]; if(copyGroup) currentTextureGroup.addPoly(poly[idx]); } } /** * Copies an array of vertices and quads to the current shape. This method * converts quads to polygons and then calls the main copyTo method. * @param verts the array of vertices you want to copy * @param quad the array of quads you want to copy */ public void copyTo(PositionTextureVertex[] verts, TexturedQuad[] quad) { TexturedPolygon[] poly = new TexturedPolygon[quad.length]; for(int idx = 0; idx < quad.length; idx++) { poly[idx] = new TexturedPolygon((PositionTextureVertex[])quad[idx].vertexPositions); } copyTo(verts, poly); } /** * Sets the current transformation group. The transformation group is used * to allow for vertex transformation. If a transformation group does not exist, * a new one will be created. * @param groupName the name of the transformation group you want to switch to */ public void setGroup(String groupName) { setGroup(groupName, new Bone(0, 0, 0, 0), 1D); } /** * Sets the current transformation group. The transformation group is used * to allow for vertex transformation. If a transformation group does not exist, * a new one will be created. * @param groupName the name of the transformation group you want to switch to * @param bone the Bone this transformation group is attached to * @param weight the weight of the transformation group */ public void setGroup(String groupName, Bone bone, double weight) { if(!transformGroup.containsKey(groupName)) transformGroup.put(groupName, new TransformGroupBone(bone, weight)); currentGroup = transformGroup.get(groupName); } /** * Gets the current transformation group. * @return the current PositionTransformGroup. */ public TransformGroup getGroup() { return currentGroup; } /** * Gets the transformation group with a given group name. * @return the current PositionTransformGroup. */ public TransformGroup getGroup(String groupName) { if(!transformGroup.containsKey(groupName)) return null; return transformGroup.get(groupName); } /** * Sets the current texture group, which is used to switch the * textures on a per-model base. Do note that any model that is * rendered afterwards will use the same texture. To counter it, * set a default texture, either at initialization or before * rendering. * @param groupName The name of the texture group. If the texture * group doesn't exist, it creates a new group automatically. */ public void setTextureGroup(String groupName) { if(!textureGroup.containsKey(groupName)) { textureGroup.put(groupName, new TextureGroup()); } currentTextureGroup = textureGroup.get(groupName); } /** * Gets the current texture group. * @return a TextureGroup object. */ public TextureGroup getTextureGroup() { return currentTextureGroup; } /** * Gets the texture group with the given name. * @param groupName the name of the texture group to return * @return a TextureGroup object. */ public TextureGroup getTextureGroup(String groupName) { if(!textureGroup.containsKey(groupName)) return null; return textureGroup.get(groupName); } /** * Sets the texture of the current texture group. * @param s the filename */ public void setGroupTexture(String s) { currentTextureGroup.texture = s; } /** * Sets the default texture. When left as an empty string, * it will use the texture that has been set previously. * Note that this will also move on to other rendered models * of the same entity. * @param s the filename */ public void setDefaultTexture(String s) { defaultTexture = s; } /** * Renders the shape. * @param worldScale the scale of the shape. Usually is 0.0625. */ public void render(float worldScale) { if(field_1402_i) { return; } if(!showModel) { return; } if(!compiled || forcedRecompile) { compileDisplayList(worldScale); } if(rotateAngleX != 0.0F || rotateAngleY != 0.0F || rotateAngleZ != 0.0F) { GL11.glPushMatrix(); GL11.glTranslatef(rotationPointX * worldScale, rotationPointY * worldScale, rotationPointZ * worldScale); if(rotateAngleY != 0.0F) { GL11.glRotatef(rotateAngleY * 57.29578F, 0.0F, 1.0F, 0.0F); } if(rotateAngleZ != 0.0F) { GL11.glRotatef(rotateAngleZ * 57.29578F, 0.0F, 0.0F, 1.0F); } if(rotateAngleX != 0.0F) { GL11.glRotatef(rotateAngleX * 57.29578F, 1.0F, 0.0F, 0.0F); } callDisplayList(); if(childModels != null) { for(int i = 0; i < childModels.size(); i++) { ((ModelRenderer)childModels.get(i)).render(worldScale); } } GL11.glPopMatrix(); } else if(rotationPointX != 0.0F || rotationPointY != 0.0F || rotationPointZ != 0.0F) { GL11.glTranslatef(rotationPointX * worldScale, rotationPointY * worldScale, rotationPointZ * worldScale); callDisplayList(); if(childModels != null) { for(int i = 0; i < childModels.size(); i++) { ((ModelRenderer)childModels.get(i)).render(worldScale); } } GL11.glTranslatef(-rotationPointX * worldScale, -rotationPointY * worldScale, -rotationPointZ * worldScale); } else { callDisplayList(); if(childModels != null) { for(int i = 0; i < childModels.size(); i++) { ((ModelRenderer)childModels.get(i)).render(worldScale); } } } } public void renderWithRotation(float f) { if(field_1402_i) { return; } if(!showModel) { return; } if(!compiled) { compileDisplayList(f); } GL11.glPushMatrix(); GL11.glTranslatef(rotationPointX * f, rotationPointY * f, rotationPointZ * f); if(rotateAngleY != 0.0F) { GL11.glRotatef(rotateAngleY * 57.29578F, 0.0F, 1.0F, 0.0F); } if(rotateAngleX != 0.0F) { GL11.glRotatef(rotateAngleX * 57.29578F, 1.0F, 0.0F, 0.0F); } if(rotateAngleZ != 0.0F) { GL11.glRotatef(rotateAngleZ * 57.29578F, 0.0F, 0.0F, 1.0F); } callDisplayList(); GL11.glPopMatrix(); } public void postRender(float f) { if(field_1402_i) { return; } if(!showModel) { return; } if(!compiled || forcedRecompile) { compileDisplayList(f); } if(rotateAngleX != 0.0F || rotateAngleY != 0.0F || rotateAngleZ != 0.0F) { GL11.glTranslatef(rotationPointX * f, rotationPointY * f, rotationPointZ * f); if(rotateAngleZ != 0.0F) { GL11.glRotatef(rotateAngleZ * 57.29578F, 0.0F, 0.0F, 1.0F); } if(rotateAngleY != 0.0F) { GL11.glRotatef(rotateAngleY * 57.29578F, 0.0F, 1.0F, 0.0F); } if(rotateAngleX != 0.0F) { GL11.glRotatef(rotateAngleX * 57.29578F, 1.0F, 0.0F, 0.0F); } } else if(rotationPointX != 0.0F || rotationPointY != 0.0F || rotationPointZ != 0.0F) { GL11.glTranslatef(rotationPointX * f, rotationPointY * f, rotationPointZ * f); } } private void callDisplayList() { if(useLegacyCompiler) GL11.glCallList(displayList); else { TextureManager renderEngine = RenderManager.instance.renderEngine; Collection<TextureGroup> textures = textureGroup.values(); Iterator<TextureGroup> itr = textures.iterator(); for(int i = 0; itr.hasNext(); i++) { TextureGroup curTexGroup = (TextureGroup)itr.next(); curTexGroup.loadTexture(); GL11.glCallList(displayListArray[i]); if(!defaultTexture.equals("")) renderEngine.bindTexture(new ResourceLocation("", defaultTexture)); //TODO : Check. Not sure about this one } } } private void compileDisplayList(float worldScale) { if(useLegacyCompiler) compileLegacyDisplayList(worldScale); else { Collection<TextureGroup> textures = textureGroup.values(); Iterator<TextureGroup> itr = textures.iterator(); displayListArray = new int[textureGroup.size()]; for(int i = 0; itr.hasNext(); i++) { displayListArray[i] = GLAllocation.generateDisplayLists(1); GL11.glNewList(displayListArray[i], GL11.GL_COMPILE); TmtTessellator tessellator = TmtTessellator.instance; TextureGroup usedGroup = (TextureGroup)itr.next(); for(int j = 0; j < usedGroup.poly.size(); j++) { usedGroup.poly.get(j).draw(tessellator, worldScale); } GL11.glEndList(); } } compiled = true; } private void compileLegacyDisplayList(float worldScale) { displayList = GLAllocation.generateDisplayLists(1); GL11.glNewList(displayList, GL11.GL_COMPILE); TmtTessellator tessellator = TmtTessellator.instance; for(int i = 0; i < faces.length; i++) { faces[i].draw(tessellator, worldScale); } GL11.glEndList(); } private PositionTextureVertex vertices[]; private TexturedPolygon faces[]; private int textureOffsetX; private int textureOffsetY; private boolean compiled; private int displayList; private int displayListArray[]; private Map<String, TransformGroup> transformGroup; private Map<String, TextureGroup> textureGroup; private TransformGroup currentGroup; private TextureGroup currentTextureGroup; public boolean mirror; public boolean flip; public boolean showModel; public boolean field_1402_i; public boolean forcedRecompile; public boolean useLegacyCompiler; public List cubeList; public List childModels; public final String boxName; private String defaultTexture; public static final int MR_FRONT = 0; public static final int MR_BACK = 1; public static final int MR_LEFT = 2; public static final int MR_RIGHT = 3; public static final int MR_TOP = 4; public static final int MR_BOTTOM = 5; private static final float pi = (float) Math.PI; }
false
true
public void addFlexTrapezoid(float x, float y, float z, int w, int h, int d, float scale, float bScale1, float bScale2, float bScale3, float bScale4, float fScale1, float fScale2, int dir) { float f4 = x + (float)w; float f5 = y + (float)h; float f6 = z + (float)d; x -= scale; y -= scale; z -= scale; f4 += scale; f5 += scale; f6 += scale; int m = (mirror ? -1 : 1); if(mirror) { float f7 = f4; f4 = x; x = f7; } float[] v = {x, y, z}; float[] v1 = {f4, y, z}; float[] v2 = {f4, f5, z}; float[] v3 = {x, f5, z}; float[] v4 = {x, y, f6}; float[] v5 = {f4, y, f6}; float[] v6 = {f4, f5, f6}; float[] v7 = {x, f5, f6}; switch(dir) { case MR_RIGHT: v[2] -= fScale1; v1[2] -= fScale1; v4[2] += fScale2; v5[2] += fScale2; v[1] -= bScale1; v[2] -= bScale3; v3[1] += bScale2; v3[2] -= bScale3; v4[1] -= bScale1; v4[2] += bScale4; v7[1] += bScale2; v7[2] += bScale4; break; case MR_LEFT: v[2] -= fScale1; v1[2] -= fScale1; v4[2] += fScale2; v5[2] += fScale2; v1[1] -= bScale1; v1[2] -= bScale3; v2[1] += bScale2; v2[2] -= bScale3; v5[1] -= bScale1; v5[2] += bScale4; v6[1] += bScale2; v6[2] += bScale4; break; case MR_FRONT: v2[1] += fScale1; v3[1] += fScale2; v6[1] += fScale2; v7[1] += fScale1; v[0] -= m * bScale4; v[1] -= bScale1; v1[0] += m * bScale3; v1[1] -= bScale1; v2[0] += m * bScale3; v2[1] += bScale2; v3[0] -= m * bScale4; v3[1] += bScale2; break; case MR_BACK: v2[1] += fScale1; v3[1] += fScale2; v6[1] += fScale2; v7[1] += fScale1; v4[0] -= m * bScale4; v4[1] -= bScale1; v5[0] += m * bScale3; v5[1] -= bScale1; v6[0] += m * bScale3; v6[1] += bScale2; v7[0] -= m * bScale4; v7[1] += bScale2; break; case MR_TOP: v1[2] -= fScale1; v2[2] -= fScale1; v5[2] += fScale2; v6[2] += fScale2; v[0] -= m * bScale1; v[2] -= bScale3; v1[0] += m * bScale2; v1[2] -= bScale3; v4[0] -= m * bScale1; v4[2] += bScale4; v5[0] += m * bScale2; v5[2] += bScale4; break; case MR_BOTTOM: v1[2] -= fScale1; v2[2] -= fScale1; v5[2] += fScale2; v6[2] += fScale2; v2[0] += m * bScale2; v2[2] -= bScale3; v3[0] -= m * bScale1; v3[2] -= bScale3; v6[0] += m * bScale2; v6[2] += bScale4; v7[0] -= m * bScale1; v7[2] += bScale4; break; } float[] qValues = new float[] { Math.abs((v[0] - v1[0])/(v3[0]-v2[0])), Math.abs((v[0] - v1[0])/(v4[0]-v5[0])), Math.abs((v4[0] - v5[0])/(v7[0]-v6[0])), Math.abs((v3[0] - v2[0])/(v7[0]-v6[0])), Math.abs((v[1] - v3[1])/(v1[1]-v2[1])), Math.abs((v4[1] - v7[1])/(v5[1]-v6[1])), Math.abs((v[1] - v3[1])/(v4[1]-v7[1])), Math.abs((v1[1] - v2[1])/(v5[1]-v6[1])), Math.abs((v[2] - v4[2])/(v1[2]-v5[2])), Math.abs((v[2] - v4[2])/(v3[2]-v7[2])), Math.abs((v1[2] - v5[2])/(v2[2]-v6[2])), Math.abs((v3[2] - v7[2])/(v2[2]-v6[2])) }; addRectShape(v, v1, v2, v3, v4, v5, v6, v7, w, h, d, qValues); }
public void addFlexTrapezoid(float x, float y, float z, int w, int h, int d, float scale, float bScale1, float bScale2, float bScale3, float bScale4, float fScale1, float fScale2, int dir) { float f4 = x + (float)w; float f5 = y + (float)h; float f6 = z + (float)d; x -= scale; y -= scale; z -= scale; f4 += scale; f5 += scale; f6 += scale; int m = (mirror ? -1 : 1); if(mirror) { float f7 = f4; f4 = x; x = f7; } float[] v = {x, y, z}; float[] v1 = {f4, y, z}; float[] v2 = {f4, f5, z}; float[] v3 = {x, f5, z}; float[] v4 = {x, y, f6}; float[] v5 = {f4, y, f6}; float[] v6 = {f4, f5, f6}; float[] v7 = {x, f5, f6}; switch(dir) { case MR_RIGHT: v[2] -= fScale1; v1[2] -= fScale1; v4[2] += fScale2; v5[2] += fScale2; v[1] -= bScale1; v[2] -= bScale3; v3[1] += bScale2; v3[2] -= bScale3; v4[1] -= bScale1; v4[2] += bScale4; v7[1] += bScale2; v7[2] += bScale4; break; case MR_LEFT: v[2] -= fScale1; v1[2] -= fScale1; v4[2] += fScale2; v5[2] += fScale2; v1[1] -= bScale1; v1[2] -= bScale3; v2[1] += bScale2; v2[2] -= bScale3; v5[1] -= bScale1; v5[2] += bScale4; v6[1] += bScale2; v6[2] += bScale4; break; case MR_FRONT: v1[1] -= fScale1; v5[1] -= fScale1; v2[1] += fScale2; v6[1] += fScale2; v[0] -= m * bScale4; v[1] -= bScale1; v1[0] += m * bScale3; v1[1] -= bScale1; v2[0] += m * bScale3; v2[1] += bScale2; v3[0] -= m * bScale4; v3[1] += bScale2; break; case MR_BACK: v1[1] -= fScale1; v5[1] -= fScale1; v2[1] += fScale2; v6[1] += fScale2; v4[0] -= m * bScale4; v4[1] -= bScale1; v5[0] += m * bScale3; v5[1] -= bScale1; v6[0] += m * bScale3; v6[1] += bScale2; v7[0] -= m * bScale4; v7[1] += bScale2; break; case MR_TOP: v1[2] -= fScale1; v2[2] -= fScale1; v5[2] += fScale2; v6[2] += fScale2; v[0] -= m * bScale1; v[2] -= bScale3; v1[0] += m * bScale2; v1[2] -= bScale3; v4[0] -= m * bScale1; v4[2] += bScale4; v5[0] += m * bScale2; v5[2] += bScale4; break; case MR_BOTTOM: v1[2] -= fScale1; v2[2] -= fScale1; v5[2] += fScale2; v6[2] += fScale2; v2[0] += m * bScale2; v2[2] -= bScale3; v3[0] -= m * bScale1; v3[2] -= bScale3; v6[0] += m * bScale2; v6[2] += bScale4; v7[0] -= m * bScale1; v7[2] += bScale4; break; } float[] qValues = new float[] { Math.abs((v[0] - v1[0])/(v3[0]-v2[0])), Math.abs((v[0] - v1[0])/(v4[0]-v5[0])), Math.abs((v4[0] - v5[0])/(v7[0]-v6[0])), Math.abs((v3[0] - v2[0])/(v7[0]-v6[0])), Math.abs((v[1] - v3[1])/(v1[1]-v2[1])), Math.abs((v4[1] - v7[1])/(v5[1]-v6[1])), Math.abs((v[1] - v3[1])/(v4[1]-v7[1])), Math.abs((v1[1] - v2[1])/(v5[1]-v6[1])), Math.abs((v[2] - v4[2])/(v1[2]-v5[2])), Math.abs((v[2] - v4[2])/(v3[2]-v7[2])), Math.abs((v1[2] - v5[2])/(v2[2]-v6[2])), Math.abs((v3[2] - v7[2])/(v2[2]-v6[2])) }; addRectShape(v, v1, v2, v3, v4, v5, v6, v7, w, h, d, qValues); }
diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/html/BrowserInformationControl.java b/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/html/BrowserInformationControl.java index b8c10e4a2..eccd6bda8 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/html/BrowserInformationControl.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/html/BrowserInformationControl.java @@ -1,951 +1,951 @@ /******************************************************************************* * Copyright (c) 2000, 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.jface.internal.text.html; import java.io.IOException; import java.io.StringReader; import java.util.Iterator; import org.eclipse.swt.SWT; import org.eclipse.swt.SWTError; import org.eclipse.swt.browser.Browser; import org.eclipse.swt.browser.LocationAdapter; import org.eclipse.swt.browser.LocationEvent; import org.eclipse.swt.browser.LocationListener; import org.eclipse.swt.browser.ProgressAdapter; import org.eclipse.swt.browser.ProgressEvent; import org.eclipse.swt.custom.StyleRange; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.FocusListener; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.KeyListener; import org.eclipse.swt.events.MouseAdapter; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseMoveListener; 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.graphics.Rectangle; import org.eclipse.swt.graphics.TextLayout; import org.eclipse.swt.graphics.TextStyle; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; 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.Menu; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Slider; import org.eclipse.swt.widgets.ToolBar; import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.ListenerList; import org.eclipse.jface.action.ToolBarManager; import org.eclipse.jface.text.IDelayedInputChangeProvider; import org.eclipse.jface.text.IInformationControl; import org.eclipse.jface.text.IInformationControlExtension; import org.eclipse.jface.text.IInformationControlExtension2; import org.eclipse.jface.text.IInformationControlExtension3; import org.eclipse.jface.text.IInformationControlExtension4; import org.eclipse.jface.text.IInformationControlExtension5; import org.eclipse.jface.text.IInputChangedListener; import org.eclipse.jface.text.TextPresentation; /** * Displays HTML information in a {@link org.eclipse.swt.browser.Browser} widget. * <p> * This {@link IInformationControlExtension2} expects {@link #setInput(Object)} to be * called with an argument of type {@link BrowserInformationControlInput}. * </p> * <p> * Moved into this package from <code>org.eclipse.jface.internal.text.revisions</code>.</p> * <p> * This class may be instantiated; it is not intended to be subclassed.</p> * <p> * Current problems: * <ul> * <li>the size computation is too small</li> * <li>focusLost event is not sent - see https://bugs.eclipse.org/bugs/show_bug.cgi?id=84532</li> * </ul> * </p> * * @since 3.2 */ public class BrowserInformationControl implements IInformationControl, IInformationControlExtension, IInformationControlExtension2, IInformationControlExtension3, IInformationControlExtension4, IInformationControlExtension5, IDelayedInputChangeProvider, DisposeListener { /** * Tells whether the SWT Browser widget and hence this information * control is available. * * @param parent the parent component used for checking or <code>null</code> if none * @return <code>true</code> if this control is available */ public static boolean isAvailable(Composite parent) { if (!fgAvailabilityChecked) { try { Browser browser= new Browser(parent, SWT.NONE); browser.dispose(); fgIsAvailable= true; Slider sliderV= new Slider(parent, SWT.VERTICAL); Slider sliderH= new Slider(parent, SWT.HORIZONTAL); int width= sliderV.computeSize(SWT.DEFAULT, SWT.DEFAULT).x; int height= sliderH.computeSize(SWT.DEFAULT, SWT.DEFAULT).y; fgScrollBarSize= new Point(width, height); sliderV.dispose(); sliderH.dispose(); } catch (SWTError er) { fgIsAvailable= false; } finally { fgAvailabilityChecked= true; } } return fgIsAvailable; } /** Border thickness in pixels. */ private static final int BORDER= 1; /** * Minimal size constraints. * @since 3.2 */ private static final int MIN_WIDTH= 80; private static final int MIN_HEIGHT= 80; /** * Availability checking cache. */ private static boolean fgIsAvailable= false; private static boolean fgAvailabilityChecked= false; /** * Cached scroll bar width and height * @since 3.4 */ private static Point fgScrollBarSize; /** The control's shell */ private Shell fShell; /** The control's browser widget */ private Browser fBrowser; /** Tells whether the browser has content */ private boolean fBrowserHasContent; /** The control width constraint */ private int fMaxWidth= SWT.DEFAULT; /** The control height constraint */ private int fMaxHeight= SWT.DEFAULT; private Label fSeparator; private Font fStatusTextFont; private Label fStatusTextField; private String fStatusFieldText; private ToolBarManager fToolBarManager; private Label fTBSeparator; private ToolBar fToolBar; private final int fBorderWidth; private boolean fHideScrollBars; private Listener fShellListener; private ListenerList fFocusListeners= new ListenerList(ListenerList.IDENTITY); private TextLayout fTextLayout; private TextStyle fBoldStyle; private BrowserInformationControlInput fInput; /** * <code>true</code> iff the browser has completed loading of the last * input set via {@link #setInformation(String)}. * @since 3.4 */ private boolean fCompleted= false; /** * The listener to be notified when a delayed location changing event happened. * @since 3.4 */ private IInputChangedListener fDelayedInputChangeListener; /** * The listeners to be notified when the input changed. * @since 3.4 */ private ListenerList/*<IInputChangedListener>*/ fInputChangeListeners= new ListenerList(ListenerList.IDENTITY); /** * Creates a browser information control with the given shell as parent. The given * information presenter is used to process the information to be displayed. The given * styles are applied to the created browser widget. * * @param parent the parent shell * @param shellStyle the additional styles for the shell * @param style the additional styles for the browser widget */ public BrowserInformationControl(Shell parent, int shellStyle, int style) { this(parent, shellStyle, style, null); } /** * Creates a browser information control with the given shell as parent. The given * information presenter is used to process the information to be displayed. The given * styles are applied to the created browser widget. * * @param parent the parent shell * @param shellStyle the additional styles for the shell * @param style the additional styles for the browser widget * @param statusFieldText the text to be used in the optional status field * or <code>null</code> if the status field should be hidden */ public BrowserInformationControl(Shell parent, int shellStyle, int style, String statusFieldText) { this(parent, shellStyle, style, null, statusFieldText); } /** * Creates a browser information control with the given shell as parent. The given * information presenter is used to process the information to be displayed. The given * styles are applied to the created browser widget. * * @param parent the parent shell * @param shellStyle the additional styles for the shell * @param style the additional styles for the browser widget * @param toolBarManager the tool bar manager or <code>null</code> to hide the tool bar * @param statusFieldText the text to be used in the optional status field * or <code>null</code> if the status field should be hidden */ public BrowserInformationControl(Shell parent, int shellStyle, int style, ToolBarManager toolBarManager, String statusFieldText) { fStatusFieldText= statusFieldText; fShell= new Shell(parent, SWT.ON_TOP | shellStyle); Display display= fShell.getDisplay(); fShell.setBackground(display.getSystemColor(SWT.COLOR_BLACK)); Composite composite= fShell; GridLayout layout= new GridLayout(1, false); fBorderWidth= ((shellStyle & SWT.NO_TRIM) == 0) ? 0 : BORDER; layout.marginHeight= fBorderWidth; layout.marginWidth= fBorderWidth; composite.setLayout(layout); if (statusFieldText != null || toolBarManager != null) { composite= new Composite(composite, SWT.NONE); layout= new GridLayout(1, false); layout.marginHeight= 0; layout.marginWidth= 0; layout.verticalSpacing= 1; layout.horizontalSpacing= 1; composite.setLayout(layout); GridData gd= new GridData(GridData.FILL_BOTH); composite.setLayoutData(gd); composite.setForeground(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND)); composite.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND)); } createBrowser(composite, style); fToolBarManager= toolBarManager; if (toolBarManager != null) createToolBar(composite, toolBarManager); if (statusFieldText != null) createStatusField(composite, statusFieldText); addDisposeListener(this); createTextLayout(); } /** * Creates the browser control. * * @param composite the parent composite * @param style the additional styles for the browser widget */ private void createBrowser(Composite composite, int style) { fBrowser= new Browser(composite, SWT.NONE); fHideScrollBars= (style & SWT.V_SCROLL) == 0 && (style & SWT.H_SCROLL) == 0; GridData gd= new GridData(GridData.BEGINNING | GridData.FILL_BOTH); fBrowser.setLayoutData(gd); Display display= fShell.getDisplay(); fBrowser.setForeground(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND)); fBrowser.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND)); fBrowser.addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { if (e.character == 0x1B) // ESC fShell.dispose(); // XXX: Just hide? Would avoid constant recreations. } public void keyReleased(KeyEvent e) {} }); /* * XXX revisit when the Browser support is better * See https://bugs.eclipse.org/bugs/show_bug.cgi?id=107629 . Choosing a link to a * non-available target will show an error dialog behind the ON_TOP shell that seemingly * blocks the workbench. Disable links completely for now. */ fBrowser.addLocationListener(new LocationAdapter() { /* * @see org.eclipse.swt.browser.LocationAdapter#changing(org.eclipse.swt.browser.LocationEvent) */ public void changing(LocationEvent event) { String location= event.location; /* * Using the Browser.setText API triggers a location change to "about:blank" with * the mozilla widget. The Browser on carbon uses yet another kind of special * initialization URLs. * XXX: remove this code once https://bugs.eclipse.org/bugs/show_bug.cgi?id=130314 is fixed */ if (!"about:blank".equals(location) && !("carbon".equals(SWT.getPlatform()) && location.startsWith("applewebdata:"))) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ event.doit= false; } }); fBrowser.addProgressListener(new ProgressAdapter() { public void completed(ProgressEvent event) { fCompleted= true; } }); // Replace browser's built-in context menu with none fBrowser.setMenu(new Menu(fShell, SWT.NONE)); } /** * @param composite * @param toolBarManager */ private void createToolBar(Composite composite, ToolBarManager toolBarManager) { fTBSeparator= new Label(composite, SWT.SEPARATOR | SWT.HORIZONTAL | SWT.LINE_DOT); fTBSeparator.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); final Composite bars= new Composite(composite, SWT.NONE); bars.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false)); GridLayout layout= new GridLayout(2, false); layout.marginHeight= 0; layout.marginWidth= 0; bars.setLayout(layout); fToolBar= toolBarManager.createControl(bars); GridData gd= new GridData(SWT.BEGINNING, SWT.BEGINNING, false, false); fToolBar.setLayoutData(gd); //TODO: add view menu with "save size" (not location)? // [contribTB] [movable area] [view menu] addMoveSupport(bars); // Display display= fShell.getDisplay(); // bars.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND)); // fToolBar.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND)); } /** * Adds support to move the shell by dragging the given control. * * @param control the control to make movable * @since 3.4 */ private void addMoveSupport(final Control control) { MouseAdapter moveSupport= new MouseAdapter() { private MouseMoveListener fMoveListener; public void mouseDown(MouseEvent e) { Point shellLoc= fShell.getLocation(); final int shellX= shellLoc.x; final int shellY= shellLoc.y; Point mouseLoc= control.toDisplay(e.x, e.y); final int mouseX= mouseLoc.x; final int mouseY= mouseLoc.y; fMoveListener= new MouseMoveListener() { public void mouseMove(MouseEvent e2) { Point mouseLoc2= control.toDisplay(e2.x, e2.y); int dx= mouseLoc2.x - mouseX; int dy= mouseLoc2.y - mouseY; fShell.setLocation(shellX + dx, shellY + dy); } }; control.addMouseMoveListener(fMoveListener); } public void mouseUp(MouseEvent e) { control.removeMouseMoveListener(fMoveListener); fMoveListener= null; } }; control.addMouseListener(moveSupport); } /** * Creates the status field. * * @param composite the parent composite * @param statusFieldText the text to show in the status field */ private void createStatusField(Composite composite, String statusFieldText) { fSeparator= new Label(composite, SWT.SEPARATOR | SWT.HORIZONTAL | SWT.LINE_DOT); fSeparator.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); // Status field label fStatusTextField= new Label(composite, SWT.RIGHT); fStatusTextField.setText(statusFieldText); Font font= fStatusTextField.getFont(); FontData[] fontDatas= font.getFontData(); for (int i= 0; i < fontDatas.length; i++) fontDatas[i].setHeight(fontDatas[i].getHeight() * 9 / 10); fStatusTextFont= new Font(fStatusTextField.getDisplay(), fontDatas); fStatusTextField.setFont(fStatusTextFont); GridData gd= new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_BEGINNING); fStatusTextField.setLayoutData(gd); Display display= fShell.getDisplay(); fStatusTextField.setForeground(display.getSystemColor(SWT.COLOR_WIDGET_DARK_SHADOW)); fStatusTextField.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND)); } /** * {@inheritDoc} * @deprecated use {@link #setInput(Object)} */ public void setInformation(final String content) { setInput(new BrowserInformationControlInput(null) { public String getHtml() { return content; } }); } /** * {@inheritDoc} This control can handle {@link String} and * {@link BrowserInformationControlInput}. */ public void setInput(Object input) { - Assert.isLegal(input instanceof String || input instanceof BrowserInformationControlInput); + Assert.isLegal(input == null || input instanceof String || input instanceof BrowserInformationControlInput); if (input instanceof String) { setInformation((String)input); return; } fInput= (BrowserInformationControlInput)input; String content= null; if (fInput != null) content= fInput.getHtml(); fBrowserHasContent= content != null && content.length() > 0; if (!fBrowserHasContent) content= "<html><body ></html>"; //$NON-NLS-1$ int shellStyle= fShell.getStyle(); boolean RTL= (shellStyle & SWT.RIGHT_TO_LEFT) != 0; // The default "overflow:auto" would not result in a predictable width for the client area // and the re-wrapping would cause visual noise String[] styles= null; if (RTL && !fHideScrollBars) styles= new String[] { "direction:rtl;", "overflow:scroll;", "word-wrap:break-word;" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ else if (RTL && fHideScrollBars) styles= new String[] { "direction:rtl;", "overflow:hidden;", "word-wrap:break-word;" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ else if (fHideScrollBars) //XXX: In IE, "word-wrap: break-word;" causes bogus wrapping even in non-broken words :-(see e.g. Javadoc of String). // Re-check whether we really still need this now that the Javadoc Hover header already sets this style. styles= new String[] { "overflow:hidden;"/*, "word-wrap: break-word;"*/ }; //$NON-NLS-1$ else styles= new String[] { "overflow:scroll;" }; //$NON-NLS-1$ StringBuffer buffer= new StringBuffer(content); HTMLPrinter.insertStyles(buffer, styles); content= buffer.toString(); /* * XXX: Should add some JavaScript here that shows something like * "(continued...)" or "..." at the end of the visible area when the page overflowed * with "overflow:hidden;". */ fCompleted= false; fBrowser.setText(content); Object[] listeners= fInputChangeListeners.getListeners(); for (int i= 0; i < listeners.length; i++) ((IInputChangedListener)listeners[i]).inputChanged(fInput); } /* * @see org.eclipse.jdt.internal.ui.text.IInformationControlExtension4#setStatusText(java.lang.String) * @since 3.2 */ public void setStatusText(String statusFieldText) { fStatusFieldText= statusFieldText; } /* * @see IInformationControl#setVisible(boolean) */ public void setVisible(boolean visible) { if (fShell.isVisible() == visible) return; if (visible) { if (fStatusTextField != null) { boolean state= fStatusFieldText != null; if (state) fStatusTextField.setText(fStatusFieldText); fStatusTextField.setVisible(state); fSeparator.setVisible(state); } } if (!visible) { fShell.setVisible(false); setInput(null); return; } /* * The Browser widget flickers when made visible while it is not completely loaded. * The fix is to delay the call to setVisible until either loading is completed * (see ProgressListener in constructor), or a timeout has been reached. */ final Display display= fShell.getDisplay(); // Make sure the display wakes from sleep after timeout: display.timerExec(100, new Runnable() { public void run() { fCompleted= true; } }); while (!fCompleted) { // Drive the event loop to process the events required to load the browser widget's contents: if (!display.readAndDispatch()) { display.sleep(); } } // fShell.moveAbove(null); // XXX: has no useful contract and bugs, e.g. https://bugs.eclipse.org/bugs/show_bug.cgi?id=170774 fShell.setVisible(true); } /** * Creates and initializes the text layout used * to compute the size hint. * * @since 3.2 */ private void createTextLayout() { fTextLayout= new TextLayout(fBrowser.getDisplay()); // Initialize fonts Font font= fBrowser.getFont(); fTextLayout.setFont(font); fTextLayout.setWidth(-1); FontData[] fontData= font.getFontData(); for (int i= 0; i < fontData.length; i++) fontData[i].setStyle(SWT.BOLD); font= new Font(fShell.getDisplay(), fontData); fBoldStyle= new TextStyle(font, null, null); // Compute and set tab width fTextLayout.setText(" "); //$NON-NLS-1$ int tabWidth = fTextLayout.getBounds().width; fTextLayout.setTabs(new int[] {tabWidth}); fTextLayout.setText(""); //$NON-NLS-1$ } /* * @see IInformationControl#dispose() */ public void dispose() { if (fTextLayout != null) fTextLayout.dispose(); fTextLayout= null; if (fBoldStyle != null) fBoldStyle.font.dispose(); fBoldStyle= null; if (fToolBarManager != null) fToolBarManager.dispose(); if (fShell != null && !fShell.isDisposed()) fShell.dispose(); else widgetDisposed(null); } /* * @see org.eclipse.swt.events.DisposeListener#widgetDisposed(org.eclipse.swt.events.DisposeEvent) */ public void widgetDisposed(DisposeEvent event) { if (fStatusTextFont != null && !fStatusTextFont.isDisposed()) fStatusTextFont.dispose(); fShell= null; fBrowser= null; fStatusTextFont= null; } /* * @see IInformationControl#setSize(int, int) */ public void setSize(int width, int height) { fShell.setSize(Math.min(width, fMaxWidth), Math.min(height, fMaxHeight)); } /* * @see IInformationControl#setLocation(Point) */ public void setLocation(Point location) { fShell.setLocation(location); } /* * @see IInformationControl#setSizeConstraints(int, int) */ public void setSizeConstraints(int maxWidth, int maxHeight) { fMaxWidth= maxWidth; fMaxHeight= maxHeight; } /* * @see IInformationControl#computeSizeHint() */ public Point computeSizeHint() { TextPresentation presentation= new TextPresentation(); HTML2TextReader reader= new HTML2TextReader(new StringReader(fInput.getHtml()), presentation); String text; try { text= reader.getString(); } catch (IOException e) { text= ""; //$NON-NLS-1$ } fTextLayout.setText(text); Iterator iter= presentation.getAllStyleRangeIterator(); while (iter.hasNext()) { StyleRange sr= (StyleRange)iter.next(); if (sr.fontStyle == SWT.BOLD) fTextLayout.setStyle(fBoldStyle, sr.start, sr.start + sr.length - 1); } Rectangle bounds= fTextLayout.getBounds(); int width= bounds.width; int height= bounds.height; width += 15; height += 25; if (fStatusFieldText != null && fSeparator != null) { fTextLayout.setText(fStatusFieldText); Rectangle statusBounds= fTextLayout.getBounds(); Rectangle separatorBounds= fSeparator.getBounds(); width= Math.max(width, statusBounds.width); height= height + statusBounds.height + separatorBounds.height; } if (fToolBar != null && fTBSeparator != null) { Point toolBarSize= fToolBar.computeSize(SWT.DEFAULT, SWT.DEFAULT); Rectangle separatorBounds= fTBSeparator.getBounds(); width= Math.max(width, toolBarSize.x); height= height + toolBarSize.y + separatorBounds.height; } // Apply size constraints if (fMaxWidth != SWT.DEFAULT) width= Math.min(fMaxWidth, width); if (fMaxHeight != SWT.DEFAULT) height= Math.min(fMaxHeight, height); // Ensure minimal size width= Math.max(MIN_WIDTH, width); height= Math.max(MIN_HEIGHT, height); return new Point(width, height); } /* * @see org.eclipse.jface.text.IInformationControlExtension3#computeTrim() */ public Rectangle computeTrim() { Rectangle trim= fShell.computeTrim(0, 0, 0, 0); addInternalTrim(trim); return trim; } /** * Adds the internal trimmings to the given trim of the shell. * * @param trim the shell's trim, will be updated * @since 3.4 */ private void addInternalTrim(Rectangle trim) { trim.x-= fBorderWidth; trim.y-= fBorderWidth; trim.width+= 2 * fBorderWidth; trim.height+= 2 * fBorderWidth; if (! fHideScrollBars) { boolean RTL= (fShell.getStyle() & SWT.RIGHT_TO_LEFT) != 0; if (RTL) { trim.x-= fgScrollBarSize.x; } trim.width+= fgScrollBarSize.x; trim.height+= fgScrollBarSize.y; } if (fStatusTextField != null) { trim.height+= 2; // from the layout's verticalSpacing trim.height+= fSeparator.computeSize(SWT.DEFAULT, SWT.DEFAULT).y; trim.height+= fStatusTextField.computeSize(SWT.DEFAULT, SWT.DEFAULT).y; } if (fToolBar != null) { trim.height+= 2; // from the layout's verticalSpacing trim.height+= fTBSeparator.computeSize(SWT.DEFAULT, SWT.DEFAULT).y; trim.height+= fToolBar.computeSize(SWT.DEFAULT, SWT.DEFAULT).y; } } /* * @see org.eclipse.jface.text.IInformationControlExtension3#getBounds() */ public Rectangle getBounds() { // return fShell == null || fShell.isDisposed() ? null : fShell.getBounds(); return fShell.getBounds(); } /* * @see org.eclipse.jface.text.IInformationControlExtension3#restoresLocation() */ public boolean restoresLocation() { return false; } /* * @see org.eclipse.jface.text.IInformationControlExtension3#restoresSize() */ public boolean restoresSize() { return false; } /* * @see IInformationControl#addDisposeListener(DisposeListener) */ public void addDisposeListener(DisposeListener listener) { fShell.addDisposeListener(listener); } /* * @see IInformationControl#removeDisposeListener(DisposeListener) */ public void removeDisposeListener(DisposeListener listener) { fShell.removeDisposeListener(listener); } /** * Adds the listener to the collection of listeners who will be * notified when the current location has changed or is about to change. * * @param listener the location listener * @since 3.4 */ public void addLocationListener(LocationListener listener) { fBrowser.addLocationListener(listener); } /* * @see IInformationControl#setForegroundColor(Color) */ public void setForegroundColor(Color foreground) { fBrowser.setForeground(foreground); } /* * @see IInformationControl#setBackgroundColor(Color) */ public void setBackgroundColor(Color background) { fBrowser.setBackground(background); } /* * @see IInformationControl#isFocusControl() */ public boolean isFocusControl() { return fShell.getDisplay().getActiveShell() == fShell; } /* * @see IInformationControl#setFocus() */ public void setFocus() { fShell.forceFocus(); fBrowser.setFocus(); } /* * @see IInformationControl#addFocusListener(FocusListener) */ public void addFocusListener(final FocusListener listener) { if (fFocusListeners.isEmpty()) { fShellListener= new Listener() { public void handleEvent(Event event) { Object[] listeners= fFocusListeners.getListeners(); for (int i = 0; i < listeners.length; i++) { FocusListener focusListener= (FocusListener)listeners[i]; if (event.type == SWT.Activate) { focusListener.focusGained(new FocusEvent(event)); } else { focusListener.focusLost(new FocusEvent(event)); } } } }; fBrowser.getShell().addListener(SWT.Deactivate, fShellListener); fBrowser.getShell().addListener(SWT.Activate, fShellListener); } fFocusListeners.add(listener); } /* * @see IInformationControl#removeFocusListener(FocusListener) */ public void removeFocusListener(FocusListener listener) { fFocusListeners.remove(listener); if (fFocusListeners.isEmpty()) { fBrowser.getShell().removeListener(SWT.Activate, fShellListener); fBrowser.getShell().removeListener(SWT.Deactivate, fShellListener); fShellListener= null; } } /* * @see IInformationControlExtension#hasContents() */ public boolean hasContents() { return fBrowserHasContent; } /* * @see org.eclipse.jface.text.IInformationControlExtension5#containsControl(org.eclipse.swt.widgets.Control) * @since 3.4 */ public boolean containsControl(Control control) { do { if (control == fShell) return true; if (control instanceof Shell) return false; control= control.getParent(); } while (control != null); return false; } /** * Adds a listener for input changes to this input change provider. * Has no effect if an identical listener is already registered. * * @param inputChangeListener the listener to add * @since 3.4 */ public void addInputChangeListener(IInputChangedListener inputChangeListener) { Assert.isNotNull(inputChangeListener); fInputChangeListeners.add(inputChangeListener); } /** * Removes the given input change listener from this input change provider. * Has no effect if an identical listener is not registered. * * @param inputChangeListener the listener to remove * @since 3.4 */ public void removeInputChangeListener(IInputChangedListener inputChangeListener) { fInputChangeListeners.remove(inputChangeListener); } /* * @see org.eclipse.jface.text.IDelayedInputChangeProvider#setDelayedInputChangeListener(org.eclipse.jface.text.IInputChangedListener) * @since 3.4 */ public void setDelayedInputChangeListener(IInputChangedListener inputChangeListener) { fDelayedInputChangeListener= inputChangeListener; } /** * Tells whether a delayed input change listener is registered. * * @return <code>true</code> iff a delayed input change * listener is currently registered * @since 3.4 */ public boolean hasDelayedInputChangeListener() { return fDelayedInputChangeListener != null; } /** * Notifies listeners of a delayed input change. * * @param newInput the new input, or <code>null</code> to request cancellation * @since 3.4 */ public void notifyDelayedInputChange(Object newInput) { if (fDelayedInputChangeListener != null) fDelayedInputChangeListener.inputChanged(newInput); } /* * @see org.eclipse.jface.text.IInformationControlExtension5#isVisible() * @since 3.4 */ public boolean isVisible() { return fShell != null && ! fShell.isDisposed() && fShell.isVisible(); } /* * @see org.eclipse.jface.text.IInformationControlExtension5#allowMoveIntoControl() * @since 3.4 */ public boolean allowMoveIntoControl() { return true; } /* * @see java.lang.Object#toString() * @since 3.4 */ public String toString() { String style= (fShell.getStyle() & SWT.RESIZE) == 0 ? "fixed" : "resizeable"; //$NON-NLS-1$ //$NON-NLS-2$ return super.toString() + " - style: " + style; //$NON-NLS-1$ } /** * @return the current browser input or <code>null</code> */ public BrowserInformationControlInput getInput() { return fInput; } }
true
true
public void setInput(Object input) { Assert.isLegal(input instanceof String || input instanceof BrowserInformationControlInput); if (input instanceof String) { setInformation((String)input); return; } fInput= (BrowserInformationControlInput)input; String content= null; if (fInput != null) content= fInput.getHtml(); fBrowserHasContent= content != null && content.length() > 0; if (!fBrowserHasContent) content= "<html><body ></html>"; //$NON-NLS-1$ int shellStyle= fShell.getStyle(); boolean RTL= (shellStyle & SWT.RIGHT_TO_LEFT) != 0; // The default "overflow:auto" would not result in a predictable width for the client area // and the re-wrapping would cause visual noise String[] styles= null; if (RTL && !fHideScrollBars) styles= new String[] { "direction:rtl;", "overflow:scroll;", "word-wrap:break-word;" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ else if (RTL && fHideScrollBars) styles= new String[] { "direction:rtl;", "overflow:hidden;", "word-wrap:break-word;" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ else if (fHideScrollBars) //XXX: In IE, "word-wrap: break-word;" causes bogus wrapping even in non-broken words :-(see e.g. Javadoc of String). // Re-check whether we really still need this now that the Javadoc Hover header already sets this style. styles= new String[] { "overflow:hidden;"/*, "word-wrap: break-word;"*/ }; //$NON-NLS-1$ else styles= new String[] { "overflow:scroll;" }; //$NON-NLS-1$ StringBuffer buffer= new StringBuffer(content); HTMLPrinter.insertStyles(buffer, styles); content= buffer.toString(); /* * XXX: Should add some JavaScript here that shows something like * "(continued...)" or "..." at the end of the visible area when the page overflowed * with "overflow:hidden;". */ fCompleted= false; fBrowser.setText(content); Object[] listeners= fInputChangeListeners.getListeners(); for (int i= 0; i < listeners.length; i++) ((IInputChangedListener)listeners[i]).inputChanged(fInput); }
public void setInput(Object input) { Assert.isLegal(input == null || input instanceof String || input instanceof BrowserInformationControlInput); if (input instanceof String) { setInformation((String)input); return; } fInput= (BrowserInformationControlInput)input; String content= null; if (fInput != null) content= fInput.getHtml(); fBrowserHasContent= content != null && content.length() > 0; if (!fBrowserHasContent) content= "<html><body ></html>"; //$NON-NLS-1$ int shellStyle= fShell.getStyle(); boolean RTL= (shellStyle & SWT.RIGHT_TO_LEFT) != 0; // The default "overflow:auto" would not result in a predictable width for the client area // and the re-wrapping would cause visual noise String[] styles= null; if (RTL && !fHideScrollBars) styles= new String[] { "direction:rtl;", "overflow:scroll;", "word-wrap:break-word;" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ else if (RTL && fHideScrollBars) styles= new String[] { "direction:rtl;", "overflow:hidden;", "word-wrap:break-word;" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ else if (fHideScrollBars) //XXX: In IE, "word-wrap: break-word;" causes bogus wrapping even in non-broken words :-(see e.g. Javadoc of String). // Re-check whether we really still need this now that the Javadoc Hover header already sets this style. styles= new String[] { "overflow:hidden;"/*, "word-wrap: break-word;"*/ }; //$NON-NLS-1$ else styles= new String[] { "overflow:scroll;" }; //$NON-NLS-1$ StringBuffer buffer= new StringBuffer(content); HTMLPrinter.insertStyles(buffer, styles); content= buffer.toString(); /* * XXX: Should add some JavaScript here that shows something like * "(continued...)" or "..." at the end of the visible area when the page overflowed * with "overflow:hidden;". */ fCompleted= false; fBrowser.setText(content); Object[] listeners= fInputChangeListeners.getListeners(); for (int i= 0; i < listeners.length; i++) ((IInputChangedListener)listeners[i]).inputChanged(fInput); }
diff --git a/org.eclipse.nebula.widgets.nattable.core.test/src/org/eclipse/nebula/widgets/nattable/selection/SelectionLayerStructuralChangeEventHandlerTest.java b/org.eclipse.nebula.widgets.nattable.core.test/src/org/eclipse/nebula/widgets/nattable/selection/SelectionLayerStructuralChangeEventHandlerTest.java index 70486ac9..0632b327 100644 --- a/org.eclipse.nebula.widgets.nattable.core.test/src/org/eclipse/nebula/widgets/nattable/selection/SelectionLayerStructuralChangeEventHandlerTest.java +++ b/org.eclipse.nebula.widgets.nattable.core.test/src/org/eclipse/nebula/widgets/nattable/selection/SelectionLayerStructuralChangeEventHandlerTest.java @@ -1,59 +1,59 @@ /******************************************************************************* * Copyright (c) 2012 Original authors 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: * Original authors and others - initial API and implementation ******************************************************************************/ package org.eclipse.nebula.widgets.nattable.selection; import org.eclipse.nebula.widgets.nattable.layer.event.RowDeleteEvent; import org.eclipse.nebula.widgets.nattable.layer.stack.DefaultBodyLayerStack; import org.eclipse.nebula.widgets.nattable.selection.ISelectionModel; import org.eclipse.nebula.widgets.nattable.selection.SelectionLayer; import org.eclipse.nebula.widgets.nattable.selection.event.SelectionLayerStructuralChangeEventHandler; import org.eclipse.nebula.widgets.nattable.test.fixture.layer.DataLayerFixture; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class SelectionLayerStructuralChangeEventHandlerTest { private ISelectionModel selectionModel; private DataLayerFixture dataLayer; private SelectionLayer selectionLayer; @Before public void setup(){ dataLayer = new DataLayerFixture(10, 10); DefaultBodyLayerStack bodyLayer = new DefaultBodyLayerStack(dataLayer); selectionLayer = bodyLayer.getSelectionLayer(); selectionModel = selectionLayer.getSelectionModel(); } @Test public void shouldClearSelectionIfASelectedRowIsModified() throws Exception { selectionModel.addSelection(2, 3); SelectionLayerStructuralChangeEventHandler handler = new SelectionLayerStructuralChangeEventHandler(selectionLayer, selectionModel); handler.handleLayerEvent(new RowDeleteEvent(dataLayer, 3)); Assert.assertTrue(selectionModel.isEmpty()); } @Test public void shouldLeaveSelectionUnchangedIfASelectedRowIsNotModified() throws Exception { selectionModel.addSelection(2, 3); SelectionLayerStructuralChangeEventHandler handler = new SelectionLayerStructuralChangeEventHandler(selectionLayer, selectionModel); - handler.handleLayerEvent(new RowDeleteEvent(dataLayer, 4)); + handler.handleLayerEvent(new RowDeleteEvent(dataLayer, 5)); Assert.assertFalse(selectionModel.isEmpty()); Assert.assertTrue(selectionModel.isRowPositionSelected(3)); } }
true
true
public void shouldLeaveSelectionUnchangedIfASelectedRowIsNotModified() throws Exception { selectionModel.addSelection(2, 3); SelectionLayerStructuralChangeEventHandler handler = new SelectionLayerStructuralChangeEventHandler(selectionLayer, selectionModel); handler.handleLayerEvent(new RowDeleteEvent(dataLayer, 4)); Assert.assertFalse(selectionModel.isEmpty()); Assert.assertTrue(selectionModel.isRowPositionSelected(3)); }
public void shouldLeaveSelectionUnchangedIfASelectedRowIsNotModified() throws Exception { selectionModel.addSelection(2, 3); SelectionLayerStructuralChangeEventHandler handler = new SelectionLayerStructuralChangeEventHandler(selectionLayer, selectionModel); handler.handleLayerEvent(new RowDeleteEvent(dataLayer, 5)); Assert.assertFalse(selectionModel.isEmpty()); Assert.assertTrue(selectionModel.isRowPositionSelected(3)); }
diff --git a/src/polskaad1340/PolskaAD1340.java b/src/polskaad1340/PolskaAD1340.java index 185aa54..e61cc48 100644 --- a/src/polskaad1340/PolskaAD1340.java +++ b/src/polskaad1340/PolskaAD1340.java @@ -1,102 +1,102 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package polskaad1340; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import polskaad1340.window.LadowanieMapy; import polskaad1340.window.OknoMapy; import world.World; import agents.Agent; import clips.ClipsEnvironment; /** * * @author Kuba */ public class PolskaAD1340 { /** * @param args the command line arguments */ public static void main(String[] args) { System.setProperty("java.util.Arrays.useLegacyMergeSort", "true"); //bugfix, patrz http://stackoverflow.com/questions/13575224/comparison-method-violates-its-general-contract-timsort-and-gridlayout // TODO code application logic here OknoMapy om = new OknoMapy(); om.setVisible(true); try { LadowanieMapy lm = new LadowanieMapy("/maps/example.json"); om.importBackgroundTileGrid(lm.getMap()); om.setForegroundTileGrid(om.createTileGrid(lm.getMapSize(), 0)); om.drawAllTiles(); ClipsEnvironment clipsEnv = new ClipsEnvironment(); World world = new World(clipsEnv, lm, om); ArrayList<String> inferenceResults = new ArrayList<String>(); // glowna petla - for (int i = 0; i < 3; i++) { + for (int i = 0; i < 10; i++) { System.out.println("|ITERACJA " + (i + 1) + " |"); clipsEnv.getWorldEnv().reset(); // do swiata przekazujemy obiekty swiata oraz wywnioskowane // przez agentow fakty world.saveToClips(); for (int k = 0; k < inferenceResults.size(); k++) { clipsEnv.getWorldEnv().assertString(inferenceResults.get(k)); } clipsEnv.getWorldEnv().assertString("(iteracja " + (i + 1) + ")"); inferenceResults = new ArrayList<String>(); System.out.println("<wnioskowanie swiata>"); clipsEnv.getWorldEnv().run(); System.out.println("</wnioskowanie swiata>"); //clipsEnv.displayWorldFacts(); world.loadFromClips(); for (int j = 0; j < world.getAgents().size(); j++) { Agent actualAgent = world.getAgents().get(j); ArrayList<Object> visibleObjects = world.getVisibleWorld(actualAgent.getId()); clipsEnv.getAgentEnv().reset(); clipsEnv.getAgentEnv().load(actualAgent.getPathToClipsFile()); for (int k = 0; k < visibleObjects.size(); k++) { clipsEnv.getAgentEnv().assertString(visibleObjects.get(k).toString()); } // dany agent wnioskuje //clipsEnv.displayAgentFacts(); System.out.println("<wnioskowanie agenta " + actualAgent.getId() + " >"); clipsEnv.getAgentEnv().run(); System.out.println("</wnioskowanie agenta " + actualAgent.getId() + " >"); ArrayList<String> agentInferenceResults = actualAgent.getInferenceResults(clipsEnv.getAgentEnv()); // wywnioskowane przez agenta fakty dodajemy do wszystkich // faktow, ktore po wnioskowaniu wszystkich agentow zosatna przekazane do swiata for (String agentInferenceResult : agentInferenceResults) { inferenceResults.add(agentInferenceResult); } } System.out.println("|KONIEC ITERACJI " + (i + 1) + " |\n"); } } catch (Exception ex) { Logger.getLogger(PolskaAD1340.class.getName()).log(Level.SEVERE, null, ex); } System.out.println("done and done."); } }
true
true
public static void main(String[] args) { System.setProperty("java.util.Arrays.useLegacyMergeSort", "true"); //bugfix, patrz http://stackoverflow.com/questions/13575224/comparison-method-violates-its-general-contract-timsort-and-gridlayout // TODO code application logic here OknoMapy om = new OknoMapy(); om.setVisible(true); try { LadowanieMapy lm = new LadowanieMapy("/maps/example.json"); om.importBackgroundTileGrid(lm.getMap()); om.setForegroundTileGrid(om.createTileGrid(lm.getMapSize(), 0)); om.drawAllTiles(); ClipsEnvironment clipsEnv = new ClipsEnvironment(); World world = new World(clipsEnv, lm, om); ArrayList<String> inferenceResults = new ArrayList<String>(); // glowna petla for (int i = 0; i < 3; i++) { System.out.println("|ITERACJA " + (i + 1) + " |"); clipsEnv.getWorldEnv().reset(); // do swiata przekazujemy obiekty swiata oraz wywnioskowane // przez agentow fakty world.saveToClips(); for (int k = 0; k < inferenceResults.size(); k++) { clipsEnv.getWorldEnv().assertString(inferenceResults.get(k)); } clipsEnv.getWorldEnv().assertString("(iteracja " + (i + 1) + ")"); inferenceResults = new ArrayList<String>(); System.out.println("<wnioskowanie swiata>"); clipsEnv.getWorldEnv().run(); System.out.println("</wnioskowanie swiata>"); //clipsEnv.displayWorldFacts(); world.loadFromClips(); for (int j = 0; j < world.getAgents().size(); j++) { Agent actualAgent = world.getAgents().get(j); ArrayList<Object> visibleObjects = world.getVisibleWorld(actualAgent.getId()); clipsEnv.getAgentEnv().reset(); clipsEnv.getAgentEnv().load(actualAgent.getPathToClipsFile()); for (int k = 0; k < visibleObjects.size(); k++) { clipsEnv.getAgentEnv().assertString(visibleObjects.get(k).toString()); } // dany agent wnioskuje //clipsEnv.displayAgentFacts(); System.out.println("<wnioskowanie agenta " + actualAgent.getId() + " >"); clipsEnv.getAgentEnv().run(); System.out.println("</wnioskowanie agenta " + actualAgent.getId() + " >"); ArrayList<String> agentInferenceResults = actualAgent.getInferenceResults(clipsEnv.getAgentEnv()); // wywnioskowane przez agenta fakty dodajemy do wszystkich // faktow, ktore po wnioskowaniu wszystkich agentow zosatna przekazane do swiata for (String agentInferenceResult : agentInferenceResults) { inferenceResults.add(agentInferenceResult); } } System.out.println("|KONIEC ITERACJI " + (i + 1) + " |\n"); } } catch (Exception ex) { Logger.getLogger(PolskaAD1340.class.getName()).log(Level.SEVERE, null, ex); } System.out.println("done and done."); }
public static void main(String[] args) { System.setProperty("java.util.Arrays.useLegacyMergeSort", "true"); //bugfix, patrz http://stackoverflow.com/questions/13575224/comparison-method-violates-its-general-contract-timsort-and-gridlayout // TODO code application logic here OknoMapy om = new OknoMapy(); om.setVisible(true); try { LadowanieMapy lm = new LadowanieMapy("/maps/example.json"); om.importBackgroundTileGrid(lm.getMap()); om.setForegroundTileGrid(om.createTileGrid(lm.getMapSize(), 0)); om.drawAllTiles(); ClipsEnvironment clipsEnv = new ClipsEnvironment(); World world = new World(clipsEnv, lm, om); ArrayList<String> inferenceResults = new ArrayList<String>(); // glowna petla for (int i = 0; i < 10; i++) { System.out.println("|ITERACJA " + (i + 1) + " |"); clipsEnv.getWorldEnv().reset(); // do swiata przekazujemy obiekty swiata oraz wywnioskowane // przez agentow fakty world.saveToClips(); for (int k = 0; k < inferenceResults.size(); k++) { clipsEnv.getWorldEnv().assertString(inferenceResults.get(k)); } clipsEnv.getWorldEnv().assertString("(iteracja " + (i + 1) + ")"); inferenceResults = new ArrayList<String>(); System.out.println("<wnioskowanie swiata>"); clipsEnv.getWorldEnv().run(); System.out.println("</wnioskowanie swiata>"); //clipsEnv.displayWorldFacts(); world.loadFromClips(); for (int j = 0; j < world.getAgents().size(); j++) { Agent actualAgent = world.getAgents().get(j); ArrayList<Object> visibleObjects = world.getVisibleWorld(actualAgent.getId()); clipsEnv.getAgentEnv().reset(); clipsEnv.getAgentEnv().load(actualAgent.getPathToClipsFile()); for (int k = 0; k < visibleObjects.size(); k++) { clipsEnv.getAgentEnv().assertString(visibleObjects.get(k).toString()); } // dany agent wnioskuje //clipsEnv.displayAgentFacts(); System.out.println("<wnioskowanie agenta " + actualAgent.getId() + " >"); clipsEnv.getAgentEnv().run(); System.out.println("</wnioskowanie agenta " + actualAgent.getId() + " >"); ArrayList<String> agentInferenceResults = actualAgent.getInferenceResults(clipsEnv.getAgentEnv()); // wywnioskowane przez agenta fakty dodajemy do wszystkich // faktow, ktore po wnioskowaniu wszystkich agentow zosatna przekazane do swiata for (String agentInferenceResult : agentInferenceResults) { inferenceResults.add(agentInferenceResult); } } System.out.println("|KONIEC ITERACJI " + (i + 1) + " |\n"); } } catch (Exception ex) { Logger.getLogger(PolskaAD1340.class.getName()).log(Level.SEVERE, null, ex); } System.out.println("done and done."); }
diff --git a/CubicTestSeleniumExporterServer/src/main/java/org/cubictest/runner/selenium/server/internal/CubicSelenium.java b/CubicTestSeleniumExporterServer/src/main/java/org/cubictest/runner/selenium/server/internal/CubicSelenium.java index ded9ef09..760e9b52 100644 --- a/CubicTestSeleniumExporterServer/src/main/java/org/cubictest/runner/selenium/server/internal/CubicSelenium.java +++ b/CubicTestSeleniumExporterServer/src/main/java/org/cubictest/runner/selenium/server/internal/CubicSelenium.java @@ -1,658 +1,659 @@ package org.cubictest.runner.selenium.server.internal; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.Socket; import java.net.UnknownHostException; import javax.net.SocketFactory; import com.thoughtworks.selenium.Selenium; public class CubicSelenium implements Selenium { private final int port; private Socket socket; public CubicSelenium(int port) { this.port = port; } private void createSocket() throws IOException, UnknownHostException { socket = SocketFactory.getDefault().createSocket("localhost",port); } private String[] execute(String command, String... args) { String[] results = null; try{ if(socket == null){ createSocket(); } OutputStream os = socket.getOutputStream(); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os)); bw.write(command); bw.newLine(); bw.write(args.length + ""); bw.newLine(); for (int i = 0; i < args.length; i++) { String value = args[i]; bw.write(value); bw.newLine(); } bw.flush(); InputStreamReader isr = new InputStreamReader(socket.getInputStream()); BufferedReader br = new BufferedReader(isr); int numberOfResults = Integer.parseInt(br.readLine()); results = new String[numberOfResults]; for(int i = 0; i < numberOfResults; i++) results[i] = br.readLine(); }catch (IOException e) { e.printStackTrace(); + throw new RuntimeException("Could not execute Selenium command: " + command + " " + args, e); } return results; } public void addSelection(String arg0, String arg1) { execute("addSelection", arg0, arg1); } public void altKeyDown() { execute("altKeyDown"); } public void altKeyUp() { execute("altKeyUp"); } public void answerOnNextPrompt(String arg0) { execute("answerOnNextPrompt", arg0); } public void check(String arg0) { execute("check"); } public void chooseCancelOnNextConfirmation() { execute("chooseCancelOnNextConfirmation"); } public void click(String arg0) { execute("click", arg0); } public void clickAt(String arg0, String arg1) { execute("clickAt", arg0, arg1); } public void close() { execute("close"); } public void controlKeyDown() { execute("controlKeyDown"); } public void controlKeyUp() { execute("controlKeyUp"); } public void createCookie(String arg0, String arg1) { execute("createCookie", arg0, arg1); } public void deleteCookie(String arg0, String arg1) { execute("deleteCookie", arg0, arg1); } public void doubleClick(String arg0) { execute("doubleClick", arg0); } public void doubleClickAt(String arg0, String arg1) { execute("doubleClickAt", arg0, arg1); } public void dragAndDrop(String arg0, String arg1) { execute("dragAndDrop", arg0, arg1); } public void dragAndDropToObject(String arg0, String arg1) { execute("dragAndDropToObject", arg0, arg1); } public void dragdrop(String arg0, String arg1) { execute("dragdrop", arg0, arg1); } public void fireEvent(String arg0, String arg1) { execute("fireEvent", arg0, arg1); } public String getAlert() { return execute("getAlert")[0]; } public String[] getAllButtons() { return execute("getAllButtons"); } public String[] getAllFields() { return execute("getAllFields"); } public String[] getAllLinks() { return execute("getAllLinks"); } public String[] getAllWindowIds() { return execute("getAllWindowIds"); } public String[] getAllWindowNames() { return execute("getAllWindowNames"); } public String[] getAllWindowTitles() { return execute("getAllWindowTitles"); } public String getAttribute(String arg0) { return execute("getAttribute", arg0)[0]; } public String[] getAttributeFromAllWindows(String arg0) { return execute("getAttributeFromAllWindows", arg0); } public String getBodyText() { return execute("getBodyText")[0]; } public String getConfirmation() { return execute("getConfirmation")[0]; } public String getCookie() { return execute("getCookie")[0]; } public Number getCursorPosition(String arg0) { return Double.parseDouble(execute("getCursorPosition", arg0)[0]); } public Number getElementHeight(String arg0) { return Integer.parseInt(execute("getElementHeight", arg0)[0]); } public Number getElementIndex(String arg0) { return Integer.parseInt(execute("getElementIndex", arg0)[0]); } public Number getElementPositionLeft(String arg0) { return Integer.parseInt(execute("getElementPositionLeft", arg0)[0]); } public Number getElementPositionTop(String arg0) { return Integer.parseInt(execute("getElementPositionTop", arg0)[0]); } public Number getElementWidth(String arg0) { return Integer.parseInt(execute("getElementWidth", arg0)[0]); } public String getEval(String arg0) { return execute("getEval", arg0)[0]; } public String getExpression(String arg0) { return execute("getExpression", arg0)[0]; } public String getHtmlSource() { return execute("getHtmlSource")[0]; } public String getLocation() { return execute("getLocation")[0]; } public String getLogMessages() { return execute("getLogMessages")[0]; } public String getPrompt() { return execute("getPrompt")[0]; } public String[] getSelectOptions(String arg0) { return execute("getSelectOptions", arg0); } public String getSelectedId(String arg0) { return execute("getSelectedId", arg0)[0]; } public String[] getSelectedIds(String arg0) { return execute("getSelectedIds", arg0); } public String getSelectedIndex(String arg0) { return execute("getSelectedIndex", arg0)[0]; } public String[] getSelectedIndexes(String arg0) { return execute("getSelectedIndexes", arg0); } public String getSelectedLabel(String arg0) { return execute("getSelectedLabel", arg0)[0]; } public String[] getSelectedLabels(String arg0) { return execute("getSelectedLabels", arg0); } public String getSelectedValue(String arg0) { return execute("getSelectedValue", arg0)[0]; } public String[] getSelectedValues(String arg0) { return execute("getSelectedValues", arg0); } public void getSpeed() { execute("getSpeed"); } public String getTable(String arg0) { return execute("getTable", arg0)[0]; } public String getText(String arg0) { return execute("getText", arg0)[0]; } public String getTitle() { return execute("getTitle")[0]; } public String getValue(String arg0) { return execute("getValue", arg0)[0]; } public boolean getWhetherThisFrameMatchFrameExpression(String arg0, String arg1) { return Boolean.parseBoolean(execute("getWhetherThisFrameMatchFrameExpression", arg0, arg1)[0]); } public boolean getWhetherThisWindowMatchWindowExpression(String arg0, String arg1) { return Boolean.parseBoolean(execute("getWhetherThisWindowMatchWindowExpression", arg0, arg1)[0]); } public void goBack() { execute("goBack"); } public boolean isAlertPresent() { return Boolean.parseBoolean(execute("isAlertPresent")[0]); } public boolean isChecked(String arg0) { return Boolean.parseBoolean(execute("isChecked", arg0)[0]); } public boolean isConfirmationPresent() { return Boolean.parseBoolean(execute("isConfirmationPresent")[0]); } public boolean isEditable(String arg0) { return Boolean.parseBoolean(execute("isEditable", arg0)[0]); } public boolean isElementPresent(String arg0) { return Boolean.parseBoolean(execute("isElementPresent", arg0)[0]); } public boolean isOrdered(String arg0, String arg1) { return Boolean.parseBoolean(execute("isOrdered", arg0, arg1)[0]); } public boolean isPromptPresent() { return Boolean.parseBoolean(execute("isPromptPresent")[0]); } public boolean isSomethingSelected(String arg0) { return Boolean.parseBoolean(execute("isSomethingSelected", arg0)[0]); } public boolean isTextPresent(String arg0) { return Boolean.parseBoolean(execute("isTextPresent", arg0)[0]); } public boolean isVisible(String arg0) { return Boolean.parseBoolean(execute("isVisible", arg0)[0]); } public void keyDown(String arg0, String arg1) { execute("keyDown", arg0, arg1); } public void keyPress(String arg0, String arg1) { execute("keyPress", arg0, arg1); } public void keyUp(String arg0, String arg1) { execute("keyUp", arg0, arg1); } public void metaKeyDown() { execute("metaKeyDown"); } public void metaKeyUp() { execute("metaKeyUp"); } public void mouseDown(String arg0) { execute("mouseDown", arg0); } public void mouseDownAt(String arg0, String arg1) { execute("mouseDownAt", arg0, arg1); } public void mouseMove(String arg0) { execute("mouseMove", arg0); } public void mouseMoveAt(String arg0, String arg1) { execute("mouseMoveAt", arg0, arg1); } public void mouseOut(String arg0) { execute("mouseOut", arg0); } public void mouseOver(String arg0) { execute("mouseOver", arg0); } public void mouseUp(String arg0) { execute("mouseUp", arg0); } public void mouseUpAt(String arg0, String arg1) { execute("mouseUpAt", arg0, arg1); } public void open(String arg0) { execute("open", arg0); } public void openWindow(String arg0, String arg1) { execute("openWindow", arg0, arg1); } public void refresh() { execute("refresh"); } public void removeSelection(String arg0, String arg1) { execute("removeSelection", arg0, arg1); } public void select(String arg0, String arg1) { execute("select", arg0, arg1); } public void selectFrame(String arg0) { execute("selectFrame", arg0); } public void selectWindow(String arg0) { execute("selectWindow", arg0); } public void setContext(String arg0, String arg1) { execute("setContext", arg0, arg1); } public void setCursorPosition(String arg0, String arg1) { execute("setCursorPosition", arg0, arg1); } public void setSpeed(String arg0) { execute("setSpeed", arg0); } public void setTimeout(String arg0) { execute("setTimeout", arg0); } public void shiftKeyDown() { execute("shiftKeyDown"); } public void shiftKeyUp() { execute("shiftKeyUp"); } public void start() { execute("start"); } public void stop() { execute("stop"); } public void submit(String arg0) { execute("submit", arg0); } public void type(String arg0, String arg1) { execute("type", arg0, arg1); } public void uncheck(String arg0) { execute("uncheck", arg0); } public void waitForCondition(String arg0, String arg1) { execute("waitForCondition", arg0, arg1); } public void waitForPageToLoad(String arg0) { execute("waitForPageToLoad", arg0); } public void waitForPopUp(String arg0, String arg1) { execute("waitForPopUp", arg0, arg1); } public void windowFocus(String arg0) { execute("windowFocus", arg0); } public void windowMaximize(String arg0) { execute("windowMaximize", arg0); } public void addLocationStrategy(String arg0, String arg1) { execute("addLocationStrategy", arg0, arg1); } public void allowNativeXpath(String arg0) { execute("allowNativeXpath", arg0); } public void assignId(String arg0, String arg1) { execute("assignId", arg0, arg1); } public void captureScreenshot(String arg0) { execute("captureScreenshot", arg0); } public void chooseOkOnNextConfirmation() { execute("chooseOkOnNextConfirmation"); } public Number getMouseSpeed() { return Integer.parseInt(execute("getMouseSpeed")[0]); } public Number getXpathCount(String arg0) { return Integer.parseInt(execute("getXpathCount", arg0)[0]); } public void highlight(String arg0) { execute("highlight", arg0); } public void removeAllSelections(String arg0) { execute("removeAllSelections", arg0); } public void runScript(String arg0) { execute("runScript", arg0); } public void setBrowserLogLevel(String arg0) { execute("setBrowserLogLevel", arg0); } public void setContext(String arg0) { execute("setContext", arg0); } public void setMouseSpeed(String arg0) { execute("setMouseSpeed", arg0); } public void typeKeys(String arg0, String arg1) { execute("typeKeys", arg0, arg1); } public void waitForFrameToLoad(String arg0, String arg1) { execute("waitForFrameToLoad", arg0, arg1); } public void windowFocus() { execute("windowFocus"); } public void windowMaximize() { execute("windowMaximize"); } }
true
true
private String[] execute(String command, String... args) { String[] results = null; try{ if(socket == null){ createSocket(); } OutputStream os = socket.getOutputStream(); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os)); bw.write(command); bw.newLine(); bw.write(args.length + ""); bw.newLine(); for (int i = 0; i < args.length; i++) { String value = args[i]; bw.write(value); bw.newLine(); } bw.flush(); InputStreamReader isr = new InputStreamReader(socket.getInputStream()); BufferedReader br = new BufferedReader(isr); int numberOfResults = Integer.parseInt(br.readLine()); results = new String[numberOfResults]; for(int i = 0; i < numberOfResults; i++) results[i] = br.readLine(); }catch (IOException e) { e.printStackTrace(); } return results; }
private String[] execute(String command, String... args) { String[] results = null; try{ if(socket == null){ createSocket(); } OutputStream os = socket.getOutputStream(); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os)); bw.write(command); bw.newLine(); bw.write(args.length + ""); bw.newLine(); for (int i = 0; i < args.length; i++) { String value = args[i]; bw.write(value); bw.newLine(); } bw.flush(); InputStreamReader isr = new InputStreamReader(socket.getInputStream()); BufferedReader br = new BufferedReader(isr); int numberOfResults = Integer.parseInt(br.readLine()); results = new String[numberOfResults]; for(int i = 0; i < numberOfResults; i++) results[i] = br.readLine(); }catch (IOException e) { e.printStackTrace(); throw new RuntimeException("Could not execute Selenium command: " + command + " " + args, e); } return results; }
diff --git a/org.emftext.sdk/src/org/emftext/sdk/finders/GenPackageByHintFinder.java b/org.emftext.sdk/src/org/emftext/sdk/finders/GenPackageByHintFinder.java index 41b229b29..b55395303 100644 --- a/org.emftext.sdk/src/org/emftext/sdk/finders/GenPackageByHintFinder.java +++ b/org.emftext.sdk/src/org/emftext/sdk/finders/GenPackageByHintFinder.java @@ -1,75 +1,78 @@ /******************************************************************************* * Copyright (c) 2006-2009 * Software Technology Group, Dresden University of Technology * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) any * later version. This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU Lesser General Public License for more details. You should have * received a copy of the GNU Lesser General Public License along with this * program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, * Suite 330, Boston, MA 02111-1307 USA * * Contributors: * Software Technology Group - TU Dresden, Germany * - initial API and implementation ******************************************************************************/ package org.emftext.sdk.finders; import java.util.HashSet; import java.util.Set; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.resource.ResourceSet; import org.emftext.runtime.EMFTextRuntimePlugin; import org.emftext.runtime.resource.ITextResource; import org.emftext.sdk.concretesyntax.GenPackageDependentElement; /** * A finder that searches in the current project in the Eclipse workspace * for files that contain generator packages. */ public class GenPackageByHintFinder extends GenPackageInFileFinder { private Set<String> faultyHints = new HashSet<String>(); public IGenPackageFinderResult findGenPackage(String nsURI, String locationHint, GenPackageDependentElement container, ITextResource resource) { if (locationHint == null) { return null; } if (faultyHints.contains(locationHint)) { return null; } return findGenPackageUsingHint(nsURI, locationHint, container, resource); } /** * Search the current project generator models. * * @param nsURI * @param rs * @param platformString * @return */ private IGenPackageFinderResult findGenPackageUsingHint(String nsURI, String locationHint, GenPackageDependentElement container, ITextResource resource) { + if (resource == null) { + return null; + } ResourceSet rs = resource.getResourceSet(); if (rs == null) { return null; } try { URI hintURI = new LocationHintResolver().getLocationHintURI(locationHint, container); if ("genmodel".equals(hintURI.fileExtension())) { return findGenPackage(getSyntax(container), nsURI, rs, hintURI); } } catch (Exception e) { e.printStackTrace(); EMFTextRuntimePlugin.logError("Exception while looking for generator package.", e); } return null; } }
true
true
private IGenPackageFinderResult findGenPackageUsingHint(String nsURI, String locationHint, GenPackageDependentElement container, ITextResource resource) { ResourceSet rs = resource.getResourceSet(); if (rs == null) { return null; } try { URI hintURI = new LocationHintResolver().getLocationHintURI(locationHint, container); if ("genmodel".equals(hintURI.fileExtension())) { return findGenPackage(getSyntax(container), nsURI, rs, hintURI); } } catch (Exception e) { e.printStackTrace(); EMFTextRuntimePlugin.logError("Exception while looking for generator package.", e); } return null; }
private IGenPackageFinderResult findGenPackageUsingHint(String nsURI, String locationHint, GenPackageDependentElement container, ITextResource resource) { if (resource == null) { return null; } ResourceSet rs = resource.getResourceSet(); if (rs == null) { return null; } try { URI hintURI = new LocationHintResolver().getLocationHintURI(locationHint, container); if ("genmodel".equals(hintURI.fileExtension())) { return findGenPackage(getSyntax(container), nsURI, rs, hintURI); } } catch (Exception e) { e.printStackTrace(); EMFTextRuntimePlugin.logError("Exception while looking for generator package.", e); } return null; }
diff --git a/src/dk/stacktrace/risk/game_logic/continents/Asia.java b/src/dk/stacktrace/risk/game_logic/continents/Asia.java index a10d9b8..01068f8 100644 --- a/src/dk/stacktrace/risk/game_logic/continents/Asia.java +++ b/src/dk/stacktrace/risk/game_logic/continents/Asia.java @@ -1,184 +1,185 @@ package dk.stacktrace.risk.game_logic.continents; import java.util.ArrayList; import java.util.Collections; import android.util.Log; import dk.stacktrace.risk.game_logic.Board; import dk.stacktrace.risk.game_logic.Territory; import dk.stacktrace.risk.game_logic.enumerate.TerritoryID; public class Asia extends Continent { private Territory siberia, yakutsk, kamchatka, ural, irkutsk, mongolia, japan, afghanistan, china, middleEast, india, siam; public Asia(Board board) { this.board = board; territories = new ArrayList<Territory>(); reinforcementBonus = 7; createTerritories(); } protected void createTerritories() { Log.v("create territories", "1"); siberia = new Territory("Siberia", TerritoryID.SIB); yakutsk = new Territory("Yakutsk", TerritoryID.YAK); kamchatka = new Territory("Kamchatka", TerritoryID.KAM); ural = new Territory("Ural", TerritoryID.URA); irkutsk = new Territory("Irkutsk", TerritoryID.IRK); mongolia = new Territory("Mongolia", TerritoryID.MON); japan = new Territory("Japan", TerritoryID.JAP); afghanistan = new Territory("Afghanistan", TerritoryID.AFG); china = new Territory("China", TerritoryID.CHI); middleEast = new Territory("Middle East", TerritoryID.MID); india = new Territory("India", TerritoryID.IDA); siam = new Territory("Siam", TerritoryID.SIA); Collections.addAll(territories, siberia, yakutsk, kamchatka, ural, irkutsk, mongolia, japan, afghanistan, china, middleEast, india, siam); } public void setNeighbours() { siberia.addNeighbour(ural); siberia.addNeighbour(yakutsk); siberia.addNeighbour(irkutsk); siberia.addNeighbour(mongolia); siberia.addNeighbour(china); yakutsk.addNeighbour(siberia); yakutsk.addNeighbour(kamchatka); yakutsk.addNeighbour(irkutsk); kamchatka.addNeighbour(yakutsk); kamchatka.addNeighbour(board.getNorthAmerica().getAlaska()); kamchatka.addNeighbour(mongolia); kamchatka.addNeighbour(irkutsk); kamchatka.addNeighbour(japan); ural.addNeighbour(board.getEurope().getUkraine()); ural.addNeighbour(siberia); ural.addNeighbour(china); ural.addNeighbour(afghanistan); irkutsk.addNeighbour(siberia); irkutsk.addNeighbour(yakutsk); irkutsk.addNeighbour(kamchatka); irkutsk.addNeighbour(mongolia); mongolia.addNeighbour(siberia); mongolia.addNeighbour(yakutsk); mongolia.addNeighbour(kamchatka); mongolia.addNeighbour(japan); mongolia.addNeighbour(china); mongolia.addNeighbour(irkutsk); japan.addNeighbour(kamchatka); japan.addNeighbour(mongolia); afghanistan.addNeighbour(board.getEurope().getUkraine()); afghanistan.addNeighbour(ural); afghanistan.addNeighbour(china); afghanistan.addNeighbour(india); afghanistan.addNeighbour(middleEast); china.addNeighbour(afghanistan); china.addNeighbour(ural); china.addNeighbour(siberia); china.addNeighbour(mongolia); china.addNeighbour(siam); china.addNeighbour(india); middleEast.addNeighbour(board.getAfrica().getEgypt()); + middleEast.addNeighbour(board.getAfrica().getEastAfrica()); middleEast.addNeighbour(board.getEurope().getSouthEurope()); middleEast.addNeighbour(board.getEurope().getUkraine()); middleEast.addNeighbour(afghanistan); middleEast.addNeighbour(india); india.addNeighbour(middleEast); india.addNeighbour(afghanistan); india.addNeighbour(china); india.addNeighbour(siam); siam.addNeighbour(india); siam.addNeighbour(china); siam.addNeighbour(board.getAustralia().getIndonesia()); } public Territory getSiberia() { return siberia; } public Territory getYakutsk() { return yakutsk; } public Territory getKamchatka() { return kamchatka; } public Territory getUral() { return ural; } public Territory getIrkutsk() { return irkutsk; } public Territory getMongolia() { return mongolia; } public Territory getJapan() { return japan; } public Territory getAfghanistan() { return afghanistan; } public Territory getChina() { return china; } public Territory getMiddleEast() { return middleEast; } public Territory getIndia() { return india; } public Territory getSiam() { return siam; } public Board getBoard() { return board; } }
true
true
public void setNeighbours() { siberia.addNeighbour(ural); siberia.addNeighbour(yakutsk); siberia.addNeighbour(irkutsk); siberia.addNeighbour(mongolia); siberia.addNeighbour(china); yakutsk.addNeighbour(siberia); yakutsk.addNeighbour(kamchatka); yakutsk.addNeighbour(irkutsk); kamchatka.addNeighbour(yakutsk); kamchatka.addNeighbour(board.getNorthAmerica().getAlaska()); kamchatka.addNeighbour(mongolia); kamchatka.addNeighbour(irkutsk); kamchatka.addNeighbour(japan); ural.addNeighbour(board.getEurope().getUkraine()); ural.addNeighbour(siberia); ural.addNeighbour(china); ural.addNeighbour(afghanistan); irkutsk.addNeighbour(siberia); irkutsk.addNeighbour(yakutsk); irkutsk.addNeighbour(kamchatka); irkutsk.addNeighbour(mongolia); mongolia.addNeighbour(siberia); mongolia.addNeighbour(yakutsk); mongolia.addNeighbour(kamchatka); mongolia.addNeighbour(japan); mongolia.addNeighbour(china); mongolia.addNeighbour(irkutsk); japan.addNeighbour(kamchatka); japan.addNeighbour(mongolia); afghanistan.addNeighbour(board.getEurope().getUkraine()); afghanistan.addNeighbour(ural); afghanistan.addNeighbour(china); afghanistan.addNeighbour(india); afghanistan.addNeighbour(middleEast); china.addNeighbour(afghanistan); china.addNeighbour(ural); china.addNeighbour(siberia); china.addNeighbour(mongolia); china.addNeighbour(siam); china.addNeighbour(india); middleEast.addNeighbour(board.getAfrica().getEgypt()); middleEast.addNeighbour(board.getEurope().getSouthEurope()); middleEast.addNeighbour(board.getEurope().getUkraine()); middleEast.addNeighbour(afghanistan); middleEast.addNeighbour(india); india.addNeighbour(middleEast); india.addNeighbour(afghanistan); india.addNeighbour(china); india.addNeighbour(siam); siam.addNeighbour(india); siam.addNeighbour(china); siam.addNeighbour(board.getAustralia().getIndonesia()); }
public void setNeighbours() { siberia.addNeighbour(ural); siberia.addNeighbour(yakutsk); siberia.addNeighbour(irkutsk); siberia.addNeighbour(mongolia); siberia.addNeighbour(china); yakutsk.addNeighbour(siberia); yakutsk.addNeighbour(kamchatka); yakutsk.addNeighbour(irkutsk); kamchatka.addNeighbour(yakutsk); kamchatka.addNeighbour(board.getNorthAmerica().getAlaska()); kamchatka.addNeighbour(mongolia); kamchatka.addNeighbour(irkutsk); kamchatka.addNeighbour(japan); ural.addNeighbour(board.getEurope().getUkraine()); ural.addNeighbour(siberia); ural.addNeighbour(china); ural.addNeighbour(afghanistan); irkutsk.addNeighbour(siberia); irkutsk.addNeighbour(yakutsk); irkutsk.addNeighbour(kamchatka); irkutsk.addNeighbour(mongolia); mongolia.addNeighbour(siberia); mongolia.addNeighbour(yakutsk); mongolia.addNeighbour(kamchatka); mongolia.addNeighbour(japan); mongolia.addNeighbour(china); mongolia.addNeighbour(irkutsk); japan.addNeighbour(kamchatka); japan.addNeighbour(mongolia); afghanistan.addNeighbour(board.getEurope().getUkraine()); afghanistan.addNeighbour(ural); afghanistan.addNeighbour(china); afghanistan.addNeighbour(india); afghanistan.addNeighbour(middleEast); china.addNeighbour(afghanistan); china.addNeighbour(ural); china.addNeighbour(siberia); china.addNeighbour(mongolia); china.addNeighbour(siam); china.addNeighbour(india); middleEast.addNeighbour(board.getAfrica().getEgypt()); middleEast.addNeighbour(board.getAfrica().getEastAfrica()); middleEast.addNeighbour(board.getEurope().getSouthEurope()); middleEast.addNeighbour(board.getEurope().getUkraine()); middleEast.addNeighbour(afghanistan); middleEast.addNeighbour(india); india.addNeighbour(middleEast); india.addNeighbour(afghanistan); india.addNeighbour(china); india.addNeighbour(siam); siam.addNeighbour(india); siam.addNeighbour(china); siam.addNeighbour(board.getAustralia().getIndonesia()); }
diff --git a/src/com/android/mms/ui/UriImage.java b/src/com/android/mms/ui/UriImage.java index c74764b5..da3e8f13 100644 --- a/src/com/android/mms/ui/UriImage.java +++ b/src/com/android/mms/ui/UriImage.java @@ -1,405 +1,434 @@ /* * Copyright (C) 2008 Esmertec AG. * 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.mms.ui; import java.io.ByteArrayOutputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import android.content.ContentResolver; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SqliteWrapper; import android.graphics.Bitmap; import android.graphics.Bitmap.CompressFormat; import android.graphics.BitmapFactory; import android.net.Uri; import android.provider.MediaStore.Images; import android.provider.Telephony.Mms.Part; import android.text.TextUtils; import android.util.Log; import android.webkit.MimeTypeMap; import com.android.mms.LogTag; import com.android.mms.model.ImageModel; import com.google.android.mms.ContentType; import com.google.android.mms.pdu.PduPart; public class UriImage { private static final String TAG = "Mms/image"; private static final boolean DEBUG = false; private static final boolean LOCAL_LOGV = false; private final Context mContext; private final Uri mUri; private String mContentType; private String mPath; private String mSrc; private int mWidth; private int mHeight; public UriImage(Context context, Uri uri) { if ((null == context) || (null == uri)) { throw new IllegalArgumentException(); } String scheme = uri.getScheme(); if (scheme.equals("content")) { initFromContentUri(context, uri); } else if (uri.getScheme().equals("file")) { initFromFile(context, uri); } mContext = context; mUri = uri; decodeBoundsInfo(); if (LOCAL_LOGV) { Log.v(TAG, "UriImage uri: " + uri + " mPath: " + mPath + " mWidth: " + mWidth + " mHeight: " + mHeight); } } private void initFromFile(Context context, Uri uri) { mPath = uri.getPath(); MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton(); String extension = MimeTypeMap.getFileExtensionFromUrl(mPath); if (TextUtils.isEmpty(extension)) { // getMimeTypeFromExtension() doesn't handle spaces in filenames nor can it handle // urlEncoded strings. Let's try one last time at finding the extension. int dotPos = mPath.lastIndexOf('.'); if (0 <= dotPos) { extension = mPath.substring(dotPos + 1); } } mContentType = mimeTypeMap.getMimeTypeFromExtension(extension); // It's ok if mContentType is null. Eventually we'll show a toast telling the // user the picture couldn't be attached. buildSrcFromPath(); } private void buildSrcFromPath() { mSrc = mPath.substring(mPath.lastIndexOf('/') + 1); if(mSrc.startsWith(".") && mSrc.length() > 1) { mSrc = mSrc.substring(1); } // Some MMSCs appear to have problems with filenames // containing a space. So just replace them with // underscores in the name, which is typically not // visible to the user anyway. mSrc = mSrc.replace(' ', '_'); } private void initFromContentUri(Context context, Uri uri) { ContentResolver resolver = context.getContentResolver(); Cursor c = SqliteWrapper.query(context, resolver, uri, null, null, null, null); mSrc = null; if (c == null) { throw new IllegalArgumentException( "Query on " + uri + " returns null result."); } try { if ((c.getCount() != 1) || !c.moveToFirst()) { throw new IllegalArgumentException( "Query on " + uri + " returns 0 or multiple rows."); } String filePath; if (ImageModel.isMmsUri(uri)) { filePath = c.getString(c.getColumnIndexOrThrow(Part.FILENAME)); if (TextUtils.isEmpty(filePath)) { filePath = c.getString( c.getColumnIndexOrThrow(Part._DATA)); } mContentType = c.getString( c.getColumnIndexOrThrow(Part.CONTENT_TYPE)); } else { filePath = uri.getPath(); try { mContentType = c.getString( c.getColumnIndexOrThrow(Images.Media.MIME_TYPE)); // mime_type } catch (IllegalArgumentException e) { try { mContentType = c.getString(c.getColumnIndexOrThrow("mimetype")); } catch (IllegalArgumentException ex) { mContentType = resolver.getType(uri); Log.v(TAG, "initFromContentUri: " + uri + ", getType => " + mContentType); } } // use the original filename if possible int nameIndex = c.getColumnIndex(Images.Media.DISPLAY_NAME); if (nameIndex != -1) { mSrc = c.getString(nameIndex); if (!TextUtils.isEmpty(mSrc)) { // Some MMSCs appear to have problems with filenames // containing a space. So just replace them with // underscores in the name, which is typically not // visible to the user anyway. mSrc = mSrc.replace(' ', '_'); } else { mSrc = null; } } } mPath = filePath; if (mSrc == null) { buildSrcFromPath(); } } catch (IllegalArgumentException e) { Log.e(TAG, "initFromContentUri couldn't load image uri: " + uri, e); } finally { c.close(); } } private void decodeBoundsInfo() { InputStream input = null; try { input = mContext.getContentResolver().openInputStream(mUri); BitmapFactory.Options opt = new BitmapFactory.Options(); opt.inJustDecodeBounds = true; BitmapFactory.decodeStream(input, null, opt); mWidth = opt.outWidth; mHeight = opt.outHeight; } catch (FileNotFoundException e) { // Ignore Log.e(TAG, "IOException caught while opening stream", e); } finally { if (null != input) { try { input.close(); } catch (IOException e) { // Ignore Log.e(TAG, "IOException caught while closing stream", e); } } } } public String getContentType() { return mContentType; } public String getSrc() { return mSrc; } public String getPath() { return mPath; } public int getWidth() { return mWidth; } public int getHeight() { return mHeight; } /** * Get a version of this image resized to fit the given dimension and byte-size limits. Note * that the content type of the resulting PduPart may not be the same as the content type of * this UriImage; always call {@link PduPart#getContentType()} to get the new content type. * * @param widthLimit The width limit, in pixels * @param heightLimit The height limit, in pixels * @param byteLimit The binary size limit, in bytes * @return A new PduPart containing the resized image data */ public PduPart getResizedImageAsPart(int widthLimit, int heightLimit, int byteLimit) { PduPart part = new PduPart(); byte[] data = getResizedImageData(mWidth, mHeight, widthLimit, heightLimit, byteLimit, mUri, mContext); if (data == null) { if (LOCAL_LOGV) { Log.v(TAG, "Resize image failed."); } return null; } part.setData(data); // getResizedImageData ALWAYS compresses to JPEG, regardless of the original content type part.setContentType(ContentType.IMAGE_JPEG.getBytes()); return part; } private static final int NUMBER_OF_RESIZE_ATTEMPTS = 4; /** * Resize and recompress the image such that it fits the given limits. The resulting byte * array contains an image in JPEG format, regardless of the original image's content type. * @param widthLimit The width limit, in pixels * @param heightLimit The height limit, in pixels * @param byteLimit The binary size limit, in bytes * @return A resized/recompressed version of this image, in JPEG format */ public static byte[] getResizedImageData(int width, int height, int widthLimit, int heightLimit, int byteLimit, Uri uri, Context context) { int outWidth = width; int outHeight = height; float scaleFactor = 1.F; while ((outWidth * scaleFactor > widthLimit) || (outHeight * scaleFactor > heightLimit)) { scaleFactor *= .75F; } if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { Log.v(TAG, "getResizedBitmap: wlimit=" + widthLimit + ", hlimit=" + heightLimit + ", sizeLimit=" + byteLimit + ", width=" + width + ", height=" + height + ", initialScaleFactor=" + scaleFactor + ", uri=" + uri); } InputStream input = null; + ByteArrayOutputStream os = null; try { - ByteArrayOutputStream os = null; int attempts = 1; int sampleSize = 1; BitmapFactory.Options options = new BitmapFactory.Options(); int quality = MessageUtils.IMAGE_COMPRESSION_QUALITY; Bitmap b = null; // In this loop, attempt to decode the stream with the best possible subsampling (we // start with 1, which means no subsampling - get the original content) without running // out of memory. do { input = context.getContentResolver().openInputStream(uri); options.inSampleSize = sampleSize; try { b = BitmapFactory.decodeStream(input, null, options); if (b == null) { return null; // Couldn't decode and it wasn't because of an exception, // bail. } } catch (OutOfMemoryError e) { Log.w(TAG, "getResizedBitmap: img too large to decode (OutOfMemoryError), " + "may try with larger sampleSize. Curr sampleSize=" + sampleSize); sampleSize *= 2; // works best as a power of two attempts++; continue; } finally { if (input != null) { try { input.close(); } catch (IOException e) { Log.e(TAG, e.getMessage(), e); } } } } while (b == null && attempts < NUMBER_OF_RESIZE_ATTEMPTS); if (b == null) { if (Log.isLoggable(LogTag.APP, Log.VERBOSE) && attempts >= NUMBER_OF_RESIZE_ATTEMPTS) { Log.v(TAG, "getResizedImageData: gave up after too many attempts to resize"); } return null; } boolean resultTooBig = true; attempts = 1; // reset count for second loop // In this loop, we attempt to compress/resize the content to fit the given dimension // and file-size limits. do { try { if (options.outWidth > widthLimit || options.outHeight > heightLimit || (os != null && os.size() > byteLimit)) { // The decoder does not support the inSampleSize option. // Scale the bitmap using Bitmap library. int scaledWidth = (int)(outWidth * scaleFactor); int scaledHeight = (int)(outHeight * scaleFactor); if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { Log.v(TAG, "getResizedImageData: retry scaling using " + "Bitmap.createScaledBitmap: w=" + scaledWidth + ", h=" + scaledHeight); } b = Bitmap.createScaledBitmap(b, scaledWidth, scaledHeight, false); if (b == null) { if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { Log.v(TAG, "Bitmap.createScaledBitmap returned NULL!"); } return null; } } // Compress the image into a JPG. Start with MessageUtils.IMAGE_COMPRESSION_QUALITY. // In case that the image byte size is still too large reduce the quality in // proportion to the desired byte size. + if (os != null) { + try { + os.close(); + } catch (IOException e) { + Log.e(TAG, e.getMessage(), e); + } + } os = new ByteArrayOutputStream(); b.compress(CompressFormat.JPEG, quality, os); int jpgFileSize = os.size(); if (jpgFileSize > byteLimit) { quality = (quality * byteLimit) / jpgFileSize; // watch for int division! if (quality < MessageUtils.MINIMUM_IMAGE_COMPRESSION_QUALITY) { quality = MessageUtils.MINIMUM_IMAGE_COMPRESSION_QUALITY; } if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { Log.v(TAG, "getResizedImageData: compress(2) w/ quality=" + quality); } + if (os != null) { + try { + os.close(); + } catch (IOException e) { + Log.e(TAG, e.getMessage(), e); + } + } os = new ByteArrayOutputStream(); b.compress(CompressFormat.JPEG, quality, os); } } catch (java.lang.OutOfMemoryError e) { Log.w(TAG, "getResizedImageData - image too big (OutOfMemoryError), will try " + " with smaller scale factor, cur scale factor: " + scaleFactor); // fall through and keep trying with a smaller scale factor. } if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { Log.v(TAG, "attempt=" + attempts + " size=" + (os == null ? 0 : os.size()) + " width=" + outWidth * scaleFactor + " height=" + outHeight * scaleFactor + " scaleFactor=" + scaleFactor + " quality=" + quality); } scaleFactor *= .75F; attempts++; resultTooBig = os == null || os.size() > byteLimit; } while (resultTooBig && attempts < NUMBER_OF_RESIZE_ATTEMPTS); b.recycle(); // done with the bitmap, release the memory if (Log.isLoggable(LogTag.APP, Log.VERBOSE) && resultTooBig) { Log.v(TAG, "getResizedImageData returning NULL because the result is too big: " + " requested max: " + byteLimit + " actual: " + os.size()); } return resultTooBig ? null : os.toByteArray(); } catch (FileNotFoundException e) { Log.e(TAG, e.getMessage(), e); return null; } catch (java.lang.OutOfMemoryError e) { Log.e(TAG, e.getMessage(), e); return null; + } finally { + if (input != null) { + try { + input.close(); + } catch (IOException e) { + Log.e(TAG, e.getMessage(), e); + } + } + if (os != null) { + try { + os.close(); + } catch (IOException e) { + Log.e(TAG, e.getMessage(), e); + } + } } } }
false
true
public static byte[] getResizedImageData(int width, int height, int widthLimit, int heightLimit, int byteLimit, Uri uri, Context context) { int outWidth = width; int outHeight = height; float scaleFactor = 1.F; while ((outWidth * scaleFactor > widthLimit) || (outHeight * scaleFactor > heightLimit)) { scaleFactor *= .75F; } if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { Log.v(TAG, "getResizedBitmap: wlimit=" + widthLimit + ", hlimit=" + heightLimit + ", sizeLimit=" + byteLimit + ", width=" + width + ", height=" + height + ", initialScaleFactor=" + scaleFactor + ", uri=" + uri); } InputStream input = null; try { ByteArrayOutputStream os = null; int attempts = 1; int sampleSize = 1; BitmapFactory.Options options = new BitmapFactory.Options(); int quality = MessageUtils.IMAGE_COMPRESSION_QUALITY; Bitmap b = null; // In this loop, attempt to decode the stream with the best possible subsampling (we // start with 1, which means no subsampling - get the original content) without running // out of memory. do { input = context.getContentResolver().openInputStream(uri); options.inSampleSize = sampleSize; try { b = BitmapFactory.decodeStream(input, null, options); if (b == null) { return null; // Couldn't decode and it wasn't because of an exception, // bail. } } catch (OutOfMemoryError e) { Log.w(TAG, "getResizedBitmap: img too large to decode (OutOfMemoryError), " + "may try with larger sampleSize. Curr sampleSize=" + sampleSize); sampleSize *= 2; // works best as a power of two attempts++; continue; } finally { if (input != null) { try { input.close(); } catch (IOException e) { Log.e(TAG, e.getMessage(), e); } } } } while (b == null && attempts < NUMBER_OF_RESIZE_ATTEMPTS); if (b == null) { if (Log.isLoggable(LogTag.APP, Log.VERBOSE) && attempts >= NUMBER_OF_RESIZE_ATTEMPTS) { Log.v(TAG, "getResizedImageData: gave up after too many attempts to resize"); } return null; } boolean resultTooBig = true; attempts = 1; // reset count for second loop // In this loop, we attempt to compress/resize the content to fit the given dimension // and file-size limits. do { try { if (options.outWidth > widthLimit || options.outHeight > heightLimit || (os != null && os.size() > byteLimit)) { // The decoder does not support the inSampleSize option. // Scale the bitmap using Bitmap library. int scaledWidth = (int)(outWidth * scaleFactor); int scaledHeight = (int)(outHeight * scaleFactor); if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { Log.v(TAG, "getResizedImageData: retry scaling using " + "Bitmap.createScaledBitmap: w=" + scaledWidth + ", h=" + scaledHeight); } b = Bitmap.createScaledBitmap(b, scaledWidth, scaledHeight, false); if (b == null) { if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { Log.v(TAG, "Bitmap.createScaledBitmap returned NULL!"); } return null; } } // Compress the image into a JPG. Start with MessageUtils.IMAGE_COMPRESSION_QUALITY. // In case that the image byte size is still too large reduce the quality in // proportion to the desired byte size. os = new ByteArrayOutputStream(); b.compress(CompressFormat.JPEG, quality, os); int jpgFileSize = os.size(); if (jpgFileSize > byteLimit) { quality = (quality * byteLimit) / jpgFileSize; // watch for int division! if (quality < MessageUtils.MINIMUM_IMAGE_COMPRESSION_QUALITY) { quality = MessageUtils.MINIMUM_IMAGE_COMPRESSION_QUALITY; } if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { Log.v(TAG, "getResizedImageData: compress(2) w/ quality=" + quality); } os = new ByteArrayOutputStream(); b.compress(CompressFormat.JPEG, quality, os); } } catch (java.lang.OutOfMemoryError e) { Log.w(TAG, "getResizedImageData - image too big (OutOfMemoryError), will try " + " with smaller scale factor, cur scale factor: " + scaleFactor); // fall through and keep trying with a smaller scale factor. } if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { Log.v(TAG, "attempt=" + attempts + " size=" + (os == null ? 0 : os.size()) + " width=" + outWidth * scaleFactor + " height=" + outHeight * scaleFactor + " scaleFactor=" + scaleFactor + " quality=" + quality); } scaleFactor *= .75F; attempts++; resultTooBig = os == null || os.size() > byteLimit; } while (resultTooBig && attempts < NUMBER_OF_RESIZE_ATTEMPTS); b.recycle(); // done with the bitmap, release the memory if (Log.isLoggable(LogTag.APP, Log.VERBOSE) && resultTooBig) { Log.v(TAG, "getResizedImageData returning NULL because the result is too big: " + " requested max: " + byteLimit + " actual: " + os.size()); } return resultTooBig ? null : os.toByteArray(); } catch (FileNotFoundException e) { Log.e(TAG, e.getMessage(), e); return null; } catch (java.lang.OutOfMemoryError e) { Log.e(TAG, e.getMessage(), e); return null; } }
public static byte[] getResizedImageData(int width, int height, int widthLimit, int heightLimit, int byteLimit, Uri uri, Context context) { int outWidth = width; int outHeight = height; float scaleFactor = 1.F; while ((outWidth * scaleFactor > widthLimit) || (outHeight * scaleFactor > heightLimit)) { scaleFactor *= .75F; } if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { Log.v(TAG, "getResizedBitmap: wlimit=" + widthLimit + ", hlimit=" + heightLimit + ", sizeLimit=" + byteLimit + ", width=" + width + ", height=" + height + ", initialScaleFactor=" + scaleFactor + ", uri=" + uri); } InputStream input = null; ByteArrayOutputStream os = null; try { int attempts = 1; int sampleSize = 1; BitmapFactory.Options options = new BitmapFactory.Options(); int quality = MessageUtils.IMAGE_COMPRESSION_QUALITY; Bitmap b = null; // In this loop, attempt to decode the stream with the best possible subsampling (we // start with 1, which means no subsampling - get the original content) without running // out of memory. do { input = context.getContentResolver().openInputStream(uri); options.inSampleSize = sampleSize; try { b = BitmapFactory.decodeStream(input, null, options); if (b == null) { return null; // Couldn't decode and it wasn't because of an exception, // bail. } } catch (OutOfMemoryError e) { Log.w(TAG, "getResizedBitmap: img too large to decode (OutOfMemoryError), " + "may try with larger sampleSize. Curr sampleSize=" + sampleSize); sampleSize *= 2; // works best as a power of two attempts++; continue; } finally { if (input != null) { try { input.close(); } catch (IOException e) { Log.e(TAG, e.getMessage(), e); } } } } while (b == null && attempts < NUMBER_OF_RESIZE_ATTEMPTS); if (b == null) { if (Log.isLoggable(LogTag.APP, Log.VERBOSE) && attempts >= NUMBER_OF_RESIZE_ATTEMPTS) { Log.v(TAG, "getResizedImageData: gave up after too many attempts to resize"); } return null; } boolean resultTooBig = true; attempts = 1; // reset count for second loop // In this loop, we attempt to compress/resize the content to fit the given dimension // and file-size limits. do { try { if (options.outWidth > widthLimit || options.outHeight > heightLimit || (os != null && os.size() > byteLimit)) { // The decoder does not support the inSampleSize option. // Scale the bitmap using Bitmap library. int scaledWidth = (int)(outWidth * scaleFactor); int scaledHeight = (int)(outHeight * scaleFactor); if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { Log.v(TAG, "getResizedImageData: retry scaling using " + "Bitmap.createScaledBitmap: w=" + scaledWidth + ", h=" + scaledHeight); } b = Bitmap.createScaledBitmap(b, scaledWidth, scaledHeight, false); if (b == null) { if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { Log.v(TAG, "Bitmap.createScaledBitmap returned NULL!"); } return null; } } // Compress the image into a JPG. Start with MessageUtils.IMAGE_COMPRESSION_QUALITY. // In case that the image byte size is still too large reduce the quality in // proportion to the desired byte size. if (os != null) { try { os.close(); } catch (IOException e) { Log.e(TAG, e.getMessage(), e); } } os = new ByteArrayOutputStream(); b.compress(CompressFormat.JPEG, quality, os); int jpgFileSize = os.size(); if (jpgFileSize > byteLimit) { quality = (quality * byteLimit) / jpgFileSize; // watch for int division! if (quality < MessageUtils.MINIMUM_IMAGE_COMPRESSION_QUALITY) { quality = MessageUtils.MINIMUM_IMAGE_COMPRESSION_QUALITY; } if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { Log.v(TAG, "getResizedImageData: compress(2) w/ quality=" + quality); } if (os != null) { try { os.close(); } catch (IOException e) { Log.e(TAG, e.getMessage(), e); } } os = new ByteArrayOutputStream(); b.compress(CompressFormat.JPEG, quality, os); } } catch (java.lang.OutOfMemoryError e) { Log.w(TAG, "getResizedImageData - image too big (OutOfMemoryError), will try " + " with smaller scale factor, cur scale factor: " + scaleFactor); // fall through and keep trying with a smaller scale factor. } if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { Log.v(TAG, "attempt=" + attempts + " size=" + (os == null ? 0 : os.size()) + " width=" + outWidth * scaleFactor + " height=" + outHeight * scaleFactor + " scaleFactor=" + scaleFactor + " quality=" + quality); } scaleFactor *= .75F; attempts++; resultTooBig = os == null || os.size() > byteLimit; } while (resultTooBig && attempts < NUMBER_OF_RESIZE_ATTEMPTS); b.recycle(); // done with the bitmap, release the memory if (Log.isLoggable(LogTag.APP, Log.VERBOSE) && resultTooBig) { Log.v(TAG, "getResizedImageData returning NULL because the result is too big: " + " requested max: " + byteLimit + " actual: " + os.size()); } return resultTooBig ? null : os.toByteArray(); } catch (FileNotFoundException e) { Log.e(TAG, e.getMessage(), e); return null; } catch (java.lang.OutOfMemoryError e) { Log.e(TAG, e.getMessage(), e); return null; } finally { if (input != null) { try { input.close(); } catch (IOException e) { Log.e(TAG, e.getMessage(), e); } } if (os != null) { try { os.close(); } catch (IOException e) { Log.e(TAG, e.getMessage(), e); } } } }
diff --git a/applet/src/DynVizGraph.java b/applet/src/DynVizGraph.java index 384fcd7..a5b6d13 100644 --- a/applet/src/DynVizGraph.java +++ b/applet/src/DynVizGraph.java @@ -1,449 +1,449 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ import javax.swing.JApplet; import javax.swing.JPanel; import javax.swing.border.LineBorder; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Container; import java.awt.GridLayout; import java.awt.Graphics2D; import java.awt.image.BufferedImage; /** * * @author gmcwhirt */ public class DynVizGraph extends JApplet { private int chartWidth = 210; // The width of the canvas panel private int chartHeight = 210; // The height of the canvas panel private CanvasPanel BRChart; // JPanel canvas for graphics drawing private CanvasPanel DtRChart; private CanvasPanel CtRChart; private int payoffA; private int payoffB; private int payoffC; private int payoffD; @Override public void init(){ Container c = getContentPane(); setPreferredSize(new Dimension(chartWidth * 3 + 2, chartHeight)); c.setPreferredSize(new Dimension(chartWidth * 3 + 2, chartHeight)); JPanel panel = new JPanel(new GridLayout(1,3)); BRChart = new CanvasPanel(); DtRChart = new CanvasPanel(); CtRChart = new CanvasPanel(); panel.setBorder(new LineBorder(Color.LIGHT_GRAY)); panel.setPreferredSize(new Dimension(chartWidth * 3 + 2, chartHeight)); BRChart.setPreferredSize(new Dimension(chartWidth, chartHeight)); DtRChart.setPreferredSize(new Dimension(chartWidth, chartHeight)); CtRChart.setPreferredSize(new Dimension(chartWidth, chartHeight)); panel.add(BRChart); panel.add(DtRChart); panel.add(CtRChart); c.add(panel); try { String pAS = getParameter("A"); payoffA = Integer.parseInt(pAS); } catch (NumberFormatException e) { payoffA = 0; } catch (NullPointerException e) { payoffA = 0; } try { String pBS = getParameter("B"); payoffB = Integer.parseInt(pBS); } catch (NumberFormatException e) { payoffB = 0; } catch (NullPointerException e) { payoffB = 0; } try { String pCS = getParameter("C"); payoffC = Integer.parseInt(pCS); } catch (NumberFormatException e) { payoffC = 0; } catch (NullPointerException e) { payoffC = 0; } try { String pDS = getParameter("D"); payoffD = Integer.parseInt(pDS); } catch (NumberFormatException e) { payoffD = 0; } catch (NullPointerException e) { payoffD = 0; } Thread BRGen = new Thread(new BRGraphGenerator(payoffA, payoffB, payoffC, payoffD)); BRGen.start(); } private void BRGraphInfo(Line[] lines, Line[] arrows){ //BRChart BRChart.setLines(lines); BRChart.setArrows(arrows); } private void DtRGraphInfo(BufferedImage bi){ } private void CtRGraphInfo(BufferedImage bi){ } class Line { private int[] coords; private Color color; private Color color2; public Line(int c1, int c2, int c3, int c4, Color c, Color cp){ coords = new int[4]; coords[0] = c1; coords[1] = c2; coords[2] = c3; coords[3] = c4; color = c; color2 = cp; } public Line(int c1, int c2, int c3, int c4, Color c){ coords = new int[4]; coords[0] = c1; coords[1] = c2; coords[2] = c3; coords[3] = c4; color = c; color2 = Color.BLACK; } public Line(int c1, int c2, int c3, int c4){ coords = new int[4]; coords[0] = c1; coords[1] = c2; coords[2] = c3; coords[3] = c4; color = Color.BLACK; color2 = Color.BLACK; } public Color getColor(){ return color; } public Color getColor2(){ return color2; } public int[] getCoords(){ return coords; } @Override public String toString(){ return coords.toString(); } } class BRGraphGenerator implements Runnable { private int A, B, C, D; public BRGraphGenerator(int Ap, int Bp, int Cp, int Dp){ A = Ap; B = Bp; C = Cp; D = Dp; } @Override public void run(){ Line[] lines; Line[] arrows; //draw stuff float qlimf = (float)C / (float)(A + C); int qlim = (int) Math.floor(200f * (1f - qlimf)); lines = new Line[106]; int index = 0; int index2 = 0; float brlimx; float brlimy; int lrespx; int lrespy; if (A + C > 0){ lrespx = 0; if (qlimf <= 1f && qlimf >= 0f){ lines[index++] = new Line(200, qlim, 200, 0, Color.RED); lines[index++] = new Line(0, qlim, 0, 200, Color.RED); lines[index++] = new Line(0, qlim, 200, qlim, Color.RED); brlimy = qlimf; } else if (qlimf > 1f) { //always play the other lines[index++] = new Line(0, 0, 0, 200, Color.RED); brlimy = 1f; } else { //always play this lines[index++] = new Line(200, 0, 200, 200, Color.RED); brlimy = 0f; } } else if (A + C < 0){ lrespx = 200; if (qlimf <= 1f && qlimf >= 0f){ lines[index++] = new Line(200, qlim, 200, 200, Color.RED); lines[index++] = new Line(0, qlim, 0, 0, Color.RED); lines[index++] = new Line(0, qlim, 200, qlim, Color.RED); brlimy = qlimf; } else if (qlimf > 1f) { //always play this lines[index++] = new Line(200, 0, 200, 200, Color.RED); brlimy = 0f; } else { //always play the other lines[index++] = new Line(0, 0, 0, 200, Color.RED); brlimy = 1f; } } else if (0 >= C) { //play this lines[index++] = new Line(200, 0, 200, 200, Color.RED); lrespx = 0; brlimy = 0f; } else { //play other lines[index++] = new Line(0, 0, 0, 200, Color.RED); lrespx = 0; brlimy = 1f; } float plimf = (float)D / (float)(B + D); int plim = (int) Math.floor(200f * (1 - plimf)); if (B + D > 0){ lrespy = 200; if (plimf >= 0f && plimf <= 1f){ lines[index++] = new Line(plim, 200, 0, 200, Color.BLUE); lines[index++] = new Line(plim, 0, 200, 0, Color.BLUE); lines[index++] = new Line(plim, 0, plim, 200, Color.BLUE); brlimx = plimf; } else if (plimf > 1f){ //play the other lines[index++] = new Line(0, 200, 200, 0, Color.BLUE); brlimx = 1f; } else { //play this lines[index++] = new Line(0, 200, 200, 200, Color.BLUE); brlimx = 0f; } } else if (B + D < 0){ lrespy = 0; if (plimf >= 0f && plimf <= 1f){ lines[index++] = new Line(plim, 200, 200, 200, Color.BLUE); lines[index++] = new Line(plim, 0, 0, 0, Color.BLUE); lines[index++] = new Line(plim, 0, plim, 200, Color.BLUE); brlimx = plimf; } else if (plimf > 1f) { //play this lines[index++] = new Line(0, 200, 200, 200, Color.BLUE); brlimx = 0f; } else { //play the other lines[index++] = new Line(0, 200, 200, 0, Color.BLUE); brlimx = 1f; } } else if (0 >= D) { //play this lines[index++] = new Line(0, 0, 200, 0, Color.BLUE); lrespy = 200; brlimx = 0f; } else { //play other lines[index++] = new Line(0, 200, 200, 200, Color.BLUE); lrespy = 200; brlimx = 1f; } - arrows = new Line[100]; + arrows = new Line[121]; float step = 0.1f; int fmx; int fmy; int tox; int toy; - for (float i = 0f; i < 1f; i += step){ - for (float j = 0f; j < 1f; j += step){ + for (float i = 0f; i <= 1f; i += step){ + for (float j = 0f; j <= 1f; j += step){ //response at (i, j) fmx = (int) Math.floor( 200 * (1f - i) ); fmy = (int) Math.floor( 200 * (1f - j) ); if (j < brlimy){ tox = lrespx; } else if (j > brlimy) { tox = Math.abs(lrespx - 200); } else { tox = fmx; } if (i < brlimx){ toy = lrespy; } else if (i > brlimx) { toy = Math.abs(lrespy - 200); } else { toy = fmy; } arrows[index2++] = new Line(fmx, fmy, tox, toy, Color.GREEN, Color.BLACK); lines[index++] = new Line(fmx, fmy, fmx, fmy, Color.BLACK); } } BRGraphInfo(lines, arrows); } } // Class to provide a drawing surface for graphics display class CanvasPanel extends JPanel { static final int BR = 1; static final int DtR = 2; static final int CtR = 3; private Line[] _lines; private Line[] _arrows; private int _typ; // Constructor public CanvasPanel(){ setBackground(Color.white); setPreferredSize( new Dimension( chartWidth, chartHeight ) ); // Set its size setVisible( true ); // Make the window visible } public void setLines(Line[] lines){ _lines = lines; } public void setArrows(Line[] arrows){ _arrows = arrows; } @Override public void paintComponent ( Graphics g ){ super.paintComponent( g ); Graphics2D g2d = (Graphics2D) g; g2d.setColor(Color.LIGHT_GRAY); g2d.drawRect(5, 5, 200, 200); Color color; Color color2; int[] coords; if (_arrows != null && _arrows.length > 0) { for (int i = 0; i < _arrows.length; i++){ if (_arrows[i] != null){ coords = _arrows[i].getCoords(); color = _arrows[i].getColor(); color2 = _arrows[i].getColor2(); drawArrow(g2d, coords[0] + 5, coords[1] + 5, coords[2] + 5, coords[3] + 5, color, color2); } } } if (_lines != null && _lines.length > 0) { System.out.println("We have lines!"); for (int i = 0; i < _lines.length; i++){ if (_lines[i] != null){ coords = _lines[i].getCoords(); color = _lines[i].getColor(); g2d.setColor(color); g2d.drawLine(coords[0] + 5, coords[1] + 5, coords[2] + 5, coords[3] + 5); } } } } /** * Draws an arrow on the given Graphics2D context * @param g The Graphics2D context to draw on * @param x The x location of the "tail" of the arrow * @param y The y location of the "tail" of the arrow * @param xx The x location of the "head" of the arrow * @param yy The y location of the "head" of the arrow */ private void drawArrow( Graphics2D g, int x, int y, int xx, int yy, Color lcolor, Color acolor ) { float arrowWidth = 5.0f ; float theta = 0.423f ; int[] xPoints = new int[ 3 ] ; int[] yPoints = new int[ 3 ] ; float[] vecLine = new float[ 2 ] ; float[] vecLeft = new float[ 2 ] ; float fLength; float th; float ta; float baseX, baseY ; xPoints[ 0 ] = xx ; yPoints[ 0 ] = yy ; // build the line vector vecLine[ 0 ] = (float)xPoints[ 0 ] - x ; vecLine[ 1 ] = (float)yPoints[ 0 ] - y ; // build the arrow base vector - normal to the line vecLeft[ 0 ] = -vecLine[ 1 ] ; vecLeft[ 1 ] = vecLine[ 0 ] ; // setup length parameters fLength = (float)Math.sqrt( vecLine[0] * vecLine[0] + vecLine[1] * vecLine[1] ) ; if (fLength > 0f){ th = arrowWidth / ( 2.0f * fLength ) ; ta = arrowWidth / ( 2.0f * ( (float)Math.tan( theta ) / 2.0f ) * fLength ) ; } else { th = 0f; ta = 0f; } // find the base of the arrow baseX = ( (float)xPoints[ 0 ] - ta * vecLine[0]); baseY = ( (float)yPoints[ 0 ] - ta * vecLine[1]); // build the points on the sides of the arrow xPoints[ 1 ] = (int)( baseX + th * vecLeft[0] ); yPoints[ 1 ] = (int)( baseY + th * vecLeft[1] ); xPoints[ 2 ] = (int)( baseX - th * vecLeft[0] ); yPoints[ 2 ] = (int)( baseY - th * vecLeft[1] ); g.setColor(lcolor); g.drawLine( x, y, (int)baseX, (int)baseY ) ; g.setColor(acolor); g.fillPolygon( xPoints, yPoints, 3 ) ; } } // End canvasPanel class }
false
true
public void run(){ Line[] lines; Line[] arrows; //draw stuff float qlimf = (float)C / (float)(A + C); int qlim = (int) Math.floor(200f * (1f - qlimf)); lines = new Line[106]; int index = 0; int index2 = 0; float brlimx; float brlimy; int lrespx; int lrespy; if (A + C > 0){ lrespx = 0; if (qlimf <= 1f && qlimf >= 0f){ lines[index++] = new Line(200, qlim, 200, 0, Color.RED); lines[index++] = new Line(0, qlim, 0, 200, Color.RED); lines[index++] = new Line(0, qlim, 200, qlim, Color.RED); brlimy = qlimf; } else if (qlimf > 1f) { //always play the other lines[index++] = new Line(0, 0, 0, 200, Color.RED); brlimy = 1f; } else { //always play this lines[index++] = new Line(200, 0, 200, 200, Color.RED); brlimy = 0f; } } else if (A + C < 0){ lrespx = 200; if (qlimf <= 1f && qlimf >= 0f){ lines[index++] = new Line(200, qlim, 200, 200, Color.RED); lines[index++] = new Line(0, qlim, 0, 0, Color.RED); lines[index++] = new Line(0, qlim, 200, qlim, Color.RED); brlimy = qlimf; } else if (qlimf > 1f) { //always play this lines[index++] = new Line(200, 0, 200, 200, Color.RED); brlimy = 0f; } else { //always play the other lines[index++] = new Line(0, 0, 0, 200, Color.RED); brlimy = 1f; } } else if (0 >= C) { //play this lines[index++] = new Line(200, 0, 200, 200, Color.RED); lrespx = 0; brlimy = 0f; } else { //play other lines[index++] = new Line(0, 0, 0, 200, Color.RED); lrespx = 0; brlimy = 1f; } float plimf = (float)D / (float)(B + D); int plim = (int) Math.floor(200f * (1 - plimf)); if (B + D > 0){ lrespy = 200; if (plimf >= 0f && plimf <= 1f){ lines[index++] = new Line(plim, 200, 0, 200, Color.BLUE); lines[index++] = new Line(plim, 0, 200, 0, Color.BLUE); lines[index++] = new Line(plim, 0, plim, 200, Color.BLUE); brlimx = plimf; } else if (plimf > 1f){ //play the other lines[index++] = new Line(0, 200, 200, 0, Color.BLUE); brlimx = 1f; } else { //play this lines[index++] = new Line(0, 200, 200, 200, Color.BLUE); brlimx = 0f; } } else if (B + D < 0){ lrespy = 0; if (plimf >= 0f && plimf <= 1f){ lines[index++] = new Line(plim, 200, 200, 200, Color.BLUE); lines[index++] = new Line(plim, 0, 0, 0, Color.BLUE); lines[index++] = new Line(plim, 0, plim, 200, Color.BLUE); brlimx = plimf; } else if (plimf > 1f) { //play this lines[index++] = new Line(0, 200, 200, 200, Color.BLUE); brlimx = 0f; } else { //play the other lines[index++] = new Line(0, 200, 200, 0, Color.BLUE); brlimx = 1f; } } else if (0 >= D) { //play this lines[index++] = new Line(0, 0, 200, 0, Color.BLUE); lrespy = 200; brlimx = 0f; } else { //play other lines[index++] = new Line(0, 200, 200, 200, Color.BLUE); lrespy = 200; brlimx = 1f; } arrows = new Line[100]; float step = 0.1f; int fmx; int fmy; int tox; int toy; for (float i = 0f; i < 1f; i += step){ for (float j = 0f; j < 1f; j += step){ //response at (i, j) fmx = (int) Math.floor( 200 * (1f - i) ); fmy = (int) Math.floor( 200 * (1f - j) ); if (j < brlimy){ tox = lrespx; } else if (j > brlimy) { tox = Math.abs(lrespx - 200); } else { tox = fmx; } if (i < brlimx){ toy = lrespy; } else if (i > brlimx) { toy = Math.abs(lrespy - 200); } else { toy = fmy; } arrows[index2++] = new Line(fmx, fmy, tox, toy, Color.GREEN, Color.BLACK); lines[index++] = new Line(fmx, fmy, fmx, fmy, Color.BLACK); } } BRGraphInfo(lines, arrows); }
public void run(){ Line[] lines; Line[] arrows; //draw stuff float qlimf = (float)C / (float)(A + C); int qlim = (int) Math.floor(200f * (1f - qlimf)); lines = new Line[106]; int index = 0; int index2 = 0; float brlimx; float brlimy; int lrespx; int lrespy; if (A + C > 0){ lrespx = 0; if (qlimf <= 1f && qlimf >= 0f){ lines[index++] = new Line(200, qlim, 200, 0, Color.RED); lines[index++] = new Line(0, qlim, 0, 200, Color.RED); lines[index++] = new Line(0, qlim, 200, qlim, Color.RED); brlimy = qlimf; } else if (qlimf > 1f) { //always play the other lines[index++] = new Line(0, 0, 0, 200, Color.RED); brlimy = 1f; } else { //always play this lines[index++] = new Line(200, 0, 200, 200, Color.RED); brlimy = 0f; } } else if (A + C < 0){ lrespx = 200; if (qlimf <= 1f && qlimf >= 0f){ lines[index++] = new Line(200, qlim, 200, 200, Color.RED); lines[index++] = new Line(0, qlim, 0, 0, Color.RED); lines[index++] = new Line(0, qlim, 200, qlim, Color.RED); brlimy = qlimf; } else if (qlimf > 1f) { //always play this lines[index++] = new Line(200, 0, 200, 200, Color.RED); brlimy = 0f; } else { //always play the other lines[index++] = new Line(0, 0, 0, 200, Color.RED); brlimy = 1f; } } else if (0 >= C) { //play this lines[index++] = new Line(200, 0, 200, 200, Color.RED); lrespx = 0; brlimy = 0f; } else { //play other lines[index++] = new Line(0, 0, 0, 200, Color.RED); lrespx = 0; brlimy = 1f; } float plimf = (float)D / (float)(B + D); int plim = (int) Math.floor(200f * (1 - plimf)); if (B + D > 0){ lrespy = 200; if (plimf >= 0f && plimf <= 1f){ lines[index++] = new Line(plim, 200, 0, 200, Color.BLUE); lines[index++] = new Line(plim, 0, 200, 0, Color.BLUE); lines[index++] = new Line(plim, 0, plim, 200, Color.BLUE); brlimx = plimf; } else if (plimf > 1f){ //play the other lines[index++] = new Line(0, 200, 200, 0, Color.BLUE); brlimx = 1f; } else { //play this lines[index++] = new Line(0, 200, 200, 200, Color.BLUE); brlimx = 0f; } } else if (B + D < 0){ lrespy = 0; if (plimf >= 0f && plimf <= 1f){ lines[index++] = new Line(plim, 200, 200, 200, Color.BLUE); lines[index++] = new Line(plim, 0, 0, 0, Color.BLUE); lines[index++] = new Line(plim, 0, plim, 200, Color.BLUE); brlimx = plimf; } else if (plimf > 1f) { //play this lines[index++] = new Line(0, 200, 200, 200, Color.BLUE); brlimx = 0f; } else { //play the other lines[index++] = new Line(0, 200, 200, 0, Color.BLUE); brlimx = 1f; } } else if (0 >= D) { //play this lines[index++] = new Line(0, 0, 200, 0, Color.BLUE); lrespy = 200; brlimx = 0f; } else { //play other lines[index++] = new Line(0, 200, 200, 200, Color.BLUE); lrespy = 200; brlimx = 1f; } arrows = new Line[121]; float step = 0.1f; int fmx; int fmy; int tox; int toy; for (float i = 0f; i <= 1f; i += step){ for (float j = 0f; j <= 1f; j += step){ //response at (i, j) fmx = (int) Math.floor( 200 * (1f - i) ); fmy = (int) Math.floor( 200 * (1f - j) ); if (j < brlimy){ tox = lrespx; } else if (j > brlimy) { tox = Math.abs(lrespx - 200); } else { tox = fmx; } if (i < brlimx){ toy = lrespy; } else if (i > brlimx) { toy = Math.abs(lrespy - 200); } else { toy = fmy; } arrows[index2++] = new Line(fmx, fmy, tox, toy, Color.GREEN, Color.BLACK); lines[index++] = new Line(fmx, fmy, fmx, fmy, Color.BLACK); } } BRGraphInfo(lines, arrows); }
diff --git a/src/java/com/android/internal/telephony/OperatorInfo.java b/src/java/com/android/internal/telephony/OperatorInfo.java index 0718bf85..b9f938ea 100644 --- a/src/java/com/android/internal/telephony/OperatorInfo.java +++ b/src/java/com/android/internal/telephony/OperatorInfo.java @@ -1,170 +1,170 @@ /* * Copyright (C) 2006 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.internal.telephony; import android.os.Parcel; import android.os.Parcelable; /** * {@hide} */ public class OperatorInfo implements Parcelable { public enum State { UNKNOWN, AVAILABLE, CURRENT, FORBIDDEN; } private String mOperatorAlphaLong; private String mOperatorAlphaShort; private String mOperatorNumeric; private State mState = State.UNKNOWN; private String mRadioTech = ""; public String getOperatorAlphaLong() { return mOperatorAlphaLong; } public String getOperatorAlphaShort() { return mOperatorAlphaShort; } public String getOperatorNumeric() { return mOperatorNumeric; } public State getState() { return mState; } public String getRadioTech() { return mRadioTech; } OperatorInfo(String operatorAlphaLong, String operatorAlphaShort, String operatorNumeric, State state) { mOperatorAlphaLong = operatorAlphaLong; mOperatorAlphaShort = operatorAlphaShort; - mOperatorNumeric = null; + mOperatorNumeric = operatorNumeric; mRadioTech = ""; /* operatorNumeric format: PLMN+RAT or PLMN */ if (null != operatorNumeric) { - String values[] = operatorNumeric.split("+"); + String values[] = operatorNumeric.split("\\+"); mOperatorNumeric = values[0]; if (values.length > 1) mRadioTech = values[1]; } mState = state; } public OperatorInfo(String operatorAlphaLong, String operatorAlphaShort, String operatorNumeric, String stateString) { this (operatorAlphaLong, operatorAlphaShort, operatorNumeric, rilStateToState(stateString)); } /** * See state strings defined in ril.h RIL_REQUEST_QUERY_AVAILABLE_NETWORKS */ private static State rilStateToState(String s) { if (s.equals("unknown")) { return State.UNKNOWN; } else if (s.equals("available")) { return State.AVAILABLE; } else if (s.equals("current")) { return State.CURRENT; } else if (s.equals("forbidden")) { return State.FORBIDDEN; } else { throw new RuntimeException( "RIL impl error: Invalid network state '" + s + "'"); } } @Override public String toString() { return "OperatorInfo " + mOperatorAlphaLong + "/" + mOperatorAlphaShort + "/" + mOperatorNumeric + "/" + mState + "/" + mRadioTech; } /** * Parcelable interface implemented below. * This is a simple effort to make OperatorInfo parcelable rather than * trying to make the conventional containing object (AsyncResult), * implement parcelable. This functionality is needed for the * NetworkQueryService to fix 1128695. */ @Override public int describeContents() { return 0; } /** * Implement the Parcelable interface. * Method to serialize a OperatorInfo object. */ @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(mOperatorAlphaLong); dest.writeString(mOperatorAlphaShort); dest.writeString(mOperatorNumeric + "+" + mRadioTech); dest.writeSerializable(mState); } /** * Implement the Parcelable interface * Method to deserialize a OperatorInfo object, or an array thereof. */ public static final Creator<OperatorInfo> CREATOR = new Creator<OperatorInfo>() { @Override public OperatorInfo createFromParcel(Parcel in) { OperatorInfo opInfo = new OperatorInfo( in.readString(), /*operatorAlphaLong*/ in.readString(), /*operatorAlphaShort*/ in.readString(), /*operatorNumeric*/ (State) in.readSerializable()); /*state*/ return opInfo; } @Override public OperatorInfo[] newArray(int size) { return new OperatorInfo[size]; } }; }
false
true
OperatorInfo(String operatorAlphaLong, String operatorAlphaShort, String operatorNumeric, State state) { mOperatorAlphaLong = operatorAlphaLong; mOperatorAlphaShort = operatorAlphaShort; mOperatorNumeric = null; mRadioTech = ""; /* operatorNumeric format: PLMN+RAT or PLMN */ if (null != operatorNumeric) { String values[] = operatorNumeric.split("+"); mOperatorNumeric = values[0]; if (values.length > 1) mRadioTech = values[1]; } mState = state; }
OperatorInfo(String operatorAlphaLong, String operatorAlphaShort, String operatorNumeric, State state) { mOperatorAlphaLong = operatorAlphaLong; mOperatorAlphaShort = operatorAlphaShort; mOperatorNumeric = operatorNumeric; mRadioTech = ""; /* operatorNumeric format: PLMN+RAT or PLMN */ if (null != operatorNumeric) { String values[] = operatorNumeric.split("\\+"); mOperatorNumeric = values[0]; if (values.length > 1) mRadioTech = values[1]; } mState = state; }
diff --git a/src/main/java/com/dritanium/delegates/AbstractIntelligentDelegate.java b/src/main/java/com/dritanium/delegates/AbstractIntelligentDelegate.java index 8980cc5..1ef67f7 100644 --- a/src/main/java/com/dritanium/delegates/AbstractIntelligentDelegate.java +++ b/src/main/java/com/dritanium/delegates/AbstractIntelligentDelegate.java @@ -1,106 +1,106 @@ //Copyright 2012-2013 Joshua Scoggins. 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 Joshua Scoggins ``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 Joshua Scoggins 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 Joshua Scoggins. package com.dritanium.delegates; import java.util.ArrayList; /** * An abstract implementation of an IntelligentDelegate * @author Joshua Scoggins */ public abstract class AbstractIntelligentDelegate implements IntelligentDelegate { private Class[] args; public AbstractIntelligentDelegate(int size) { args = new Class[size]; } public AbstractIntelligentDelegate(Class[] arguments) { args = arguments; } public int getArgumentCount() { return args.length; } public boolean checkInput(Object[] input) { if(input.length != getArgumentCount()) { return false; } else { for(int i = 0; i < getArgumentCount(); i++) { - Class desiredType = args[i].getClass(); + Class desiredType = args[i]; if(!desiredType.isInstance(input[i])) { return false; } } return true; } } public Class getArgument(int index) { return args[index]; } public void registerArgument(int index, Class value) { args[index] = value; } public final Object invoke(Object[] input) { //do type checking here if(checkInput(input)) { return invokeImpl(input); //if we support return type checking then it is up //to the programmer to denote if it returns null or not. //I think that's really stupid so no returnType checking } else { throw new TypeCheckingException(); } } protected abstract Object invokeImpl(Object[] input); /** * A method used to get the input used by the run method * @return the input used by run() */ protected abstract Object[] getInput(); /** * A method used to set the input used by the run method * @param input The input used by run() */ public abstract void setInput(Object[] input); /** * Retrieves the result of the invoking the run method * @return the result of calling run */ public abstract Object getResult(); /** * Sets the result from invoking the run method * @param input The result of calling run() */ protected abstract void setResult(Object input); public void run() { setResult(invoke(getInput())); } }
true
true
public boolean checkInput(Object[] input) { if(input.length != getArgumentCount()) { return false; } else { for(int i = 0; i < getArgumentCount(); i++) { Class desiredType = args[i].getClass(); if(!desiredType.isInstance(input[i])) { return false; } } return true; } }
public boolean checkInput(Object[] input) { if(input.length != getArgumentCount()) { return false; } else { for(int i = 0; i < getArgumentCount(); i++) { Class desiredType = args[i]; if(!desiredType.isInstance(input[i])) { return false; } } return true; } }
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/common/jna/Natives.java b/modules/elasticsearch/src/main/java/org/elasticsearch/common/jna/Natives.java index 5150a030c7e..13438424e86 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/common/jna/Natives.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/common/jna/Natives.java @@ -1,55 +1,55 @@ /* * Licensed to Elastic Search and Shay Banon under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Elastic Search licenses this * file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.common.jna; import com.sun.jna.Native; import org.elasticsearch.common.logging.ESLogger; import org.elasticsearch.common.logging.Loggers; /** * @author kimchy (shay.banon) */ public class Natives { private static ESLogger logger = Loggers.getLogger(Natives.class); public static void tryMlockall() { int errno = Integer.MIN_VALUE; try { int result = CLibrary.mlockall(CLibrary.MCL_CURRENT); if (result != 0) errno = Native.getLastError(); } catch (UnsatisfiedLinkError e) { // this will have already been logged by CLibrary, no need to repeat it return; } if (errno != Integer.MIN_VALUE) { if (errno == CLibrary.ENOMEM && System.getProperty("os.name").toLowerCase().contains("linux")) { logger.debug("Unable to lock JVM memory (ENOMEM)." - + " This can result in part of the JVM being swapped out, especially with mmapped I/O enabled." - + " Increase RLIMIT_MEMLOCK or run Cassandra as root."); + + " This can result in part of the JVM being swapped out." + + " Increase RLIMIT_MEMLOCK or run elasticsearch as root."); } else if (!System.getProperty("os.name").toLowerCase().contains("mac")) { // OS X allows mlockall to be called, but always returns an error logger.debug("Unknown mlockall error " + errno); } } } }
true
true
public static void tryMlockall() { int errno = Integer.MIN_VALUE; try { int result = CLibrary.mlockall(CLibrary.MCL_CURRENT); if (result != 0) errno = Native.getLastError(); } catch (UnsatisfiedLinkError e) { // this will have already been logged by CLibrary, no need to repeat it return; } if (errno != Integer.MIN_VALUE) { if (errno == CLibrary.ENOMEM && System.getProperty("os.name").toLowerCase().contains("linux")) { logger.debug("Unable to lock JVM memory (ENOMEM)." + " This can result in part of the JVM being swapped out, especially with mmapped I/O enabled." + " Increase RLIMIT_MEMLOCK or run Cassandra as root."); } else if (!System.getProperty("os.name").toLowerCase().contains("mac")) { // OS X allows mlockall to be called, but always returns an error logger.debug("Unknown mlockall error " + errno); } } }
public static void tryMlockall() { int errno = Integer.MIN_VALUE; try { int result = CLibrary.mlockall(CLibrary.MCL_CURRENT); if (result != 0) errno = Native.getLastError(); } catch (UnsatisfiedLinkError e) { // this will have already been logged by CLibrary, no need to repeat it return; } if (errno != Integer.MIN_VALUE) { if (errno == CLibrary.ENOMEM && System.getProperty("os.name").toLowerCase().contains("linux")) { logger.debug("Unable to lock JVM memory (ENOMEM)." + " This can result in part of the JVM being swapped out." + " Increase RLIMIT_MEMLOCK or run elasticsearch as root."); } else if (!System.getProperty("os.name").toLowerCase().contains("mac")) { // OS X allows mlockall to be called, but always returns an error logger.debug("Unknown mlockall error " + errno); } } }
diff --git a/src/java/org/apache/fop/render/afp/AFPImageHandlerRenderedImage.java b/src/java/org/apache/fop/render/afp/AFPImageHandlerRenderedImage.java index 354dbef90..ed6fe52b5 100644 --- a/src/java/org/apache/fop/render/afp/AFPImageHandlerRenderedImage.java +++ b/src/java/org/apache/fop/render/afp/AFPImageHandlerRenderedImage.java @@ -1,219 +1,222 @@ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* $Id$ */ package org.apache.fop.render.afp; import java.awt.Rectangle; import java.awt.image.ColorModel; import java.awt.image.RenderedImage; import java.io.IOException; import org.apache.commons.io.output.ByteArrayOutputStream; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.xmlgraphics.image.loader.Image; import org.apache.xmlgraphics.image.loader.ImageFlavor; import org.apache.xmlgraphics.image.loader.impl.ImageRendered; import org.apache.xmlgraphics.ps.ImageEncodingHelper; import org.apache.xmlgraphics.util.MimeConstants; import org.apache.fop.afp.AFPDataObjectInfo; import org.apache.fop.afp.AFPImageObjectInfo; import org.apache.fop.afp.AFPObjectAreaInfo; import org.apache.fop.afp.AFPPaintingState; import org.apache.fop.render.ImageHandler; import org.apache.fop.render.RenderingContext; import org.apache.fop.util.BitmapImageUtil; /** * PDFImageHandler implementation which handles RenderedImage instances. */ public class AFPImageHandlerRenderedImage extends AFPImageHandler implements ImageHandler { /** logging instance */ private static Log log = LogFactory.getLog(AFPImageHandlerRenderedImage.class); private static final ImageFlavor[] FLAVORS = new ImageFlavor[] { ImageFlavor.BUFFERED_IMAGE, ImageFlavor.RENDERED_IMAGE }; /** {@inheritDoc} */ public AFPDataObjectInfo generateDataObjectInfo( AFPRendererImageInfo rendererImageInfo) throws IOException { AFPImageObjectInfo imageObjectInfo = (AFPImageObjectInfo)super.generateDataObjectInfo(rendererImageInfo); AFPRendererContext rendererContext = (AFPRendererContext)rendererImageInfo.getRendererContext(); AFPInfo afpInfo = rendererContext.getInfo(); AFPPaintingState paintingState = afpInfo.getPaintingState(); ImageRendered imageRendered = (ImageRendered) rendererImageInfo.img; updateDataObjectInfo(imageObjectInfo, paintingState, imageRendered); return imageObjectInfo; } private AFPDataObjectInfo updateDataObjectInfo(AFPImageObjectInfo imageObjectInfo, AFPPaintingState paintingState, ImageRendered imageRendered) throws IOException { int resolution = paintingState.getResolution(); imageObjectInfo.setMimeType(MimeConstants.MIME_AFP_IOCA_FS45); imageObjectInfo.setDataHeightRes(resolution); imageObjectInfo.setDataWidthRes(resolution); RenderedImage renderedImage = imageRendered.getRenderedImage(); int dataHeight = renderedImage.getHeight(); imageObjectInfo.setDataHeight(dataHeight); int dataWidth = renderedImage.getWidth(); imageObjectInfo.setDataWidth(dataWidth); //TODO To reduce AFP file size, investigate using a compression scheme. //Currently, all image data is uncompressed. int maxPixelSize = paintingState.getBitsPerPixel(); if (paintingState.isColorImages()) { maxPixelSize *= 3; //RGB only at the moment } ColorModel cm = renderedImage.getColorModel(); if (log.isTraceEnabled()) { log.trace("ColorModel: " + cm); } int pixelSize = cm.getPixelSize(); if (cm.hasAlpha()) { pixelSize -= 8; } //TODO Add support for CMYK images byte[] imageData = null; ByteArrayOutputStream baos = new ByteArrayOutputStream(); boolean allowDirectEncoding = true; if (allowDirectEncoding && pixelSize <= maxPixelSize) { //Attempt to encode without resampling the image ImageEncodingHelper helper = new ImageEncodingHelper(renderedImage); ColorModel encodedColorModel = helper.getEncodedColorModel(); boolean directEncode = true; if (helper.getEncodedColorModel().getPixelSize() > maxPixelSize) { directEncode = false; //pixel size needs to be reduced } if (BitmapImageUtil.getColorIndexSize(renderedImage) > 2) { directEncode = false; //Lookup tables are not implemented, yet } if (directEncode) { log.debug("Encoding image directly..."); imageObjectInfo.setBitsPerPixel(encodedColorModel.getPixelSize()); if (BitmapImageUtil.isMonochromeImage(renderedImage) && !BitmapImageUtil.isZeroBlack(renderedImage)) { log.trace("set subtractive mode"); imageObjectInfo.setSubtractive(true); } helper.encode(baos); imageData = baos.toByteArray(); } } if (imageData == null) { log.debug("Encoding image via RGB..."); //Convert image to 24bit RGB ImageEncodingHelper.encodeRenderedImageAsRGB(renderedImage, baos); imageData = baos.toByteArray(); boolean colorImages = paintingState.isColorImages(); imageObjectInfo.setColor(colorImages); // convert to grayscale if (!colorImages) { log.debug("Converting RGB image to grayscale..."); baos.reset(); int bitsPerPixel = paintingState.getBitsPerPixel(); imageObjectInfo.setBitsPerPixel(bitsPerPixel); //TODO this should be done off the RenderedImage to avoid buffering the //intermediate 24bit image ImageEncodingHelper.encodeRGBAsGrayScale( imageData, dataWidth, dataHeight, bitsPerPixel, baos); imageData = baos.toByteArray(); + if (bitsPerPixel == 1) { + imageObjectInfo.setSubtractive(true); + } } } imageObjectInfo.setData(imageData); // set object area info AFPObjectAreaInfo objectAreaInfo = imageObjectInfo.getObjectAreaInfo(); objectAreaInfo.setWidthRes(resolution); objectAreaInfo.setHeightRes(resolution); return imageObjectInfo; } /** {@inheritDoc} */ protected AFPDataObjectInfo createDataObjectInfo() { return new AFPImageObjectInfo(); } /** {@inheritDoc} */ public int getPriority() { return 300; } /** {@inheritDoc} */ public Class getSupportedImageClass() { return ImageRendered.class; } /** {@inheritDoc} */ public ImageFlavor[] getSupportedImageFlavors() { return FLAVORS; } /** {@inheritDoc} */ public void handleImage(RenderingContext context, Image image, Rectangle pos) throws IOException { AFPRenderingContext afpContext = (AFPRenderingContext)context; AFPImageObjectInfo imageObjectInfo = (AFPImageObjectInfo)createDataObjectInfo(); // set resource information setResourceInformation(imageObjectInfo, image.getInfo().getOriginalURI(), afpContext.getForeignAttributes()); // Positioning imageObjectInfo.setObjectAreaInfo(createObjectAreaInfo(afpContext.getPaintingState(), pos)); // Image content ImageRendered imageRend = (ImageRendered)image; updateDataObjectInfo(imageObjectInfo, afpContext.getPaintingState(), imageRend); // Create image afpContext.getResourceManager().createObject(imageObjectInfo); } /** {@inheritDoc} */ public boolean isCompatible(RenderingContext targetContext, Image image) { return (image == null || image instanceof ImageRendered) && targetContext instanceof AFPRenderingContext; } }
true
true
private AFPDataObjectInfo updateDataObjectInfo(AFPImageObjectInfo imageObjectInfo, AFPPaintingState paintingState, ImageRendered imageRendered) throws IOException { int resolution = paintingState.getResolution(); imageObjectInfo.setMimeType(MimeConstants.MIME_AFP_IOCA_FS45); imageObjectInfo.setDataHeightRes(resolution); imageObjectInfo.setDataWidthRes(resolution); RenderedImage renderedImage = imageRendered.getRenderedImage(); int dataHeight = renderedImage.getHeight(); imageObjectInfo.setDataHeight(dataHeight); int dataWidth = renderedImage.getWidth(); imageObjectInfo.setDataWidth(dataWidth); //TODO To reduce AFP file size, investigate using a compression scheme. //Currently, all image data is uncompressed. int maxPixelSize = paintingState.getBitsPerPixel(); if (paintingState.isColorImages()) { maxPixelSize *= 3; //RGB only at the moment } ColorModel cm = renderedImage.getColorModel(); if (log.isTraceEnabled()) { log.trace("ColorModel: " + cm); } int pixelSize = cm.getPixelSize(); if (cm.hasAlpha()) { pixelSize -= 8; } //TODO Add support for CMYK images byte[] imageData = null; ByteArrayOutputStream baos = new ByteArrayOutputStream(); boolean allowDirectEncoding = true; if (allowDirectEncoding && pixelSize <= maxPixelSize) { //Attempt to encode without resampling the image ImageEncodingHelper helper = new ImageEncodingHelper(renderedImage); ColorModel encodedColorModel = helper.getEncodedColorModel(); boolean directEncode = true; if (helper.getEncodedColorModel().getPixelSize() > maxPixelSize) { directEncode = false; //pixel size needs to be reduced } if (BitmapImageUtil.getColorIndexSize(renderedImage) > 2) { directEncode = false; //Lookup tables are not implemented, yet } if (directEncode) { log.debug("Encoding image directly..."); imageObjectInfo.setBitsPerPixel(encodedColorModel.getPixelSize()); if (BitmapImageUtil.isMonochromeImage(renderedImage) && !BitmapImageUtil.isZeroBlack(renderedImage)) { log.trace("set subtractive mode"); imageObjectInfo.setSubtractive(true); } helper.encode(baos); imageData = baos.toByteArray(); } } if (imageData == null) { log.debug("Encoding image via RGB..."); //Convert image to 24bit RGB ImageEncodingHelper.encodeRenderedImageAsRGB(renderedImage, baos); imageData = baos.toByteArray(); boolean colorImages = paintingState.isColorImages(); imageObjectInfo.setColor(colorImages); // convert to grayscale if (!colorImages) { log.debug("Converting RGB image to grayscale..."); baos.reset(); int bitsPerPixel = paintingState.getBitsPerPixel(); imageObjectInfo.setBitsPerPixel(bitsPerPixel); //TODO this should be done off the RenderedImage to avoid buffering the //intermediate 24bit image ImageEncodingHelper.encodeRGBAsGrayScale( imageData, dataWidth, dataHeight, bitsPerPixel, baos); imageData = baos.toByteArray(); } } imageObjectInfo.setData(imageData); // set object area info AFPObjectAreaInfo objectAreaInfo = imageObjectInfo.getObjectAreaInfo(); objectAreaInfo.setWidthRes(resolution); objectAreaInfo.setHeightRes(resolution); return imageObjectInfo; }
private AFPDataObjectInfo updateDataObjectInfo(AFPImageObjectInfo imageObjectInfo, AFPPaintingState paintingState, ImageRendered imageRendered) throws IOException { int resolution = paintingState.getResolution(); imageObjectInfo.setMimeType(MimeConstants.MIME_AFP_IOCA_FS45); imageObjectInfo.setDataHeightRes(resolution); imageObjectInfo.setDataWidthRes(resolution); RenderedImage renderedImage = imageRendered.getRenderedImage(); int dataHeight = renderedImage.getHeight(); imageObjectInfo.setDataHeight(dataHeight); int dataWidth = renderedImage.getWidth(); imageObjectInfo.setDataWidth(dataWidth); //TODO To reduce AFP file size, investigate using a compression scheme. //Currently, all image data is uncompressed. int maxPixelSize = paintingState.getBitsPerPixel(); if (paintingState.isColorImages()) { maxPixelSize *= 3; //RGB only at the moment } ColorModel cm = renderedImage.getColorModel(); if (log.isTraceEnabled()) { log.trace("ColorModel: " + cm); } int pixelSize = cm.getPixelSize(); if (cm.hasAlpha()) { pixelSize -= 8; } //TODO Add support for CMYK images byte[] imageData = null; ByteArrayOutputStream baos = new ByteArrayOutputStream(); boolean allowDirectEncoding = true; if (allowDirectEncoding && pixelSize <= maxPixelSize) { //Attempt to encode without resampling the image ImageEncodingHelper helper = new ImageEncodingHelper(renderedImage); ColorModel encodedColorModel = helper.getEncodedColorModel(); boolean directEncode = true; if (helper.getEncodedColorModel().getPixelSize() > maxPixelSize) { directEncode = false; //pixel size needs to be reduced } if (BitmapImageUtil.getColorIndexSize(renderedImage) > 2) { directEncode = false; //Lookup tables are not implemented, yet } if (directEncode) { log.debug("Encoding image directly..."); imageObjectInfo.setBitsPerPixel(encodedColorModel.getPixelSize()); if (BitmapImageUtil.isMonochromeImage(renderedImage) && !BitmapImageUtil.isZeroBlack(renderedImage)) { log.trace("set subtractive mode"); imageObjectInfo.setSubtractive(true); } helper.encode(baos); imageData = baos.toByteArray(); } } if (imageData == null) { log.debug("Encoding image via RGB..."); //Convert image to 24bit RGB ImageEncodingHelper.encodeRenderedImageAsRGB(renderedImage, baos); imageData = baos.toByteArray(); boolean colorImages = paintingState.isColorImages(); imageObjectInfo.setColor(colorImages); // convert to grayscale if (!colorImages) { log.debug("Converting RGB image to grayscale..."); baos.reset(); int bitsPerPixel = paintingState.getBitsPerPixel(); imageObjectInfo.setBitsPerPixel(bitsPerPixel); //TODO this should be done off the RenderedImage to avoid buffering the //intermediate 24bit image ImageEncodingHelper.encodeRGBAsGrayScale( imageData, dataWidth, dataHeight, bitsPerPixel, baos); imageData = baos.toByteArray(); if (bitsPerPixel == 1) { imageObjectInfo.setSubtractive(true); } } } imageObjectInfo.setData(imageData); // set object area info AFPObjectAreaInfo objectAreaInfo = imageObjectInfo.getObjectAreaInfo(); objectAreaInfo.setWidthRes(resolution); objectAreaInfo.setHeightRes(resolution); return imageObjectInfo; }
diff --git a/src/br/ufmg/dcc/vod/spiderpig/common/config/AbstractConfigurable.java b/src/br/ufmg/dcc/vod/spiderpig/common/config/AbstractConfigurable.java index 1dfe53c..95d8df5 100644 --- a/src/br/ufmg/dcc/vod/spiderpig/common/config/AbstractConfigurable.java +++ b/src/br/ufmg/dcc/vod/spiderpig/common/config/AbstractConfigurable.java @@ -1,34 +1,35 @@ package br.ufmg.dcc.vod.spiderpig.common.config; import java.util.Iterator; import org.apache.commons.configuration.Configuration; import org.apache.commons.configuration.ConfigurationException; /** * Abstract configurable used to guarantee that required parameters * are in the configuration. * * @author Flavio Figueiredo - flaviovdf 'at' gmail.com * * @param <T> Return value of the configurable */ public abstract class AbstractConfigurable<T> implements Configurable<T> { @Override public final T configurate(Configuration configuration) throws Exception { Iterator<String> keys = configuration.getKeys(); while (keys.hasNext()) { String key = keys.next(); if (!getRequiredParameters().contains(key)) - throw new ConfigurationException("Required key not found"); + throw new ConfigurationException("Required key " + key + + " not found"); } return realConfigurate(configuration); } public abstract T realConfigurate(Configuration configuration) throws Exception; }
true
true
public final T configurate(Configuration configuration) throws Exception { Iterator<String> keys = configuration.getKeys(); while (keys.hasNext()) { String key = keys.next(); if (!getRequiredParameters().contains(key)) throw new ConfigurationException("Required key not found"); } return realConfigurate(configuration); }
public final T configurate(Configuration configuration) throws Exception { Iterator<String> keys = configuration.getKeys(); while (keys.hasNext()) { String key = keys.next(); if (!getRequiredParameters().contains(key)) throw new ConfigurationException("Required key " + key + " not found"); } return realConfigurate(configuration); }
diff --git a/software/ICeePotPC/src/iceepotpc/ui/PotPanel.java b/software/ICeePotPC/src/iceepotpc/ui/PotPanel.java index a15459c..b4032f8 100644 --- a/software/ICeePotPC/src/iceepotpc/ui/PotPanel.java +++ b/software/ICeePotPC/src/iceepotpc/ui/PotPanel.java @@ -1,377 +1,378 @@ package iceepotpc.ui; import iceepotpc.appication.Context; import iceepotpc.charteng.ChartCreator; import iceepotpc.servergw.Meauserement; import iceepotpc.servergw.Server; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.ScrollPaneConstants; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.awt.event.ItemListener; import java.awt.event.ItemEvent; import java.awt.Component; import javax.swing.border.CompoundBorder; import java.awt.ComponentOrientation; import java.awt.Dimension; import com.jgoodies.forms.layout.FormLayout; import com.jgoodies.forms.layout.ColumnSpec; import com.jgoodies.forms.factories.FormFactory; import com.jgoodies.forms.layout.RowSpec; import java.awt.GridBagLayout; import java.awt.GridBagConstraints; import java.awt.Insets; import javax.swing.border.LineBorder; import java.awt.Color; /** * @author tsantakis A tab where information and inputs per pot is displayed. * */ public class PotPanel extends JPanel { /** * */ private static final long serialVersionUID = 1L; private String[] availableMonths = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; private String[] availableYears = { "2011", "2012", "2013", "2014" }; private JTextField txtLastValue; private JTextField txtLastTime; Context cntx; DateFormat df = new SimpleDateFormat(); ArrayList<Meauserement> measurements = null; /** * Create the panel. */ public PotPanel(final int pin, final JFrame frame) { setSize(new Dimension(900, 780)); setMinimumSize(new Dimension(900, 780)); cntx = Context.getInstance(); this.setToolTipText(""); GridBagLayout gridBagLayout = new GridBagLayout(); gridBagLayout.columnWidths = new int[] { 47, 186, 30, 620 }; gridBagLayout.rowHeights = new int[] {29, 450, 85, 0}; gridBagLayout.columnWeights = new double[] { 0.0, 0.0, 0.0, 1.0 }; gridBagLayout.rowWeights = new double[] { 0.0, 1.0, 0.0, Double.MIN_VALUE }; setLayout(gridBagLayout); // last values panel JPanel pnlLastValues = new JPanel(); pnlLastValues.setPreferredSize(new Dimension(410, 20)); pnlLastValues.setMinimumSize(new Dimension(410, 20)); pnlLastValues.setMaximumSize(new Dimension(410, 20)); pnlLastValues .setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT); pnlLastValues.setAlignmentY(Component.TOP_ALIGNMENT); pnlLastValues.setAlignmentX(Component.LEFT_ALIGNMENT); GridBagConstraints gbc_pnlLastValues = new GridBagConstraints(); gbc_pnlLastValues.insets = new Insets(0, 0, 5, 0); gbc_pnlLastValues.ipady = 5; gbc_pnlLastValues.ipadx = 5; gbc_pnlLastValues.gridwidth = 3; gbc_pnlLastValues.anchor = GridBagConstraints.NORTHWEST; gbc_pnlLastValues.gridx = 1; gbc_pnlLastValues.gridy = 0; add(pnlLastValues, gbc_pnlLastValues); GridBagLayout gbl_pnlLastValues = new GridBagLayout(); gbl_pnlLastValues.columnWidths = new int[] { 150, 90, 40, 120 }; gbl_pnlLastValues.rowHeights = new int[] { 20 }; gbl_pnlLastValues.columnWeights = new double[] { 0.0, 0.0, 0.0, 0.0 }; gbl_pnlLastValues.rowWeights = new double[] { 0.0 }; pnlLastValues.setLayout(gbl_pnlLastValues); JLabel lblLastMeasruement = new JLabel("Last measurement"); lblLastMeasruement.setPreferredSize(new Dimension(130, 20)); lblLastMeasruement.setSize(new Dimension(130, 20)); lblLastMeasruement.setMinimumSize(new Dimension(130, 20)); lblLastMeasruement.setMaximumSize(new Dimension(130, 20)); lblLastMeasruement.setBorder(new CompoundBorder()); GridBagConstraints gbc_lblLastMeasruement = new GridBagConstraints(); gbc_lblLastMeasruement.anchor = GridBagConstraints.EAST; gbc_lblLastMeasruement.fill = GridBagConstraints.VERTICAL; gbc_lblLastMeasruement.insets = new Insets(0, 0, 0, 5); gbc_lblLastMeasruement.gridx = 0; gbc_lblLastMeasruement.gridy = 0; pnlLastValues.add(lblLastMeasruement, gbc_lblLastMeasruement); txtLastValue = new JTextField(); txtLastValue.setColumns(10); txtLastValue.setPreferredSize(new Dimension(90, 20)); txtLastValue.setMinimumSize(new Dimension(90, 20)); txtLastValue.setMaximumSize(new Dimension(90, 20)); GridBagConstraints gbc_txtLastValue = new GridBagConstraints(); gbc_txtLastValue.fill = GridBagConstraints.BOTH; gbc_txtLastValue.gridx = 1; gbc_txtLastValue.gridy = 0; pnlLastValues.add(txtLastValue, gbc_txtLastValue); txtLastValue.setEditable(false); JLabel lblAt = new JLabel("at"); lblAt.setPreferredSize(new Dimension(40, 20)); lblAt.setMinimumSize(new Dimension(40, 20)); lblAt.setMaximumSize(new Dimension(40, 20)); lblAt.setAlignmentX(Component.RIGHT_ALIGNMENT); GridBagConstraints gbc_lblAt = new GridBagConstraints(); gbc_lblAt.anchor = GridBagConstraints.EAST; gbc_lblAt.fill = GridBagConstraints.VERTICAL; gbc_lblAt.insets = new Insets(0, 5, 0, 5); gbc_lblAt.gridx = 2; gbc_lblAt.gridy = 0; pnlLastValues.add(lblAt, gbc_lblAt); txtLastTime = new JTextField(); txtLastTime.setSize(new Dimension(120, 20)); txtLastTime.setPreferredSize(new Dimension(120, 20)); txtLastTime.setMinimumSize(new Dimension(120, 20)); txtLastTime.setMaximumSize(new Dimension(120, 20)); GridBagConstraints gbc_txtLastTime = new GridBagConstraints(); gbc_txtLastTime.fill = GridBagConstraints.BOTH; gbc_txtLastTime.gridx = 3; gbc_txtLastTime.gridy = 0; pnlLastValues.add(txtLastTime, gbc_txtLastTime); txtLastTime.setColumns(10); txtLastTime.setEditable(false); // panel results final JTextArea txtResults = new JTextArea(); txtResults.setEditable(false); txtResults.setTabSize(2); txtResults.setPreferredSize(new Dimension(120, 4000)); txtResults.setMinimumSize(new Dimension(120, 4000)); txtResults.setMaximumSize(new Dimension(120, 4000)); // txtResults.setMaximumSize(new Dimension(32767, 32767)); // txtResults.setMinimumSize(new Dimension(23, 23)); // txtResults.setBounds(47, 58, 601, 400); JScrollPane sp = new JScrollPane(txtResults); sp.setPreferredSize(new Dimension(120, 450)); sp.setMinimumSize(new Dimension(120, 450)); sp.setMaximumSize(new Dimension(120, 450)); sp.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); sp.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); GridBagConstraints gbc_sp = new GridBagConstraints(); gbc_sp.fill = GridBagConstraints.BOTH; gbc_sp.insets = new Insets(0, 0, 5, 5); gbc_sp.gridx = 1; gbc_sp.gridy = 1; this.add(sp, gbc_sp); txtResults.setColumns(1); txtResults.setRows(30); final ChartPanel pnlChart = new ChartPanel(null); pnlChart.setMaximumDrawWidth(2048); pnlChart.setMinimumDrawWidth(620); pnlChart.setMinimumSize(new Dimension(620, 450)); pnlChart.setPreferredSize(new Dimension(620, 450)); //FlowLayout flowLayout = (FlowLayout) pnlChart.getLayout(); GridBagConstraints gbc_pnlChart = new GridBagConstraints(); gbc_pnlChart.fill = GridBagConstraints.BOTH; gbc_pnlChart.insets = new Insets(0, 0, 5, 0); gbc_pnlChart.gridx = 3; gbc_pnlChart.gridy = 1; add(pnlChart, gbc_pnlChart); // criteria panel JPanel pnlCriteria = new JPanel(); pnlCriteria.setSize(new Dimension(500, 85)); pnlCriteria.setMinimumSize(new Dimension(500, 85)); pnlCriteria.setBorder(new LineBorder(new Color(0, 0, 0), 1, true)); pnlCriteria.setAlignmentY(Component.BOTTOM_ALIGNMENT); pnlCriteria.setAlignmentX(Component.RIGHT_ALIGNMENT); GridBagConstraints gbc_pnlCriteria = new GridBagConstraints(); gbc_pnlCriteria.insets = new Insets(0, 5, 0, 0); gbc_pnlCriteria.anchor = GridBagConstraints.SOUTHEAST; gbc_pnlCriteria.gridx = 3; gbc_pnlCriteria.gridy = 2; add(pnlCriteria, gbc_pnlCriteria); pnlCriteria.setLayout(new FormLayout(new ColumnSpec[] { FormFactory.UNRELATED_GAP_COLSPEC, ColumnSpec.decode("60px"), FormFactory.UNRELATED_GAP_COLSPEC, ColumnSpec.decode("112px"), FormFactory.UNRELATED_GAP_COLSPEC, ColumnSpec.decode("112px"), FormFactory.RELATED_GAP_COLSPEC, FormFactory.DEFAULT_COLSPEC, FormFactory.UNRELATED_GAP_COLSPEC,}, new RowSpec[] { FormFactory.UNRELATED_GAP_ROWSPEC, RowSpec.decode("26px"), FormFactory.UNRELATED_GAP_ROWSPEC, RowSpec.decode("26px"), FormFactory.UNRELATED_GAP_ROWSPEC,})); JLabel lblDateFrom = new JLabel("From"); pnlCriteria.add(lblDateFrom, "2, 2, fill, fill"); final JComboBox cmbMonthFrom = new JComboBox(); pnlCriteria.add(cmbMonthFrom, "4, 2, fill, fill"); JLabel lblDateTo = new JLabel("To"); pnlCriteria.add(lblDateTo, "2, 4, fill, fill"); final JComboBox cmbMonthTo = new JComboBox(); pnlCriteria.add(cmbMonthTo, "4, 4, fill, fill"); final JComboBox cmbYearTo = new JComboBox(); pnlCriteria.add(cmbYearTo, "6, 4, fill, fill"); JButton btnGet = new JButton("Get Information"); pnlCriteria.add(btnGet, "8, 4, fill, fill"); // handlers this.addComponentListener(new ComponentListener() { @Override public void componentShown(ComponentEvent e) { // TODO Auto-generated method stub } @Override public void componentResized(ComponentEvent e) { if(measurements!= null){ JFreeChart fc = ChartCreator .createChart(measurements); // pnlChart = new ChartPanel(fc, false); pnlChart.setChart(fc); // pnlChart.setBounds(263, 70, 620, 460); pnlChart.setVisible(true); } } @Override public void componentMoved(ComponentEvent e) { // TODO Auto-generated method stub } @Override public void componentHidden(ComponentEvent e) { // TODO Auto-generated method stub } }); cmbMonthFrom.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent arg0) { cmbMonthTo.setSelectedIndex(cmbMonthFrom.getSelectedIndex()); } }); final JComboBox cmbYearFrom = new JComboBox(); pnlCriteria.add(cmbYearFrom, "6, 2, fill, fill"); cmbYearFrom.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { cmbYearTo.setSelectedIndex(cmbYearFrom.getSelectedIndex()); } }); btnGet.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { + txtResults.setText(""); Calendar from = Calendar.getInstance(); from.set(Calendar.MONTH, cmbMonthFrom.getSelectedIndex() + 1); from.set(Calendar.DAY_OF_MONTH, 1); from.set(Calendar.YEAR, Integer.parseInt((String) cmbYearFrom .getSelectedItem())); Calendar to = Calendar.getInstance(); to.set(Calendar.MONTH, cmbMonthTo.getSelectedIndex() + 1); to.set(Calendar.DAY_OF_MONTH, 1); to.set(Calendar.YEAR, Integer.parseInt((String) cmbYearTo.getSelectedItem())); if (from.getTime().getTime() > to.getTime().getTime()) { JOptionPane.showMessageDialog(frame, "The \"From\" date is after the \"To\" one", "Warning", JOptionPane.ERROR_MESSAGE); } else { measurements = null; try { measurements = Server.GetMeasurements(from, to, pin, cntx); if (measurements == null || measurements.size() == 0) JOptionPane.showMessageDialog(frame, "Measurements not available yet", "Warning", JOptionPane.WARNING_MESSAGE); else { for (int i = 0; i < measurements.size(); i++) txtResults.setText(txtResults.getText() + "\n" + df.format(new Date(measurements .get(i).getMoment())) + "\t" + measurements.get(i).getValue()); Calendar c = Calendar.getInstance(); c.setTimeInMillis((long) measurements.get( measurements.size() - 1).getMoment()); txtLastTime.setText(df.format(c.getTime())); txtLastValue.setText(String.valueOf(measurements .get(measurements.size() - 1).getValue())); JFreeChart fc = ChartCreator .createChart(measurements); // pnlChart = new ChartPanel(fc, false); pnlChart.setChart(fc); // pnlChart.setBounds(263, 70, 620, 460); pnlChart.setVisible(true); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, e1.getMessage(), "Warning", JOptionPane.ERROR_MESSAGE); } } } }); // filling data for (int i = 0; i < availableMonths.length; i++) cmbMonthTo.addItem(availableMonths[i]); for (int i = 0; i < availableYears.length; i++) cmbYearTo.addItem(availableYears[i]); for (int i = 0; i < availableMonths.length; i++) cmbMonthFrom.addItem(availableMonths[i]); for (int i = 0; i < availableYears.length; i++) cmbYearFrom.addItem(availableYears[i]); } }
true
true
public PotPanel(final int pin, final JFrame frame) { setSize(new Dimension(900, 780)); setMinimumSize(new Dimension(900, 780)); cntx = Context.getInstance(); this.setToolTipText(""); GridBagLayout gridBagLayout = new GridBagLayout(); gridBagLayout.columnWidths = new int[] { 47, 186, 30, 620 }; gridBagLayout.rowHeights = new int[] {29, 450, 85, 0}; gridBagLayout.columnWeights = new double[] { 0.0, 0.0, 0.0, 1.0 }; gridBagLayout.rowWeights = new double[] { 0.0, 1.0, 0.0, Double.MIN_VALUE }; setLayout(gridBagLayout); // last values panel JPanel pnlLastValues = new JPanel(); pnlLastValues.setPreferredSize(new Dimension(410, 20)); pnlLastValues.setMinimumSize(new Dimension(410, 20)); pnlLastValues.setMaximumSize(new Dimension(410, 20)); pnlLastValues .setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT); pnlLastValues.setAlignmentY(Component.TOP_ALIGNMENT); pnlLastValues.setAlignmentX(Component.LEFT_ALIGNMENT); GridBagConstraints gbc_pnlLastValues = new GridBagConstraints(); gbc_pnlLastValues.insets = new Insets(0, 0, 5, 0); gbc_pnlLastValues.ipady = 5; gbc_pnlLastValues.ipadx = 5; gbc_pnlLastValues.gridwidth = 3; gbc_pnlLastValues.anchor = GridBagConstraints.NORTHWEST; gbc_pnlLastValues.gridx = 1; gbc_pnlLastValues.gridy = 0; add(pnlLastValues, gbc_pnlLastValues); GridBagLayout gbl_pnlLastValues = new GridBagLayout(); gbl_pnlLastValues.columnWidths = new int[] { 150, 90, 40, 120 }; gbl_pnlLastValues.rowHeights = new int[] { 20 }; gbl_pnlLastValues.columnWeights = new double[] { 0.0, 0.0, 0.0, 0.0 }; gbl_pnlLastValues.rowWeights = new double[] { 0.0 }; pnlLastValues.setLayout(gbl_pnlLastValues); JLabel lblLastMeasruement = new JLabel("Last measurement"); lblLastMeasruement.setPreferredSize(new Dimension(130, 20)); lblLastMeasruement.setSize(new Dimension(130, 20)); lblLastMeasruement.setMinimumSize(new Dimension(130, 20)); lblLastMeasruement.setMaximumSize(new Dimension(130, 20)); lblLastMeasruement.setBorder(new CompoundBorder()); GridBagConstraints gbc_lblLastMeasruement = new GridBagConstraints(); gbc_lblLastMeasruement.anchor = GridBagConstraints.EAST; gbc_lblLastMeasruement.fill = GridBagConstraints.VERTICAL; gbc_lblLastMeasruement.insets = new Insets(0, 0, 0, 5); gbc_lblLastMeasruement.gridx = 0; gbc_lblLastMeasruement.gridy = 0; pnlLastValues.add(lblLastMeasruement, gbc_lblLastMeasruement); txtLastValue = new JTextField(); txtLastValue.setColumns(10); txtLastValue.setPreferredSize(new Dimension(90, 20)); txtLastValue.setMinimumSize(new Dimension(90, 20)); txtLastValue.setMaximumSize(new Dimension(90, 20)); GridBagConstraints gbc_txtLastValue = new GridBagConstraints(); gbc_txtLastValue.fill = GridBagConstraints.BOTH; gbc_txtLastValue.gridx = 1; gbc_txtLastValue.gridy = 0; pnlLastValues.add(txtLastValue, gbc_txtLastValue); txtLastValue.setEditable(false); JLabel lblAt = new JLabel("at"); lblAt.setPreferredSize(new Dimension(40, 20)); lblAt.setMinimumSize(new Dimension(40, 20)); lblAt.setMaximumSize(new Dimension(40, 20)); lblAt.setAlignmentX(Component.RIGHT_ALIGNMENT); GridBagConstraints gbc_lblAt = new GridBagConstraints(); gbc_lblAt.anchor = GridBagConstraints.EAST; gbc_lblAt.fill = GridBagConstraints.VERTICAL; gbc_lblAt.insets = new Insets(0, 5, 0, 5); gbc_lblAt.gridx = 2; gbc_lblAt.gridy = 0; pnlLastValues.add(lblAt, gbc_lblAt); txtLastTime = new JTextField(); txtLastTime.setSize(new Dimension(120, 20)); txtLastTime.setPreferredSize(new Dimension(120, 20)); txtLastTime.setMinimumSize(new Dimension(120, 20)); txtLastTime.setMaximumSize(new Dimension(120, 20)); GridBagConstraints gbc_txtLastTime = new GridBagConstraints(); gbc_txtLastTime.fill = GridBagConstraints.BOTH; gbc_txtLastTime.gridx = 3; gbc_txtLastTime.gridy = 0; pnlLastValues.add(txtLastTime, gbc_txtLastTime); txtLastTime.setColumns(10); txtLastTime.setEditable(false); // panel results final JTextArea txtResults = new JTextArea(); txtResults.setEditable(false); txtResults.setTabSize(2); txtResults.setPreferredSize(new Dimension(120, 4000)); txtResults.setMinimumSize(new Dimension(120, 4000)); txtResults.setMaximumSize(new Dimension(120, 4000)); // txtResults.setMaximumSize(new Dimension(32767, 32767)); // txtResults.setMinimumSize(new Dimension(23, 23)); // txtResults.setBounds(47, 58, 601, 400); JScrollPane sp = new JScrollPane(txtResults); sp.setPreferredSize(new Dimension(120, 450)); sp.setMinimumSize(new Dimension(120, 450)); sp.setMaximumSize(new Dimension(120, 450)); sp.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); sp.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); GridBagConstraints gbc_sp = new GridBagConstraints(); gbc_sp.fill = GridBagConstraints.BOTH; gbc_sp.insets = new Insets(0, 0, 5, 5); gbc_sp.gridx = 1; gbc_sp.gridy = 1; this.add(sp, gbc_sp); txtResults.setColumns(1); txtResults.setRows(30); final ChartPanel pnlChart = new ChartPanel(null); pnlChart.setMaximumDrawWidth(2048); pnlChart.setMinimumDrawWidth(620); pnlChart.setMinimumSize(new Dimension(620, 450)); pnlChart.setPreferredSize(new Dimension(620, 450)); //FlowLayout flowLayout = (FlowLayout) pnlChart.getLayout(); GridBagConstraints gbc_pnlChart = new GridBagConstraints(); gbc_pnlChart.fill = GridBagConstraints.BOTH; gbc_pnlChart.insets = new Insets(0, 0, 5, 0); gbc_pnlChart.gridx = 3; gbc_pnlChart.gridy = 1; add(pnlChart, gbc_pnlChart); // criteria panel JPanel pnlCriteria = new JPanel(); pnlCriteria.setSize(new Dimension(500, 85)); pnlCriteria.setMinimumSize(new Dimension(500, 85)); pnlCriteria.setBorder(new LineBorder(new Color(0, 0, 0), 1, true)); pnlCriteria.setAlignmentY(Component.BOTTOM_ALIGNMENT); pnlCriteria.setAlignmentX(Component.RIGHT_ALIGNMENT); GridBagConstraints gbc_pnlCriteria = new GridBagConstraints(); gbc_pnlCriteria.insets = new Insets(0, 5, 0, 0); gbc_pnlCriteria.anchor = GridBagConstraints.SOUTHEAST; gbc_pnlCriteria.gridx = 3; gbc_pnlCriteria.gridy = 2; add(pnlCriteria, gbc_pnlCriteria); pnlCriteria.setLayout(new FormLayout(new ColumnSpec[] { FormFactory.UNRELATED_GAP_COLSPEC, ColumnSpec.decode("60px"), FormFactory.UNRELATED_GAP_COLSPEC, ColumnSpec.decode("112px"), FormFactory.UNRELATED_GAP_COLSPEC, ColumnSpec.decode("112px"), FormFactory.RELATED_GAP_COLSPEC, FormFactory.DEFAULT_COLSPEC, FormFactory.UNRELATED_GAP_COLSPEC,}, new RowSpec[] { FormFactory.UNRELATED_GAP_ROWSPEC, RowSpec.decode("26px"), FormFactory.UNRELATED_GAP_ROWSPEC, RowSpec.decode("26px"), FormFactory.UNRELATED_GAP_ROWSPEC,})); JLabel lblDateFrom = new JLabel("From"); pnlCriteria.add(lblDateFrom, "2, 2, fill, fill"); final JComboBox cmbMonthFrom = new JComboBox(); pnlCriteria.add(cmbMonthFrom, "4, 2, fill, fill"); JLabel lblDateTo = new JLabel("To"); pnlCriteria.add(lblDateTo, "2, 4, fill, fill"); final JComboBox cmbMonthTo = new JComboBox(); pnlCriteria.add(cmbMonthTo, "4, 4, fill, fill"); final JComboBox cmbYearTo = new JComboBox(); pnlCriteria.add(cmbYearTo, "6, 4, fill, fill"); JButton btnGet = new JButton("Get Information"); pnlCriteria.add(btnGet, "8, 4, fill, fill"); // handlers this.addComponentListener(new ComponentListener() { @Override public void componentShown(ComponentEvent e) { // TODO Auto-generated method stub } @Override public void componentResized(ComponentEvent e) { if(measurements!= null){ JFreeChart fc = ChartCreator .createChart(measurements); // pnlChart = new ChartPanel(fc, false); pnlChart.setChart(fc); // pnlChart.setBounds(263, 70, 620, 460); pnlChart.setVisible(true); } } @Override public void componentMoved(ComponentEvent e) { // TODO Auto-generated method stub } @Override public void componentHidden(ComponentEvent e) { // TODO Auto-generated method stub } }); cmbMonthFrom.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent arg0) { cmbMonthTo.setSelectedIndex(cmbMonthFrom.getSelectedIndex()); } }); final JComboBox cmbYearFrom = new JComboBox(); pnlCriteria.add(cmbYearFrom, "6, 2, fill, fill"); cmbYearFrom.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { cmbYearTo.setSelectedIndex(cmbYearFrom.getSelectedIndex()); } }); btnGet.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Calendar from = Calendar.getInstance(); from.set(Calendar.MONTH, cmbMonthFrom.getSelectedIndex() + 1); from.set(Calendar.DAY_OF_MONTH, 1); from.set(Calendar.YEAR, Integer.parseInt((String) cmbYearFrom .getSelectedItem())); Calendar to = Calendar.getInstance(); to.set(Calendar.MONTH, cmbMonthTo.getSelectedIndex() + 1); to.set(Calendar.DAY_OF_MONTH, 1); to.set(Calendar.YEAR, Integer.parseInt((String) cmbYearTo.getSelectedItem())); if (from.getTime().getTime() > to.getTime().getTime()) { JOptionPane.showMessageDialog(frame, "The \"From\" date is after the \"To\" one", "Warning", JOptionPane.ERROR_MESSAGE); } else { measurements = null; try { measurements = Server.GetMeasurements(from, to, pin, cntx); if (measurements == null || measurements.size() == 0) JOptionPane.showMessageDialog(frame, "Measurements not available yet", "Warning", JOptionPane.WARNING_MESSAGE); else { for (int i = 0; i < measurements.size(); i++) txtResults.setText(txtResults.getText() + "\n" + df.format(new Date(measurements .get(i).getMoment())) + "\t" + measurements.get(i).getValue()); Calendar c = Calendar.getInstance(); c.setTimeInMillis((long) measurements.get( measurements.size() - 1).getMoment()); txtLastTime.setText(df.format(c.getTime())); txtLastValue.setText(String.valueOf(measurements .get(measurements.size() - 1).getValue())); JFreeChart fc = ChartCreator .createChart(measurements); // pnlChart = new ChartPanel(fc, false); pnlChart.setChart(fc); // pnlChart.setBounds(263, 70, 620, 460); pnlChart.setVisible(true); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, e1.getMessage(), "Warning", JOptionPane.ERROR_MESSAGE); } } } }); // filling data for (int i = 0; i < availableMonths.length; i++) cmbMonthTo.addItem(availableMonths[i]); for (int i = 0; i < availableYears.length; i++) cmbYearTo.addItem(availableYears[i]); for (int i = 0; i < availableMonths.length; i++) cmbMonthFrom.addItem(availableMonths[i]); for (int i = 0; i < availableYears.length; i++) cmbYearFrom.addItem(availableYears[i]); }
public PotPanel(final int pin, final JFrame frame) { setSize(new Dimension(900, 780)); setMinimumSize(new Dimension(900, 780)); cntx = Context.getInstance(); this.setToolTipText(""); GridBagLayout gridBagLayout = new GridBagLayout(); gridBagLayout.columnWidths = new int[] { 47, 186, 30, 620 }; gridBagLayout.rowHeights = new int[] {29, 450, 85, 0}; gridBagLayout.columnWeights = new double[] { 0.0, 0.0, 0.0, 1.0 }; gridBagLayout.rowWeights = new double[] { 0.0, 1.0, 0.0, Double.MIN_VALUE }; setLayout(gridBagLayout); // last values panel JPanel pnlLastValues = new JPanel(); pnlLastValues.setPreferredSize(new Dimension(410, 20)); pnlLastValues.setMinimumSize(new Dimension(410, 20)); pnlLastValues.setMaximumSize(new Dimension(410, 20)); pnlLastValues .setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT); pnlLastValues.setAlignmentY(Component.TOP_ALIGNMENT); pnlLastValues.setAlignmentX(Component.LEFT_ALIGNMENT); GridBagConstraints gbc_pnlLastValues = new GridBagConstraints(); gbc_pnlLastValues.insets = new Insets(0, 0, 5, 0); gbc_pnlLastValues.ipady = 5; gbc_pnlLastValues.ipadx = 5; gbc_pnlLastValues.gridwidth = 3; gbc_pnlLastValues.anchor = GridBagConstraints.NORTHWEST; gbc_pnlLastValues.gridx = 1; gbc_pnlLastValues.gridy = 0; add(pnlLastValues, gbc_pnlLastValues); GridBagLayout gbl_pnlLastValues = new GridBagLayout(); gbl_pnlLastValues.columnWidths = new int[] { 150, 90, 40, 120 }; gbl_pnlLastValues.rowHeights = new int[] { 20 }; gbl_pnlLastValues.columnWeights = new double[] { 0.0, 0.0, 0.0, 0.0 }; gbl_pnlLastValues.rowWeights = new double[] { 0.0 }; pnlLastValues.setLayout(gbl_pnlLastValues); JLabel lblLastMeasruement = new JLabel("Last measurement"); lblLastMeasruement.setPreferredSize(new Dimension(130, 20)); lblLastMeasruement.setSize(new Dimension(130, 20)); lblLastMeasruement.setMinimumSize(new Dimension(130, 20)); lblLastMeasruement.setMaximumSize(new Dimension(130, 20)); lblLastMeasruement.setBorder(new CompoundBorder()); GridBagConstraints gbc_lblLastMeasruement = new GridBagConstraints(); gbc_lblLastMeasruement.anchor = GridBagConstraints.EAST; gbc_lblLastMeasruement.fill = GridBagConstraints.VERTICAL; gbc_lblLastMeasruement.insets = new Insets(0, 0, 0, 5); gbc_lblLastMeasruement.gridx = 0; gbc_lblLastMeasruement.gridy = 0; pnlLastValues.add(lblLastMeasruement, gbc_lblLastMeasruement); txtLastValue = new JTextField(); txtLastValue.setColumns(10); txtLastValue.setPreferredSize(new Dimension(90, 20)); txtLastValue.setMinimumSize(new Dimension(90, 20)); txtLastValue.setMaximumSize(new Dimension(90, 20)); GridBagConstraints gbc_txtLastValue = new GridBagConstraints(); gbc_txtLastValue.fill = GridBagConstraints.BOTH; gbc_txtLastValue.gridx = 1; gbc_txtLastValue.gridy = 0; pnlLastValues.add(txtLastValue, gbc_txtLastValue); txtLastValue.setEditable(false); JLabel lblAt = new JLabel("at"); lblAt.setPreferredSize(new Dimension(40, 20)); lblAt.setMinimumSize(new Dimension(40, 20)); lblAt.setMaximumSize(new Dimension(40, 20)); lblAt.setAlignmentX(Component.RIGHT_ALIGNMENT); GridBagConstraints gbc_lblAt = new GridBagConstraints(); gbc_lblAt.anchor = GridBagConstraints.EAST; gbc_lblAt.fill = GridBagConstraints.VERTICAL; gbc_lblAt.insets = new Insets(0, 5, 0, 5); gbc_lblAt.gridx = 2; gbc_lblAt.gridy = 0; pnlLastValues.add(lblAt, gbc_lblAt); txtLastTime = new JTextField(); txtLastTime.setSize(new Dimension(120, 20)); txtLastTime.setPreferredSize(new Dimension(120, 20)); txtLastTime.setMinimumSize(new Dimension(120, 20)); txtLastTime.setMaximumSize(new Dimension(120, 20)); GridBagConstraints gbc_txtLastTime = new GridBagConstraints(); gbc_txtLastTime.fill = GridBagConstraints.BOTH; gbc_txtLastTime.gridx = 3; gbc_txtLastTime.gridy = 0; pnlLastValues.add(txtLastTime, gbc_txtLastTime); txtLastTime.setColumns(10); txtLastTime.setEditable(false); // panel results final JTextArea txtResults = new JTextArea(); txtResults.setEditable(false); txtResults.setTabSize(2); txtResults.setPreferredSize(new Dimension(120, 4000)); txtResults.setMinimumSize(new Dimension(120, 4000)); txtResults.setMaximumSize(new Dimension(120, 4000)); // txtResults.setMaximumSize(new Dimension(32767, 32767)); // txtResults.setMinimumSize(new Dimension(23, 23)); // txtResults.setBounds(47, 58, 601, 400); JScrollPane sp = new JScrollPane(txtResults); sp.setPreferredSize(new Dimension(120, 450)); sp.setMinimumSize(new Dimension(120, 450)); sp.setMaximumSize(new Dimension(120, 450)); sp.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); sp.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); GridBagConstraints gbc_sp = new GridBagConstraints(); gbc_sp.fill = GridBagConstraints.BOTH; gbc_sp.insets = new Insets(0, 0, 5, 5); gbc_sp.gridx = 1; gbc_sp.gridy = 1; this.add(sp, gbc_sp); txtResults.setColumns(1); txtResults.setRows(30); final ChartPanel pnlChart = new ChartPanel(null); pnlChart.setMaximumDrawWidth(2048); pnlChart.setMinimumDrawWidth(620); pnlChart.setMinimumSize(new Dimension(620, 450)); pnlChart.setPreferredSize(new Dimension(620, 450)); //FlowLayout flowLayout = (FlowLayout) pnlChart.getLayout(); GridBagConstraints gbc_pnlChart = new GridBagConstraints(); gbc_pnlChart.fill = GridBagConstraints.BOTH; gbc_pnlChart.insets = new Insets(0, 0, 5, 0); gbc_pnlChart.gridx = 3; gbc_pnlChart.gridy = 1; add(pnlChart, gbc_pnlChart); // criteria panel JPanel pnlCriteria = new JPanel(); pnlCriteria.setSize(new Dimension(500, 85)); pnlCriteria.setMinimumSize(new Dimension(500, 85)); pnlCriteria.setBorder(new LineBorder(new Color(0, 0, 0), 1, true)); pnlCriteria.setAlignmentY(Component.BOTTOM_ALIGNMENT); pnlCriteria.setAlignmentX(Component.RIGHT_ALIGNMENT); GridBagConstraints gbc_pnlCriteria = new GridBagConstraints(); gbc_pnlCriteria.insets = new Insets(0, 5, 0, 0); gbc_pnlCriteria.anchor = GridBagConstraints.SOUTHEAST; gbc_pnlCriteria.gridx = 3; gbc_pnlCriteria.gridy = 2; add(pnlCriteria, gbc_pnlCriteria); pnlCriteria.setLayout(new FormLayout(new ColumnSpec[] { FormFactory.UNRELATED_GAP_COLSPEC, ColumnSpec.decode("60px"), FormFactory.UNRELATED_GAP_COLSPEC, ColumnSpec.decode("112px"), FormFactory.UNRELATED_GAP_COLSPEC, ColumnSpec.decode("112px"), FormFactory.RELATED_GAP_COLSPEC, FormFactory.DEFAULT_COLSPEC, FormFactory.UNRELATED_GAP_COLSPEC,}, new RowSpec[] { FormFactory.UNRELATED_GAP_ROWSPEC, RowSpec.decode("26px"), FormFactory.UNRELATED_GAP_ROWSPEC, RowSpec.decode("26px"), FormFactory.UNRELATED_GAP_ROWSPEC,})); JLabel lblDateFrom = new JLabel("From"); pnlCriteria.add(lblDateFrom, "2, 2, fill, fill"); final JComboBox cmbMonthFrom = new JComboBox(); pnlCriteria.add(cmbMonthFrom, "4, 2, fill, fill"); JLabel lblDateTo = new JLabel("To"); pnlCriteria.add(lblDateTo, "2, 4, fill, fill"); final JComboBox cmbMonthTo = new JComboBox(); pnlCriteria.add(cmbMonthTo, "4, 4, fill, fill"); final JComboBox cmbYearTo = new JComboBox(); pnlCriteria.add(cmbYearTo, "6, 4, fill, fill"); JButton btnGet = new JButton("Get Information"); pnlCriteria.add(btnGet, "8, 4, fill, fill"); // handlers this.addComponentListener(new ComponentListener() { @Override public void componentShown(ComponentEvent e) { // TODO Auto-generated method stub } @Override public void componentResized(ComponentEvent e) { if(measurements!= null){ JFreeChart fc = ChartCreator .createChart(measurements); // pnlChart = new ChartPanel(fc, false); pnlChart.setChart(fc); // pnlChart.setBounds(263, 70, 620, 460); pnlChart.setVisible(true); } } @Override public void componentMoved(ComponentEvent e) { // TODO Auto-generated method stub } @Override public void componentHidden(ComponentEvent e) { // TODO Auto-generated method stub } }); cmbMonthFrom.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent arg0) { cmbMonthTo.setSelectedIndex(cmbMonthFrom.getSelectedIndex()); } }); final JComboBox cmbYearFrom = new JComboBox(); pnlCriteria.add(cmbYearFrom, "6, 2, fill, fill"); cmbYearFrom.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { cmbYearTo.setSelectedIndex(cmbYearFrom.getSelectedIndex()); } }); btnGet.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { txtResults.setText(""); Calendar from = Calendar.getInstance(); from.set(Calendar.MONTH, cmbMonthFrom.getSelectedIndex() + 1); from.set(Calendar.DAY_OF_MONTH, 1); from.set(Calendar.YEAR, Integer.parseInt((String) cmbYearFrom .getSelectedItem())); Calendar to = Calendar.getInstance(); to.set(Calendar.MONTH, cmbMonthTo.getSelectedIndex() + 1); to.set(Calendar.DAY_OF_MONTH, 1); to.set(Calendar.YEAR, Integer.parseInt((String) cmbYearTo.getSelectedItem())); if (from.getTime().getTime() > to.getTime().getTime()) { JOptionPane.showMessageDialog(frame, "The \"From\" date is after the \"To\" one", "Warning", JOptionPane.ERROR_MESSAGE); } else { measurements = null; try { measurements = Server.GetMeasurements(from, to, pin, cntx); if (measurements == null || measurements.size() == 0) JOptionPane.showMessageDialog(frame, "Measurements not available yet", "Warning", JOptionPane.WARNING_MESSAGE); else { for (int i = 0; i < measurements.size(); i++) txtResults.setText(txtResults.getText() + "\n" + df.format(new Date(measurements .get(i).getMoment())) + "\t" + measurements.get(i).getValue()); Calendar c = Calendar.getInstance(); c.setTimeInMillis((long) measurements.get( measurements.size() - 1).getMoment()); txtLastTime.setText(df.format(c.getTime())); txtLastValue.setText(String.valueOf(measurements .get(measurements.size() - 1).getValue())); JFreeChart fc = ChartCreator .createChart(measurements); // pnlChart = new ChartPanel(fc, false); pnlChart.setChart(fc); // pnlChart.setBounds(263, 70, 620, 460); pnlChart.setVisible(true); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, e1.getMessage(), "Warning", JOptionPane.ERROR_MESSAGE); } } } }); // filling data for (int i = 0; i < availableMonths.length; i++) cmbMonthTo.addItem(availableMonths[i]); for (int i = 0; i < availableYears.length; i++) cmbYearTo.addItem(availableYears[i]); for (int i = 0; i < availableMonths.length; i++) cmbMonthFrom.addItem(availableMonths[i]); for (int i = 0; i < availableYears.length; i++) cmbYearFrom.addItem(availableYears[i]); }
diff --git a/elog/src/de/elog/elReasoner/OWLWriter.java b/elog/src/de/elog/elReasoner/OWLWriter.java index 1af3f1b..3d0b5fa 100644 --- a/elog/src/de/elog/elReasoner/OWLWriter.java +++ b/elog/src/de/elog/elReasoner/OWLWriter.java @@ -1,169 +1,169 @@ package de.elog.elReasoner; import java.io.File; import java.util.ArrayList; import org.semanticweb.owlapi.apibinding.OWLManager; import org.semanticweb.owlapi.model.AddAxiom; import org.semanticweb.owlapi.model.IRI; import org.semanticweb.owlapi.model.OWLAxiom; import org.semanticweb.owlapi.model.OWLClass; import org.semanticweb.owlapi.model.OWLDataFactory; import org.semanticweb.owlapi.model.OWLObjectIntersectionOf; import org.semanticweb.owlapi.model.OWLObjectProperty; import org.semanticweb.owlapi.model.OWLObjectPropertyExpression; import org.semanticweb.owlapi.model.OWLObjectSomeValuesFrom; import org.semanticweb.owlapi.model.OWLOntology; import org.semanticweb.owlapi.model.OWLOntologyCreationException; import org.semanticweb.owlapi.model.OWLOntologyManager; import org.semanticweb.owlapi.model.OWLOntologyStorageException; import org.semanticweb.owlapi.util.SimpleIRIMapper; import de.elog.Constants; public class OWLWriter { private OWLDataFactory factory; private OWLOntologyManager manager; public OWLWriter(){ manager = OWLManager.createOWLOntologyManager(); factory = manager.getOWLDataFactory(); } public OWLOntology write(IRI ontologyIRI, String filenameToSave, ArrayList<String> axioms) throws OWLOntologyCreationException, OWLOntologyStorageException{ // Create the document IRI for our ontology File fileToSave = new File(filenameToSave); - IRI documentIRI = IRI.create(fileToSave); + IRI documentIRI = IRI.create(fileToSave.toURI()); // Set up a mapping, which maps the ontology to the document IRI SimpleIRIMapper mapper = new SimpleIRIMapper(ontologyIRI, documentIRI); manager.addIRIMapper(mapper); // Now create the ontology - we use the ontology IRI (not the physical URI) OWLOntology ontology = manager.createOntology(ontologyIRI); for(String axiomWhole: axioms){ String[] axiom = axiomWhole.split("\\|"); OWLAxiom owlAxiom = null; if(axiom[0].equals("subsumes")){ owlAxiom = this.getSubsumes(axiom); }else if(axiom[0].equals("intersection")){ owlAxiom = this.getIntersection(axiom); }else if(axiom[0].equals("opsub")){ owlAxiom = this.getOpsub(axiom); }else if(axiom[0].equals("opsup")){ owlAxiom = this.getOpsup(axiom); }else if(axiom[0].equals("psubsumes")){ owlAxiom = this.getPsubsumes(axiom); }else if(axiom[0].equals("pcom")){ owlAxiom = this.getPcom(axiom); }else{ System.out.println("- " + axiomWhole); } if(owlAxiom!=null){ AddAxiom addAxiom = new AddAxiom(ontology, owlAxiom); manager.applyChange(addAxiom); } } // Now save the ontology. - manager.saveOntology(ontology); + manager.saveOntology(ontology, documentIRI); System.out.println("Filename of output: "+ filenameToSave); return ontology; } private OWLClass createClass(String name){ if(name.equals(Constants.BOTTOM_ELEMENT)){ return factory.getOWLNothing(); }else if(name.equals(Constants.TOP_ELEMENT)){ return factory.getOWLThing(); }else{ IRI iri = IRI.create(name); return factory.getOWLClass(iri); } } private OWLObjectProperty createObjectProperty(String name){ return factory.getOWLObjectProperty(IRI.create(name)); } private OWLAxiom getSubsumes(String[] components){ if(components[1].equals(components[2])) { return null; } return factory.getOWLSubClassOfAxiom(this.createClass(components[1]), this.createClass(components[2])); } private OWLAxiom getIntersection(String[] components){ OWLClass c1 = this.createClass(components[1]); OWLClass c2 = this.createClass(components[2]); OWLClass d = this.createClass(components[3]); if(d.equals(factory.getOWLNothing())){ return factory.getOWLDisjointClassesAxiom(c1, c2); }else{ OWLObjectIntersectionOf objectIntersectionOf = factory.getOWLObjectIntersectionOf(c1, c2); return factory.getOWLSubClassOfAxiom(objectIntersectionOf, d); } } /** * Exists R.C1 subclassof D * * @param components * @return */ private OWLAxiom getOpsub(String[] components){ OWLObjectProperty r = this.createObjectProperty(components[1]); OWLClass c1 = this.createClass(components[2]); OWLClass d = this.createClass(components[3]); OWLObjectSomeValuesFrom objectSomeValuesFrom = factory.getOWLObjectSomeValuesFrom(r, c1); return factory.getOWLSubClassOfAxiom(objectSomeValuesFrom, d); } /** * Exists R.C1 superclassof D * * which is equivalent to: * * D subclassof Exists R.C1 * * @param components * @return */ private OWLAxiom getOpsup(String[] components){ OWLObjectProperty r = this.createObjectProperty(components[1]); OWLClass c1 = this.createClass(components[2]); OWLClass d = this.createClass(components[3]); OWLObjectSomeValuesFrom objectSomeValuesFrom = factory.getOWLObjectSomeValuesFrom(r, c1); return factory.getOWLSubClassOfAxiom(d, objectSomeValuesFrom); } /** * * @param components * @return */ private OWLAxiom getPcom(String[] components){ OWLObjectPropertyExpression opExp1 = this.createObjectProperty(components[1]); OWLObjectPropertyExpression opExp2 = this.createObjectProperty(components[2]); ArrayList<OWLObjectPropertyExpression> opExpList = new ArrayList<OWLObjectPropertyExpression>(); opExpList.add(opExp1);opExpList.add(opExp2); OWLObjectPropertyExpression opSuper = this.createObjectProperty(components[3]); return factory.getOWLSubPropertyChainOfAxiom(opExpList, opSuper); } private OWLAxiom getPsubsumes(String[] components){ if(components[1].equals(components[2])) return null; return factory.getOWLSubObjectPropertyOfAxiom(this.createObjectProperty(components[1]), this.createObjectProperty(components[2])); } }
false
true
public OWLOntology write(IRI ontologyIRI, String filenameToSave, ArrayList<String> axioms) throws OWLOntologyCreationException, OWLOntologyStorageException{ // Create the document IRI for our ontology File fileToSave = new File(filenameToSave); IRI documentIRI = IRI.create(fileToSave); // Set up a mapping, which maps the ontology to the document IRI SimpleIRIMapper mapper = new SimpleIRIMapper(ontologyIRI, documentIRI); manager.addIRIMapper(mapper); // Now create the ontology - we use the ontology IRI (not the physical URI) OWLOntology ontology = manager.createOntology(ontologyIRI); for(String axiomWhole: axioms){ String[] axiom = axiomWhole.split("\\|"); OWLAxiom owlAxiom = null; if(axiom[0].equals("subsumes")){ owlAxiom = this.getSubsumes(axiom); }else if(axiom[0].equals("intersection")){ owlAxiom = this.getIntersection(axiom); }else if(axiom[0].equals("opsub")){ owlAxiom = this.getOpsub(axiom); }else if(axiom[0].equals("opsup")){ owlAxiom = this.getOpsup(axiom); }else if(axiom[0].equals("psubsumes")){ owlAxiom = this.getPsubsumes(axiom); }else if(axiom[0].equals("pcom")){ owlAxiom = this.getPcom(axiom); }else{ System.out.println("- " + axiomWhole); } if(owlAxiom!=null){ AddAxiom addAxiom = new AddAxiom(ontology, owlAxiom); manager.applyChange(addAxiom); } } // Now save the ontology. manager.saveOntology(ontology); System.out.println("Filename of output: "+ filenameToSave); return ontology; }
public OWLOntology write(IRI ontologyIRI, String filenameToSave, ArrayList<String> axioms) throws OWLOntologyCreationException, OWLOntologyStorageException{ // Create the document IRI for our ontology File fileToSave = new File(filenameToSave); IRI documentIRI = IRI.create(fileToSave.toURI()); // Set up a mapping, which maps the ontology to the document IRI SimpleIRIMapper mapper = new SimpleIRIMapper(ontologyIRI, documentIRI); manager.addIRIMapper(mapper); // Now create the ontology - we use the ontology IRI (not the physical URI) OWLOntology ontology = manager.createOntology(ontologyIRI); for(String axiomWhole: axioms){ String[] axiom = axiomWhole.split("\\|"); OWLAxiom owlAxiom = null; if(axiom[0].equals("subsumes")){ owlAxiom = this.getSubsumes(axiom); }else if(axiom[0].equals("intersection")){ owlAxiom = this.getIntersection(axiom); }else if(axiom[0].equals("opsub")){ owlAxiom = this.getOpsub(axiom); }else if(axiom[0].equals("opsup")){ owlAxiom = this.getOpsup(axiom); }else if(axiom[0].equals("psubsumes")){ owlAxiom = this.getPsubsumes(axiom); }else if(axiom[0].equals("pcom")){ owlAxiom = this.getPcom(axiom); }else{ System.out.println("- " + axiomWhole); } if(owlAxiom!=null){ AddAxiom addAxiom = new AddAxiom(ontology, owlAxiom); manager.applyChange(addAxiom); } } // Now save the ontology. manager.saveOntology(ontology, documentIRI); System.out.println("Filename of output: "+ filenameToSave); return ontology; }
diff --git a/src/main/java/me/captainbern/animationlib/utils/refs/PacketRef.java b/src/main/java/me/captainbern/animationlib/utils/refs/PacketRef.java index 3d3e0d0..b11720e 100644 --- a/src/main/java/me/captainbern/animationlib/utils/refs/PacketRef.java +++ b/src/main/java/me/captainbern/animationlib/utils/refs/PacketRef.java @@ -1,15 +1,15 @@ package me.captainbern.animationlib.utils.refs; import com.google.common.collect.BiMap; import me.captainbern.animationlib.reflection.ClassTemplate; import me.captainbern.animationlib.reflection.NMSClassTemplate; public class PacketRef { public static final ClassTemplate<Object> protocol = NMSClassTemplate.create("EnumProtocol"); public static BiMap getServerPacketRegistry(){ - return (BiMap) protocol.getField("h"); + return (BiMap) protocol.getField("h").get(null); } }
true
true
public static BiMap getServerPacketRegistry(){ return (BiMap) protocol.getField("h"); }
public static BiMap getServerPacketRegistry(){ return (BiMap) protocol.getField("h").get(null); }
diff --git a/src/com/dalthed/tucan/ui/Messages.java b/src/com/dalthed/tucan/ui/Messages.java index 7ee6cad..646eb2e 100644 --- a/src/com/dalthed/tucan/ui/Messages.java +++ b/src/com/dalthed/tucan/ui/Messages.java @@ -1,144 +1,145 @@ package com.dalthed.tucan.ui; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Iterator; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import android.content.Intent; import android.content.res.Configuration; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import com.bugsense.trace.BugSenseHandler; import com.dalthed.tucan.R; import com.dalthed.tucan.TuCanMobileActivity; import com.dalthed.tucan.TucanMobile; import com.dalthed.tucan.Connection.AnswerObject; import com.dalthed.tucan.Connection.CookieManager; import com.dalthed.tucan.Connection.RequestObject; import com.dalthed.tucan.Connection.SimpleSecureBrowser; public class Messages extends SimpleWebListActivity { private String UserName; private CookieManager localCookieManager; private static final String LOG_TAG = "TuCanMobile"; private String URLStringtoCall; private int mode=0; private ArrayList<String> MessageLink; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.messages); BugSenseHandler.setup(this,"ed5c1682"); String CookieHTTPString = getIntent().getExtras().getString("Cookie"); URLStringtoCall = getIntent().getExtras().getString("URL"); UserName = getIntent().getExtras().getString("UserName"); URL URLtoCall; try { URLtoCall = new URL(URLStringtoCall); localCookieManager = new CookieManager(); localCookieManager.generateManagerfromHTTPString( URLtoCall.getHost(), CookieHTTPString); callResultBrowser = new SimpleSecureBrowser( this); RequestObject thisRequest = new RequestObject(URLStringtoCall, localCookieManager, RequestObject.METHOD_GET, ""); callResultBrowser.execute(thisRequest); } catch (MalformedURLException e) { Log.e(LOG_TAG, e.getMessage()); } } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); setContentView(R.layout.messages); } class MessageAdapter extends ArrayAdapter<String>{ ArrayList<String> messageDate,messageAuthor; public MessageAdapter(ArrayList<String> messageTitle,ArrayList<String> messageDate,ArrayList<String> messageAuthor) { super(Messages.this,R.layout.row_vv_events,R.id.row_vv_veranst,messageTitle); this.messageAuthor=messageAuthor; this.messageDate=messageDate; } @Override public View getView(int position, View convertView, ViewGroup parent) { View row = super.getView(position, convertView, parent); TextView TypeTextView = (TextView) row.findViewById(R.id.row_vv_type); TextView DozentTextView = (TextView) row.findViewById(R.id.row_vv_dozent); TypeTextView.setText(messageDate.get(position)); DozentTextView.setText(messageAuthor.get(position)); return row; } } @Override protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); Intent MessageStartIntent = new Intent(Messages.this, SingleMessage.class); MessageStartIntent.putExtra("URL", TucanMobile.TUCAN_PROT + TucanMobile.TUCAN_HOST + MessageLink.get(position)); MessageStartIntent.putExtra("User", UserName); MessageStartIntent.putExtra("Cookie", localCookieManager .getCookieHTTPString(TucanMobile.TUCAN_HOST)); startActivity(MessageStartIntent); } @Override public void onPostExecute(AnswerObject result) { Document doc = Jsoup.parse(result.getHTML()); + sendHTMLatBug(result.getHTML()); if(doc.select("span.notLoggedText").text().length()>0){ Intent BackToLoginIntent = new Intent(this,TuCanMobileActivity.class); BackToLoginIntent.putExtra("lostSession", true); startActivity(BackToLoginIntent); } else { if(mode==0){ String AllMailLink = TucanMobile.TUCAN_PROT + TucanMobile.TUCAN_HOST + doc.select("div.tbcontrol").select("a").last().attr("href"); mode=1; SimpleSecureBrowser callOverviewBrowser = new SimpleSecureBrowser( this); RequestObject thisRequest = new RequestObject(AllMailLink, localCookieManager, RequestObject.METHOD_GET, ""); callOverviewBrowser.execute(thisRequest); } else { Iterator<Element> MessageRows = doc.select("tr.tbdata").iterator(); ArrayList<String> MessageDate = new ArrayList<String>(); ArrayList<String> MessageAuthor = new ArrayList<String>(); ArrayList<String> MessageTitle = new ArrayList<String>(); MessageLink = new ArrayList<String>(); while(MessageRows.hasNext()){ Element next = MessageRows.next(); Elements MessageCols = next.select("td"); if(MessageCols.size()>0){ MessageDate.add(MessageCols.get(1).text()+" - "+MessageCols.get(2).text()); MessageAuthor.add("Von: "+MessageCols.get(3).text()); MessageTitle.add(MessageCols.get(4).text()); MessageLink.add(MessageCols.get(4).select("a").attr("href")); } } MessageAdapter ListAdapter = new MessageAdapter(MessageTitle, MessageDate, MessageAuthor); setListAdapter(ListAdapter); } } } }
true
true
public void onPostExecute(AnswerObject result) { Document doc = Jsoup.parse(result.getHTML()); if(doc.select("span.notLoggedText").text().length()>0){ Intent BackToLoginIntent = new Intent(this,TuCanMobileActivity.class); BackToLoginIntent.putExtra("lostSession", true); startActivity(BackToLoginIntent); } else { if(mode==0){ String AllMailLink = TucanMobile.TUCAN_PROT + TucanMobile.TUCAN_HOST + doc.select("div.tbcontrol").select("a").last().attr("href"); mode=1; SimpleSecureBrowser callOverviewBrowser = new SimpleSecureBrowser( this); RequestObject thisRequest = new RequestObject(AllMailLink, localCookieManager, RequestObject.METHOD_GET, ""); callOverviewBrowser.execute(thisRequest); } else { Iterator<Element> MessageRows = doc.select("tr.tbdata").iterator(); ArrayList<String> MessageDate = new ArrayList<String>(); ArrayList<String> MessageAuthor = new ArrayList<String>(); ArrayList<String> MessageTitle = new ArrayList<String>(); MessageLink = new ArrayList<String>(); while(MessageRows.hasNext()){ Element next = MessageRows.next(); Elements MessageCols = next.select("td"); if(MessageCols.size()>0){ MessageDate.add(MessageCols.get(1).text()+" - "+MessageCols.get(2).text()); MessageAuthor.add("Von: "+MessageCols.get(3).text()); MessageTitle.add(MessageCols.get(4).text()); MessageLink.add(MessageCols.get(4).select("a").attr("href")); } } MessageAdapter ListAdapter = new MessageAdapter(MessageTitle, MessageDate, MessageAuthor); setListAdapter(ListAdapter); } } }
public void onPostExecute(AnswerObject result) { Document doc = Jsoup.parse(result.getHTML()); sendHTMLatBug(result.getHTML()); if(doc.select("span.notLoggedText").text().length()>0){ Intent BackToLoginIntent = new Intent(this,TuCanMobileActivity.class); BackToLoginIntent.putExtra("lostSession", true); startActivity(BackToLoginIntent); } else { if(mode==0){ String AllMailLink = TucanMobile.TUCAN_PROT + TucanMobile.TUCAN_HOST + doc.select("div.tbcontrol").select("a").last().attr("href"); mode=1; SimpleSecureBrowser callOverviewBrowser = new SimpleSecureBrowser( this); RequestObject thisRequest = new RequestObject(AllMailLink, localCookieManager, RequestObject.METHOD_GET, ""); callOverviewBrowser.execute(thisRequest); } else { Iterator<Element> MessageRows = doc.select("tr.tbdata").iterator(); ArrayList<String> MessageDate = new ArrayList<String>(); ArrayList<String> MessageAuthor = new ArrayList<String>(); ArrayList<String> MessageTitle = new ArrayList<String>(); MessageLink = new ArrayList<String>(); while(MessageRows.hasNext()){ Element next = MessageRows.next(); Elements MessageCols = next.select("td"); if(MessageCols.size()>0){ MessageDate.add(MessageCols.get(1).text()+" - "+MessageCols.get(2).text()); MessageAuthor.add("Von: "+MessageCols.get(3).text()); MessageTitle.add(MessageCols.get(4).text()); MessageLink.add(MessageCols.get(4).select("a").attr("href")); } } MessageAdapter ListAdapter = new MessageAdapter(MessageTitle, MessageDate, MessageAuthor); setListAdapter(ListAdapter); } } }
diff --git a/issues/bridge/FACES-1638-portlet/src/main/java/com/liferay/faces/issues/ModelManagedBean.java b/issues/bridge/FACES-1638-portlet/src/main/java/com/liferay/faces/issues/ModelManagedBean.java index b8d513742..211e571a0 100644 --- a/issues/bridge/FACES-1638-portlet/src/main/java/com/liferay/faces/issues/ModelManagedBean.java +++ b/issues/bridge/FACES-1638-portlet/src/main/java/com/liferay/faces/issues/ModelManagedBean.java @@ -1,44 +1,44 @@ /** * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved. * * 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. */ package com.liferay.faces.issues; import java.util.ArrayList; import java.util.List; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; /** * @author Neil Griffin */ @ManagedBean @ViewScoped public class ModelManagedBean { private List<Item> items; public List<Item> getItems() { if (items == null) { items = new ArrayList<Item>(); - items.add(new Item(1, "First Item")); - items.add(new Item(2, "Second Item")); - items.add(new Item(3, "Third Item")); + items.add(new Item(1, "First-Item")); + items.add(new Item(2, "Second-Item")); + items.add(new Item(3, "Third-Item")); } return items; } }
true
true
public List<Item> getItems() { if (items == null) { items = new ArrayList<Item>(); items.add(new Item(1, "First Item")); items.add(new Item(2, "Second Item")); items.add(new Item(3, "Third Item")); } return items; }
public List<Item> getItems() { if (items == null) { items = new ArrayList<Item>(); items.add(new Item(1, "First-Item")); items.add(new Item(2, "Second-Item")); items.add(new Item(3, "Third-Item")); } return items; }
diff --git a/src/main/java/com/treasure_data/bulk_import/prepare_parts/proc/CSVTimeColumnProc.java b/src/main/java/com/treasure_data/bulk_import/prepare_parts/proc/CSVTimeColumnProc.java index 0bb4505..b3b0a25 100644 --- a/src/main/java/com/treasure_data/bulk_import/prepare_parts/proc/CSVTimeColumnProc.java +++ b/src/main/java/com/treasure_data/bulk_import/prepare_parts/proc/CSVTimeColumnProc.java @@ -1,74 +1,72 @@ // // Treasure Data Bulk-Import Tool in Java // // Copyright (C) 2012 - 2013 Muga Nishizawa // // 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.treasure_data.bulk_import.prepare_parts.proc; import com.treasure_data.bulk_import.Config; import com.treasure_data.bulk_import.prepare_parts.PreparePartsException; import com.treasure_data.bulk_import.prepare_parts.ExtStrftime; public class CSVTimeColumnProc extends AbstractCSVColumnProc { protected ExtStrftime timeFormat; // TODO should change simple time format public CSVTimeColumnProc(int index, ExtStrftime timeFormat, com.treasure_data.bulk_import.prepare_parts.FileWriter writer) { super(index, Config.BI_PREPARE_PARTS_TIMECOLUMN_DEFAULTVALUE, writer); this.timeFormat = timeFormat; } @Override public void executeKey() throws PreparePartsException { writer.writeString(Config.BI_PREPARE_PARTS_TIMECOLUMN_DEFAULTVALUE); } @Override public Object executeValue(Object value) throws PreparePartsException { // TODO refine!!!! - Long v = null; + Long v = 0L; if (value instanceof Long) { v = (Long) value; } else if (value instanceof String) { String sv = (String) value; try { v = Long.parseLong(sv); } catch (NumberFormatException e) { throw new PreparePartsException(String.format( "'%s' could not be parsed as an Long", value)); } if (v == null && timeFormat != null) { v = timeFormat.getTime(sv); - } else { - return 0; } } else { final String actualClassName = value.getClass().getName(); throw new PreparePartsException(String.format( "the input value should be of type Long or String but is of type %s", actualClassName)); } writer.writeLong(v); return v; } }
false
true
public Object executeValue(Object value) throws PreparePartsException { // TODO refine!!!! Long v = null; if (value instanceof Long) { v = (Long) value; } else if (value instanceof String) { String sv = (String) value; try { v = Long.parseLong(sv); } catch (NumberFormatException e) { throw new PreparePartsException(String.format( "'%s' could not be parsed as an Long", value)); } if (v == null && timeFormat != null) { v = timeFormat.getTime(sv); } else { return 0; } } else { final String actualClassName = value.getClass().getName(); throw new PreparePartsException(String.format( "the input value should be of type Long or String but is of type %s", actualClassName)); } writer.writeLong(v); return v; }
public Object executeValue(Object value) throws PreparePartsException { // TODO refine!!!! Long v = 0L; if (value instanceof Long) { v = (Long) value; } else if (value instanceof String) { String sv = (String) value; try { v = Long.parseLong(sv); } catch (NumberFormatException e) { throw new PreparePartsException(String.format( "'%s' could not be parsed as an Long", value)); } if (v == null && timeFormat != null) { v = timeFormat.getTime(sv); } } else { final String actualClassName = value.getClass().getName(); throw new PreparePartsException(String.format( "the input value should be of type Long or String but is of type %s", actualClassName)); } writer.writeLong(v); return v; }
diff --git a/src/be/ibridge/kettle/spoon/Spoon.java b/src/be/ibridge/kettle/spoon/Spoon.java index b97133f7..6fc6f861 100644 --- a/src/be/ibridge/kettle/spoon/Spoon.java +++ b/src/be/ibridge/kettle/spoon/Spoon.java @@ -1,4778 +1,4783 @@ /********************************************************************** ** ** ** This code belongs to the KETTLE project. ** ** ** ** Kettle, from version 2.2 on, is released into the public domain ** ** under the Lesser GNU Public License (LGPL). ** ** ** ** For more details, please read the document LICENSE.txt, included ** ** in this project ** ** ** ** http://www.kettle.be ** ** [email protected] ** ** ** **********************************************************************/ package be.ibridge.kettle.spoon; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.Properties; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.dialogs.MessageDialogWithToggle; import org.eclipse.jface.wizard.Wizard; import org.eclipse.jface.wizard.WizardDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CTabFolder; import org.eclipse.swt.custom.CTabItem; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.dnd.Clipboard; import org.eclipse.swt.dnd.DND; import org.eclipse.swt.dnd.DragSource; import org.eclipse.swt.dnd.DragSourceEvent; import org.eclipse.swt.dnd.DragSourceListener; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.ShellAdapter; import org.eclipse.swt.events.ShellEvent; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Cursor; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.ImageData; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.printing.Printer; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.MenuItem; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.ToolBar; import org.eclipse.swt.widgets.ToolItem; import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.TreeItem; import org.w3c.dom.Document; import org.w3c.dom.Node; import be.ibridge.kettle.core.AddUndoPositionInterface; import be.ibridge.kettle.core.Const; import be.ibridge.kettle.core.DragAndDropContainer; import be.ibridge.kettle.core.GUIResource; import be.ibridge.kettle.core.KettleVariables; import be.ibridge.kettle.core.LogWriter; import be.ibridge.kettle.core.NotePadMeta; import be.ibridge.kettle.core.Point; import be.ibridge.kettle.core.PrintSpool; import be.ibridge.kettle.core.Props; import be.ibridge.kettle.core.Row; import be.ibridge.kettle.core.SourceToTargetMapping; import be.ibridge.kettle.core.TransAction; import be.ibridge.kettle.core.WindowProperty; import be.ibridge.kettle.core.XMLHandler; import be.ibridge.kettle.core.XMLHandlerCache; import be.ibridge.kettle.core.XMLTransfer; import be.ibridge.kettle.core.clipboard.ImageDataTransfer; import be.ibridge.kettle.core.database.Database; import be.ibridge.kettle.core.database.DatabaseMeta; import be.ibridge.kettle.core.dialog.CheckResultDialog; import be.ibridge.kettle.core.dialog.DatabaseDialog; import be.ibridge.kettle.core.dialog.DatabaseExplorerDialog; import be.ibridge.kettle.core.dialog.EnterMappingDialog; import be.ibridge.kettle.core.dialog.EnterOptionsDialog; import be.ibridge.kettle.core.dialog.EnterSearchDialog; import be.ibridge.kettle.core.dialog.EnterStringsDialog; import be.ibridge.kettle.core.dialog.ErrorDialog; import be.ibridge.kettle.core.dialog.PreviewRowsDialog; import be.ibridge.kettle.core.dialog.SQLEditor; import be.ibridge.kettle.core.dialog.SQLStatementsDialog; import be.ibridge.kettle.core.dialog.ShowBrowserDialog; import be.ibridge.kettle.core.dialog.Splash; import be.ibridge.kettle.core.exception.KettleDatabaseException; import be.ibridge.kettle.core.exception.KettleException; import be.ibridge.kettle.core.reflection.StringSearchResult; import be.ibridge.kettle.core.util.EnvUtil; import be.ibridge.kettle.core.value.Value; import be.ibridge.kettle.core.wizards.createdatabase.CreateDatabaseWizard; import be.ibridge.kettle.job.JobEntryLoader; import be.ibridge.kettle.pan.CommandLineOption; import be.ibridge.kettle.repository.PermissionMeta; import be.ibridge.kettle.repository.RepositoriesMeta; import be.ibridge.kettle.repository.Repository; import be.ibridge.kettle.repository.RepositoryDirectory; import be.ibridge.kettle.repository.RepositoryMeta; import be.ibridge.kettle.repository.UserInfo; import be.ibridge.kettle.repository.dialog.RepositoriesDialog; import be.ibridge.kettle.repository.dialog.RepositoryExplorerDialog; import be.ibridge.kettle.repository.dialog.SelectObjectDialog; import be.ibridge.kettle.repository.dialog.UserDialog; import be.ibridge.kettle.spoon.dialog.AnalyseImpactProgressDialog; import be.ibridge.kettle.spoon.dialog.CheckTransProgressDialog; import be.ibridge.kettle.spoon.dialog.GetSQLProgressDialog; import be.ibridge.kettle.spoon.dialog.ShowCreditsDialog; import be.ibridge.kettle.spoon.dialog.TipsDialog; import be.ibridge.kettle.spoon.wizards.CopyTableWizardPage1; import be.ibridge.kettle.spoon.wizards.CopyTableWizardPage2; import be.ibridge.kettle.spoon.wizards.CopyTableWizardPage3; import be.ibridge.kettle.trans.DatabaseImpact; import be.ibridge.kettle.trans.StepLoader; import be.ibridge.kettle.trans.StepPlugin; import be.ibridge.kettle.trans.TransHopMeta; import be.ibridge.kettle.trans.TransMeta; import be.ibridge.kettle.trans.dialog.TransDialog; import be.ibridge.kettle.trans.dialog.TransHopDialog; import be.ibridge.kettle.trans.dialog.TransLoadProgressDialog; import be.ibridge.kettle.trans.dialog.TransSaveProgressDialog; import be.ibridge.kettle.trans.step.BaseStep; import be.ibridge.kettle.trans.step.StepDialogInterface; import be.ibridge.kettle.trans.step.StepMeta; import be.ibridge.kettle.trans.step.StepMetaInterface; import be.ibridge.kettle.trans.step.selectvalues.SelectValuesMeta; import be.ibridge.kettle.trans.step.tableinput.TableInputMeta; import be.ibridge.kettle.trans.step.tableoutput.TableOutputMeta; import be.ibridge.kettle.version.BuildVersion; /** * This class handles the main window of the Spoon graphical transformation editor. * * @author Matt * @since 16-may-2003 * * Add i18n support * import the package:be.ibridge.kettle.i18n.Messages * @modified by vitoelv since 07-Feb-2006 */ public class Spoon implements AddUndoPositionInterface { public static final String APP_NAME = Messages.getString("Spoon.Application.Name"); //"Spoon"; private LogWriter log; private Display disp; private Shell shell; private boolean destroy; private SpoonGraph spoongraph; private SpoonLog spoonlog; private SashForm sashform; public CTabFolder tabfolder; public Row variables; /** * These are the arguments that were given at Spoon launch time... */ private String[] arguments; /** * A list of remarks on the current Transformation... */ private ArrayList remarks; /** * A list of impacts of the current transformation on the used databases. */ private ArrayList impact; /** * Indicates whether or not an impact analyses has already run. */ private boolean impactHasRun; private boolean stopped; private Cursor cursor_hourglass, cursor_hand; public Props props; public Repository rep; public TransMeta transMeta; private ToolBar tBar; private Menu msFile; private MenuItem miFileSep3; private MenuItem miEditUndo, miEditRedo; private Tree selectionTree; private TreeItem tiConn, tiHops, tiStep, tiBase, tiPlug; private Tree pluginHistoryTree; private Listener lsNew, lsEdit, lsDupe, lsCopy, lsDel, lsSQL, lsCache, lsExpl; private SelectionAdapter lsEditDef, lsEditSel; public static final String STRING_CONNECTIONS = Messages.getString("Spoon.STRING_CONNECTIONS"); //"Connections"; public static final String STRING_STEPS = Messages.getString("Spoon.STRING_STEPS"); //"Steps"; public static final String STRING_HOPS = Messages.getString("Spoon.STRING_HOPS"); //"Hops"; public static final String STRING_BASE = Messages.getString("Spoon.STRING_BASE"); //"Base step types"; public static final String STRING_PLUGIN = Messages.getString("Spoon.STRING_PLUGIN"); //"Plugin step types"; public static final String STRING_HISTORY = Messages.getString("Spoon.STRING_HISTORY"); //"Step creation history"; private static final String APPL_TITLE = APP_NAME; public KeyAdapter defKeys; public KeyAdapter modKeys; private SpoonHistory spoonhist; private Menu mBar; private Composite tabComp; private SashForm leftSash; public Spoon(LogWriter l, Repository rep) { this(l, null, null, rep); } public Spoon(LogWriter l, Display d, Repository rep) { this(l, d, null, rep); } public Spoon(LogWriter log, Display d, TransMeta ti, Repository rep) { this.log = log; this.rep = rep; if (d!=null) { disp=d; destroy=false; } else { disp=new Display(); destroy=true; } shell=new Shell(disp); shell.setText(APPL_TITLE); FormLayout layout = new FormLayout(); layout.marginWidth = 0; layout.marginHeight = 0; shell.setLayout (layout); // INIT Data structure if (ti==null) { this.transMeta = new TransMeta(); } else { this.transMeta = ti; } if (!Props.isInitialized()) { //log.logDetailed(toString(), "Load properties for Spoon..."); log.logDetailed(toString(),Messages.getString("Spoon.Log.LoadProperties")); Props.init(disp, Props.TYPE_PROPERTIES_SPOON); // things to remember... } props=Props.getInstance(); // Load settings in the props loadSettings(); remarks = new ArrayList(); impact = new ArrayList(); impactHasRun = false; // Clean out every time we start, auto-loading etc, is not a good idea // If they are needed that often, set them in the kettle.properties file // variables = new Row(); // props.setLook(shell); shell.setImage(GUIResource.getInstance().getImageSpoon()); cursor_hourglass = new Cursor(disp, SWT.CURSOR_WAIT); cursor_hand = new Cursor(disp, SWT.CURSOR_HAND); // widgets = new WidgetContainer(); defKeys = new KeyAdapter() { public void keyPressed(KeyEvent e) { // ESC --> Unselect All steps if (e.keyCode == SWT.ESC) { spoongraph.clearSettings(); transMeta.unselectAll(); refreshGraph(); }; // F3 --> createDatabaseWizard if (e.keyCode == SWT.F3) { createDatabaseWizard(); } // F4 --> copyTableWizard if (e.keyCode == SWT.F4) { copyTableWizard(); } // F5 --> refresh if (e.keyCode == SWT.F5) { refreshGraph(); refreshTree(true); } // F6 --> show last impact analyses if (e.keyCode == SWT.F6) { showLastImpactAnalyses(); } // F7 --> show last verify results if (e.keyCode == SWT.F7) { showLastTransCheck(); } // F8 --> show last preview if (e.keyCode == SWT.F8) { spoonlog.showPreview(); } // F9 --> run if (e.keyCode == SWT.F9) { tabfolder.setSelection(1); spoonlog.startstop(); } // F10 --> preview if (e.keyCode == SWT.F10) { spoonlog.preview(); } // F11 --> Verify if (e.keyCode == SWT.F11) { checkTrans(); spoongraph.clearSettings(); } // CTRL-A --> Select All steps if ((int)e.character == 1) { transMeta.selectAll(); }; // CTRL-D --> Disconnect from repository if ((int)e.character == 4) { closeRepository(); spoongraph.clearSettings(); }; // CTRL-E --> Explore the repository if ((int)e.character == 5) { exploreRepository(); spoongraph.clearSettings(); }; // CTRL-F --> Java examination if ((int)e.character == 6 && (( e.stateMask&SWT.CONTROL)!=0) && (( e.stateMask&SWT.ALT)==0) ) { searchMetaData(); spoongraph.clearSettings(); }; // CTRL-I --> Import from XML file && (e.keyCode&SWT.CONTROL)!=0 if ((int)e.character == 9 && (( e.stateMask&SWT.CONTROL)!=0) && (( e.stateMask&SWT.ALT)==0) ) { openFile(true); spoongraph.clearSettings(); }; // CTRL-J --> Get variables if ((int)e.character == 10 && (( e.stateMask&SWT.CONTROL)!=0) && (( e.stateMask&SWT.ALT)==0) ) { getVariables(); spoongraph.clearSettings(); }; // CTRL-N --> new if ((int)e.character == 14) { newFile(); spoongraph.clearSettings(); } // CTRL-O --> open if ((int)e.character == 15) { openFile(false); spoongraph.clearSettings(); } // CTRL-P --> print if ((int)e.character == 16) { printFile(); spoongraph.clearSettings(); } // CTRL-Q --> Impact analyses if ((int)e.character == 17) { analyseImpact(); spoongraph.clearSettings(); } // CTRL-R --> Connect to repository if ((int)e.character == 18) { openRepository(); spoongraph.clearSettings(); }; // CTRL-S --> save if ((int)e.character == 19) { saveFile(); spoongraph.clearSettings(); } // CTRL-T --> transformation if ((int)e.character == 20) { setTrans(); spoongraph.clearSettings(); } // CTRL-Y --> redo action if ((int)e.character == 25) { redoAction(); spoongraph.clearSettings(); } // CTRL-Z --> undo action if ((int)e.character == 26) { spoongraph.clearSettings(); undoAction(); } // CTRL-SHIFT-I --> Copy Transformation Image to clipboard if ((int)e.character == 9 && (( e.stateMask&SWT.CONTROL)!=0) && (( e.stateMask&SWT.ALT)!=0)) { copyTransformationImage(); } // System.out.println("(int)e.character = "+(int)e.character+", keycode = "+e.keyCode+", stateMask="+e.stateMask); } }; modKeys = new KeyAdapter() { public void keyPressed(KeyEvent e) { spoongraph.shift = (e.keyCode == SWT.SHIFT ); spoongraph.control = (e.keyCode == SWT.CONTROL); } public void keyReleased(KeyEvent e) { spoongraph.shift = (e.keyCode == SWT.SHIFT ); spoongraph.control = (e.keyCode == SWT.CONTROL); } }; addBar(); FormData fdBar = new FormData(); fdBar.left = new FormAttachment(0, 0); fdBar.top = new FormAttachment(0, 0); tBar.setLayoutData(fdBar); sashform = new SashForm(shell, SWT.HORIZONTAL); // props.setLook(sashform); FormData fdSash = new FormData(); fdSash.left = new FormAttachment(0, 0); fdSash.top = new FormAttachment(tBar, 0); fdSash.bottom = new FormAttachment(100, 0); fdSash.right = new FormAttachment(100, 0); sashform.setLayoutData(fdSash); addMenu(); addTree(); addTabs(); setTreeImages(); // In case someone dares to press the [X] in the corner ;-) shell.addShellListener( new ShellAdapter() { public void shellClosed(ShellEvent e) { e.doit=quitFile(); } } ); shell.layout(); // Set the shell size, based upon previous time... WindowProperty winprop = props.getScreen(APPL_TITLE); if (winprop!=null) winprop.setShell(shell); else { shell.pack(); shell.setMaximized(true); // Default = maximized! } } /** * Search the transformation meta-data. * */ public void searchMetaData() { EnterSearchDialog esd = new EnterSearchDialog(shell); if (esd.open()) { String filterString = esd.getFilterString(); String filter = filterString; if (filter!=null) filter = filter.toUpperCase(); List stringList = transMeta.getStringList(esd.isSearchingSteps(), esd.isSearchingDatabases(), esd.isSearchingNotes()); ArrayList rows = new ArrayList(); for (int i=0;i<stringList.size();i++) { StringSearchResult result = (StringSearchResult) stringList.get(i); boolean add = Const.isEmpty(filter); if (filter!=null && result.getString().toUpperCase().indexOf(filter)>=0) add=true; if (filter!=null && result.getFieldName().toUpperCase().indexOf(filter)>=0) add=true; if (filter!=null && result.getParentObject().toString().toUpperCase().indexOf(filter)>=0) add=true; if (add) rows.add(result.toRow()); } if (rows.size()!=0) { PreviewRowsDialog prd = new PreviewRowsDialog(shell, SWT.NONE, "String searcher", rows); prd.open(); } else { MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION); mb.setMessage(Messages.getString("Spoon.Dialog.NothingFound.Message")); // Nothing found that matches your criteria mb.setText(Messages.getString("Spoon.Dialog.NothingFound.Title")); // Sorry! mb.open(); } } } public void getVariables() { Properties sp = new Properties(); KettleVariables kettleVariables = KettleVariables.getInstance(); sp.putAll(kettleVariables.getProperties()); sp.putAll(System.getProperties()); List list = transMeta.getUsedVariables(); for (int i=0;i<list.size();i++) { String varName = (String)list.get(i); String varValue = sp.getProperty(varName, ""); System.out.println("variable ["+varName+"] is defined as : "+varValue); if (variables.searchValueIndex(varName)<0) { variables.addValue(new Value(varName, varValue)); } } // Now ask the use for more info on these! EnterStringsDialog esd = new EnterStringsDialog(shell, SWT.NONE, variables); esd.setReadOnly(false); if (esd.open()!=null) { for (int i=0;i<variables.size();i++) { Value varval = variables.getValue(i); if (!Const.isEmpty(varval.getString())) { kettleVariables.setVariable(varval.getName(), varval.getString()); System.out.println("Variable ${"+varval.getName()+"} set to ["+varval.getString()+"] for thread ["+Thread.currentThread()+"]"); } } } } public void clear() { remarks = new ArrayList(); impact = new ArrayList(); impactHasRun = false; transMeta.clear(); XMLHandlerCache.getInstance().clear(); setUndoMenu(); } public void open() { shell.open(); // Shared database entries to load from repository? loadRepositoryObjects(); // What plugins did we use previously? refreshPluginHistory(); // Perhaps the transformation contains elements at startup? if (transMeta.nrSteps()>0 || transMeta.nrDatabases()>0 || transMeta.nrTransHops()>0) { refreshTree(true); // Do a complete refresh then... } transMeta.clearChanged(); // Clear changed: they were artificial (databases loaded, etc.) setShellText(); if (props.showTips()) { TipsDialog tip = new TipsDialog(shell, props); tip.open(); } } public boolean readAndDispatch () { return disp.readAndDispatch(); } /** * @return check whether or not the application was stopped. */ public boolean isStopped() { return stopped; } /** * @param stopped True to stop this application. */ public void setStopped(boolean stopped) { this.stopped = stopped; } /** * @param destroy Whether or not to distroy the display. */ public void setDestroy(boolean destroy) { this.destroy = destroy; } /** * @return Returns whether or not we should distroy the display. */ public boolean doDestroy() { return destroy; } /** * @param arguments The arguments to set. */ public void setArguments(String[] arguments) { this.arguments = arguments; } /** * @return Returns the arguments. */ public String[] getArguments() { return arguments; } public synchronized void dispose() { setStopped(true); cursor_hand.dispose(); cursor_hourglass.dispose(); if (destroy && !disp.isDisposed()) disp.dispose(); } public boolean isDisposed() { return disp.isDisposed(); } public void sleep() { disp.sleep(); } public void addMenu() { if (mBar!=null) { mBar.dispose(); } mBar = new Menu(shell, SWT.BAR); shell.setMenuBar(mBar); // main File menu... MenuItem mFile = new MenuItem(mBar, SWT.CASCADE); //mFile.setText("&File"); mFile.setText(Messages.getString("Spoon.Menu.File") ); msFile = new Menu(shell, SWT.DROP_DOWN); mFile.setMenu(msFile); MenuItem miFileNew = new MenuItem(msFile, SWT.CASCADE); miFileNew.setText(Messages.getString("Spoon.Menu.File.New")); //miFileNew.setText("&New \tCTRL-N"); MenuItem miFileOpen = new MenuItem(msFile, SWT.CASCADE); miFileOpen.setText(Messages.getString("Spoon.Menu.File.Open")); //&Open \tCTRL-O MenuItem miFileImport = new MenuItem(msFile, SWT.CASCADE); miFileImport.setText(Messages.getString("Spoon.Menu.File.Import")); //"&Import from an XML file\tCTRL-I" MenuItem miFileExport = new MenuItem(msFile, SWT.CASCADE); miFileExport.setText(Messages.getString("Spoon.Menu.File.Export")); //&Export to an XML file MenuItem miFileSave = new MenuItem(msFile, SWT.CASCADE); miFileSave.setText(Messages.getString("Spoon.Menu.File.Save")); //"&Save \tCTRL-S" MenuItem miFileSaveAs = new MenuItem(msFile, SWT.CASCADE); miFileSaveAs.setText(Messages.getString("Spoon.Menu.File.SaveAs")); //"Save &as..." new MenuItem(msFile, SWT.SEPARATOR); MenuItem miFilePrint = new MenuItem(msFile, SWT.CASCADE); miFilePrint.setText(Messages.getString("Spoon.Menu.File.Print")); //"&Print \tCTRL-P" new MenuItem(msFile, SWT.SEPARATOR); MenuItem miFileQuit = new MenuItem(msFile, SWT.CASCADE); miFileQuit.setText(Messages.getString("Spoon.Menu.File.Quit")); //miFileQuit.setText("&Quit"); miFileSep3 = new MenuItem(msFile, SWT.SEPARATOR); addMenuLast(); Listener lsFileOpen = new Listener() { public void handleEvent(Event e) { openFile(false); } }; Listener lsFileImport = new Listener() { public void handleEvent(Event e) { openFile(true); } }; Listener lsFileExport = new Listener() { public void handleEvent(Event e) { saveXMLFile(); } }; Listener lsFileNew = new Listener() { public void handleEvent(Event e) { newFile(); } }; Listener lsFileSave = new Listener() { public void handleEvent(Event e) { saveFile(); } }; Listener lsFileSaveAs = new Listener() { public void handleEvent(Event e) { saveFileAs(); } }; Listener lsFilePrint = new Listener() { public void handleEvent(Event e) { printFile(); } }; Listener lsFileQuit = new Listener() { public void handleEvent(Event e) { quitFile(); } }; miFileOpen .addListener (SWT.Selection, lsFileOpen ); miFileImport .addListener (SWT.Selection, lsFileImport ); miFileExport .addListener (SWT.Selection, lsFileExport ); miFileNew .addListener (SWT.Selection, lsFileNew ); miFileSave .addListener (SWT.Selection, lsFileSave ); miFileSaveAs .addListener (SWT.Selection, lsFileSaveAs ); miFilePrint .addListener (SWT.Selection, lsFilePrint ); miFileQuit .addListener (SWT.Selection, lsFileQuit ); // main Edit menu... MenuItem mEdit = new MenuItem(mBar, SWT.CASCADE); mEdit.setText(Messages.getString("Spoon.Menu.Edit")); //&Edit Menu msEdit = new Menu(shell, SWT.DROP_DOWN); mEdit.setMenu(msEdit); miEditUndo = new MenuItem(msEdit, SWT.CASCADE); miEditRedo = new MenuItem(msEdit, SWT.CASCADE); setUndoMenu(); new MenuItem(msEdit, SWT.SEPARATOR); MenuItem miEditSearch = new MenuItem(msEdit, SWT.CASCADE); miEditSearch.setText(Messages.getString("Spoon.Menu.Edit.Search")); //Search Metadata \tCTRL-F MenuItem miEditVars = new MenuItem(msEdit, SWT.CASCADE); miEditVars.setText(Messages.getString("Spoon.Menu.Edit.Variables")); //Edit/Enter variables \tCTRL-F new MenuItem(msEdit, SWT.SEPARATOR); MenuItem miEditUnselectAll = new MenuItem(msEdit, SWT.CASCADE); miEditUnselectAll.setText(Messages.getString("Spoon.Menu.Edit.ClearSelection")); //&Clear selection \tESC MenuItem miEditSelectAll = new MenuItem(msEdit, SWT.CASCADE); miEditSelectAll.setText(Messages.getString("Spoon.Menu.Edit.SelectAllSteps")); //"&Select all steps \tCTRL-A" new MenuItem(msEdit, SWT.SEPARATOR); MenuItem miEditCopy = new MenuItem(msEdit, SWT.CASCADE); miEditCopy.setText(Messages.getString("Spoon.Menu.Edit.CopyToClipboard")); //Copy selected steps to clipboard\tCTRL-C MenuItem miEditPaste = new MenuItem(msEdit, SWT.CASCADE); miEditPaste.setText(Messages.getString("Spoon.Menu.Edit.PasteFromClipboard")); //Paste steps from clipboard\tCTRL-V new MenuItem(msEdit, SWT.SEPARATOR); MenuItem miEditRefresh = new MenuItem(msEdit, SWT.CASCADE); miEditRefresh.setText(Messages.getString("Spoon.Menu.Edit.Refresh")); //&Refresh \tF5 new MenuItem(msEdit, SWT.SEPARATOR); MenuItem miEditOptions = new MenuItem(msEdit, SWT.CASCADE); miEditOptions.setText(Messages.getString("Spoon.Menu.Edit.Options")); //&Options... Listener lsEditUndo = new Listener() { public void handleEvent(Event e) { undoAction(); } }; Listener lsEditRedo = new Listener() { public void handleEvent(Event e) { redoAction(); } }; Listener lsEditSearch = new Listener() { public void handleEvent(Event e) { searchMetaData(); } }; Listener lsEditVars = new Listener() { public void handleEvent(Event e) { getVariables(); } }; Listener lsEditUnselectAll = new Listener() { public void handleEvent(Event e) { editUnselectAll(); } }; Listener lsEditSelectAll = new Listener() { public void handleEvent(Event e) { editSelectAll(); } }; Listener lsEditOptions = new Listener() { public void handleEvent(Event e) { editOptions(); } }; miEditUndo .addListener(SWT.Selection, lsEditUndo); miEditRedo .addListener(SWT.Selection, lsEditRedo); miEditSearch .addListener(SWT.Selection, lsEditSearch); miEditVars .addListener(SWT.Selection, lsEditVars); miEditUnselectAll.addListener(SWT.Selection, lsEditUnselectAll); miEditSelectAll .addListener(SWT.Selection, lsEditSelectAll); miEditOptions .addListener(SWT.Selection, lsEditOptions); // main Repository menu... MenuItem mRep = new MenuItem(mBar, SWT.CASCADE); mRep.setText(Messages.getString("Spoon.Menu.Repository")); //&Repository Menu msRep = new Menu(shell, SWT.DROP_DOWN); mRep.setMenu(msRep); MenuItem miRepConnect = new MenuItem(msRep, SWT.CASCADE); miRepConnect.setText(Messages.getString("Spoon.Menu.Repository.ConnectToRepository")); //&Connect to repository \tCTRL-R MenuItem miRepDisconnect = new MenuItem(msRep, SWT.CASCADE); miRepDisconnect.setText(Messages.getString("Spoon.Menu.Repository.DisconnectRepository")); //&Disconnect repository \tCTRL-D MenuItem miRepExplore = new MenuItem(msRep, SWT.CASCADE); miRepExplore.setText(Messages.getString("Spoon.Menu.Repository.ExploreRepository")); //&Explore repository \tCTRL-E new MenuItem(msRep, SWT.SEPARATOR); MenuItem miRepUser = new MenuItem(msRep, SWT.CASCADE); miRepUser.setText(Messages.getString("Spoon.Menu.Repository.EditCurrentUser")); //&Edit current user\tCTRL-U Listener lsRepConnect = new Listener() { public void handleEvent(Event e) { openRepository(); } }; Listener lsRepDisconnect = new Listener() { public void handleEvent(Event e) { closeRepository(); } }; Listener lsRepExplore = new Listener() { public void handleEvent(Event e) { exploreRepository(); } }; Listener lsRepUser = new Listener() { public void handleEvent(Event e) { editRepositoryUser();} }; miRepConnect .addListener (SWT.Selection, lsRepConnect ); miRepDisconnect .addListener (SWT.Selection, lsRepDisconnect); miRepExplore .addListener (SWT.Selection, lsRepExplore ); miRepUser .addListener (SWT.Selection, lsRepUser ); // main Transformation menu... MenuItem mTrans = new MenuItem(mBar, SWT.CASCADE); mTrans.setText(Messages.getString("Spoon.Menu.Transformation")); //&Transformation Menu msTrans = new Menu(shell, SWT.DROP_DOWN ); mTrans.setMenu(msTrans); MenuItem miTransRun = new MenuItem(msTrans, SWT.CASCADE); miTransRun .setText(Messages.getString("Spoon.Menu.Transformation.Run"));//&Run \tF9 MenuItem miTransPreview = new MenuItem(msTrans, SWT.CASCADE); miTransPreview.setText(Messages.getString("Spoon.Menu.Transformation.Preview"));//&Preview \tF10 MenuItem miTransCheck = new MenuItem(msTrans, SWT.CASCADE); miTransCheck .setText(Messages.getString("Spoon.Menu.Transformation.Verify"));//&Verify \tF11 MenuItem miTransImpact = new MenuItem(msTrans, SWT.CASCADE); miTransImpact .setText(Messages.getString("Spoon.Menu.Transformation.Impact"));//&Impact MenuItem miTransSQL = new MenuItem(msTrans, SWT.CASCADE); miTransSQL .setText(Messages.getString("Spoon.Menu.Transformation.GetSQL"));//&Get SQL new MenuItem(msTrans, SWT.SEPARATOR); MenuItem miLastImpact = new MenuItem(msTrans, SWT.CASCADE); miLastImpact .setText(Messages.getString("Spoon.Menu.Transformation.ShowLastImpactAnalyses"));//Show last impact analyses \tF6 MenuItem miLastCheck = new MenuItem(msTrans, SWT.CASCADE); miLastCheck .setText(Messages.getString("Spoon.Menu.Transformation.ShowLastVerifyResults"));//Show last verify results \tF7 MenuItem miLastPreview = new MenuItem(msTrans, SWT.CASCADE); miLastPreview .setText(Messages.getString("Spoon.Menu.Transformation.ShowLastPreviewResults"));//Show last preview results \tF8 new MenuItem(msTrans, SWT.SEPARATOR); MenuItem miTransCopy = new MenuItem(msTrans, SWT.CASCADE); miTransCopy .setText(Messages.getString("Spoon.Menu.Transformation.CopyTransformationToClipboard"));//&Copy transformation to clipboard MenuItem miTransPaste = new MenuItem(msTrans, SWT.CASCADE); miTransPaste .setText(Messages.getString("Spoon.Menu.Transformation.PasteTransformationFromClipboard"));//P&aste transformation from clipboard MenuItem miTransImage = new MenuItem(msTrans, SWT.CASCADE); miTransImage .setText(Messages.getString("Spoon.Menu.Transformation.CopyTransformationImageClipboard"));//Copy the transformation image clipboard \tCTRL-ALT-I new MenuItem(msTrans, SWT.SEPARATOR); MenuItem miTransDetails = new MenuItem(msTrans, SWT.CASCADE); miTransDetails.setText(Messages.getString("Spoon.Menu.Transformation.Settings"));//&Settings... \tCTRL-T Listener lsTransDetails = new Listener() { public void handleEvent(Event e) { setTrans(); } }; Listener lsTransRun = new Listener() { public void handleEvent(Event e) { tabfolder.setSelection(1); spoonlog.startstop(); } }; Listener lsTransPreview = new Listener() { public void handleEvent(Event e) { spoonlog.preview(); } }; Listener lsTransCheck = new Listener() { public void handleEvent(Event e) { checkTrans(); } }; Listener lsTransImpact = new Listener() { public void handleEvent(Event e) { analyseImpact(); } }; Listener lsTransSQL = new Listener() { public void handleEvent(Event e) { getSQL(); } }; Listener lsLastPreview = new Listener() { public void handleEvent(Event e) { spoonlog.showPreview(); } }; Listener lsLastCheck = new Listener() { public void handleEvent(Event e) { showLastTransCheck(); } }; Listener lsLastImpact = new Listener() { public void handleEvent(Event e) { showLastImpactAnalyses(); } }; Listener lsTransCopy = new Listener() { public void handleEvent(Event e) { copyTransformation(); } }; Listener lsTransImage = new Listener() { public void handleEvent(Event e) { copyTransformationImage(); } }; Listener lsTransPaste = new Listener() { public void handleEvent(Event e) { pasteTransformation(); } }; miTransDetails.addListener(SWT.Selection, lsTransDetails); miTransRun .addListener(SWT.Selection, lsTransRun); miTransPreview.addListener(SWT.Selection, lsTransPreview); miTransCheck .addListener(SWT.Selection, lsTransCheck); miTransImpact .addListener(SWT.Selection, lsTransImpact); miTransSQL .addListener(SWT.Selection, lsTransSQL); miLastPreview .addListener(SWT.Selection, lsLastPreview); miLastCheck .addListener(SWT.Selection, lsLastCheck); miLastImpact .addListener(SWT.Selection, lsLastImpact); miTransCopy .addListener(SWT.Selection, lsTransCopy); miTransPaste .addListener(SWT.Selection, lsTransPaste); miTransImage .addListener(SWT.Selection, lsTransImage); // Wizard menu MenuItem mWizard = new MenuItem(mBar, SWT.CASCADE); mWizard.setText(Messages.getString("Spoon.Menu.Wizard")); //"&Wizard" Menu msWizard = new Menu(shell, SWT.DROP_DOWN ); mWizard.setMenu(msWizard); MenuItem miWizardNewConnection = new MenuItem(msWizard, SWT.CASCADE); miWizardNewConnection.setText(Messages.getString("Spoon.Menu.Wizard.CreateDatabaseConnectionWizard"));//&Create database connection wizard...\tF3 Listener lsWizardNewConnection= new Listener() { public void handleEvent(Event e) { createDatabaseWizard(); } }; miWizardNewConnection.addListener(SWT.Selection, lsWizardNewConnection); MenuItem miWizardCopyTable = new MenuItem(msWizard, SWT.CASCADE); miWizardCopyTable.setText(Messages.getString("Spoon.Menu.Wizard.CopyTableWizard"));//&Copy table wizard...\tF4 Listener lsWizardCopyTable= new Listener() { public void handleEvent(Event e) { copyTableWizard(); } }; miWizardCopyTable.addListener(SWT.Selection, lsWizardCopyTable); // main Help menu... MenuItem mHelp = new MenuItem(mBar, SWT.CASCADE); mHelp.setText(Messages.getString("Spoon.Menu.Help")); //"&Help" Menu msHelp = new Menu(shell, SWT.DROP_DOWN ); mHelp.setMenu(msHelp); MenuItem miHelpCredit = new MenuItem(msHelp, SWT.CASCADE); miHelpCredit.setText(Messages.getString("Spoon.Menu.Help.Credits"));//&Credits Listener lsHelpCredit = new Listener() { public void handleEvent(Event e) { ShowCreditsDialog scd = new ShowCreditsDialog(shell, props, GUIResource.getInstance().getImageCredits()); scd.open(); } }; miHelpCredit.addListener (SWT.Selection, lsHelpCredit ); MenuItem miHelpTOTD = new MenuItem(msHelp, SWT.CASCADE); miHelpTOTD.setText(Messages.getString("Spoon.Menu.Help.Tip"));//&Tip of the day Listener lsHelpTOTD = new Listener() { public void handleEvent(Event e) { TipsDialog td = new TipsDialog(shell, props); td.open(); } }; miHelpTOTD.addListener (SWT.Selection, lsHelpTOTD ); new MenuItem(msHelp, SWT.SEPARATOR); MenuItem miHelpAbout = new MenuItem(msHelp, SWT.CASCADE); miHelpAbout.setText(Messages.getString("Spoon.Menu.About"));//"&About" Listener lsHelpAbout = new Listener() { public void handleEvent(Event e) { helpAbout(); } }; miHelpAbout.addListener (SWT.Selection, lsHelpAbout ); } private void addMenuLast() { int idx = msFile.indexOf(miFileSep3); int max = msFile.getItemCount(); // Remove everything until end... for (int i=max-1;i>idx;i--) { MenuItem mi = msFile.getItem(i); mi.dispose(); } // Previously loaded files... String lf[] = props.getLastFiles(); String ld[] = props.getLastDirs(); boolean lt[] = props.getLastTypes(); String lr[] = props.getLastRepositories(); for (int i=0;i<lf.length;i++) { MenuItem miFileLast = new MenuItem(msFile, SWT.CASCADE); char chr = (char)('1'+i ); int accel = SWT.CTRL | chr; String repository = ( lr[i]!=null && lr[i].length()>0 ) ? ( "["+lr[i]+"] " ) : ""; String filename = RepositoryDirectory.DIRECTORY_SEPARATOR + lf[i]; if (!lt[i]) filename = lf[i]; if (!ld[i].equals(RepositoryDirectory.DIRECTORY_SEPARATOR)) { filename=ld[i]+filename; } if (i<9) { miFileLast.setAccelerator(accel); miFileLast.setText("&"+chr+" "+repository+filename+ "\tCTRL-"+chr); } else { miFileLast.setText(" "+repository+filename); } final String fn = lf[i]; // filename final String fd = ld[i]; // Repository directory ... final boolean ft = lt[i]; // type: true=repository, false=file final String fr = lr[i]; // repository name Listener lsFileLast = new Listener() { public void handleEvent(Event e) { if (showChangedWarning()) { // If the file comes from a repository and it's not the same as // the one we're connected to, ask for a username/password! // boolean noRepository=false; if (ft && (rep==null || !rep.getRepositoryInfo().getName().equalsIgnoreCase(fr) )) { int perms[] = new int[] { PermissionMeta.TYPE_PERMISSION_TRANSFORMATION }; RepositoriesDialog rd = new RepositoriesDialog(disp, SWT.NONE, perms, Messages.getString("Spoon.Application.Name")); //RepositoriesDialog.ToolName="Spoon" rd.setRepositoryName(fr); if (rd.open()) { // Close the previous connection... if (rep!=null) rep.disconnect(); rep = new Repository(log, rd.getRepository(), rd.getUser()); try { rep.connect(APP_NAME); } catch(KettleException ke) { rep=null; new ErrorDialog(shell, props, Messages.getString("Spoon.Dialog.UnableConnectRepository.Title"), Messages.getString("Spoon.Dialog.UnableConnectRepository.Message"), ke); //$NON-NLS-1$ //$NON-NLS-2$ } } else { noRepository=true; } } if (ft) { if (!noRepository && rep!=null && rep.getRepositoryInfo().getName().equalsIgnoreCase(fr)) { // OK, we're connected to the new repository... // Load the transformation... RepositoryDirectory fdRepdir = rep.getDirectoryTree().findDirectory(fd); TransLoadProgressDialog tlpd = new TransLoadProgressDialog(shell, rep, fn, fdRepdir); TransMeta transInfo = tlpd.open(); if (transInfo!=null) { transMeta = transInfo; transMeta.clearChanged(); props.addLastFile(Props.TYPE_PROPERTIES_SPOON, fn, fdRepdir.getPath(), true, rep.getName()); } } else { clear(); MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR ); mb.setMessage(Messages.getString("Spoon.Dialog.UnableLoadTransformation.Message"));//Can't load this transformation. Please connect to the correct repository first. mb.setText(Messages.getString("Spoon.Dialog.UnableLoadTransformation.Title"));//Error! mb.open(); } } else // Load from XML! { try { transMeta = new TransMeta(fn); transMeta.clearChanged(); transMeta.setFilename(fn); props.addLastFile(Props.TYPE_PROPERTIES_SPOON, fn, null, false, null); } catch(KettleException ke) { clear(); //"Error loading transformation", "I was unable to load this transformation from the XML file because of an error" new ErrorDialog(shell, props, Messages.getString("Spoon.Dialog.LoadTransformationError.Title"), Messages.getString("Spoon.Dialog.LoadTransformationError.Message"), ke); } } setShellText(); addMenuLast(); refreshTree(); refreshGraph(); refreshHistory(); } } }; miFileLast.addListener(SWT.Selection, lsFileLast); } } private void addBar() { tBar = new ToolBar(shell, SWT.HORIZONTAL | SWT.FLAT ); // props.setLook(tBar); final ToolItem tiFileNew = new ToolItem(tBar, SWT.PUSH); final Image imFileNew = new Image(disp, getClass().getResourceAsStream(Const.IMAGE_DIRECTORY+"new.png")); tiFileNew.setImage(imFileNew); tiFileNew.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { newFile(); }}); tiFileNew.setToolTipText(Messages.getString("Spoon.Tooltip.NewTranformation"));//New transformation, clear all settings final ToolItem tiFileOpen = new ToolItem(tBar, SWT.PUSH); final Image imFileOpen = new Image(disp, getClass().getResourceAsStream(Const.IMAGE_DIRECTORY+"open.png")); tiFileOpen.setImage(imFileOpen); tiFileOpen.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { openFile(false); }}); tiFileOpen.setToolTipText(Messages.getString("Spoon.Tooltip.OpenTranformation"));//Open tranformation final ToolItem tiFileSave = new ToolItem(tBar, SWT.PUSH); final Image imFileSave = new Image(disp, getClass().getResourceAsStream(Const.IMAGE_DIRECTORY+"save.png")); tiFileSave.setImage(imFileSave); tiFileSave.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { saveFile(); }}); tiFileSave.setToolTipText(Messages.getString("Spoon.Tooltip.SaveCurrentTranformation"));//Save current transformation final ToolItem tiFileSaveAs = new ToolItem(tBar, SWT.PUSH); final Image imFileSaveAs = new Image(disp, getClass().getResourceAsStream(Const.IMAGE_DIRECTORY+"saveas.png")); tiFileSaveAs.setImage(imFileSaveAs); tiFileSaveAs.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { saveFileAs(); }}); tiFileSaveAs.setToolTipText(Messages.getString("Spoon.Tooltip.SaveDifferentNameTranformation"));//Save transformation with different name new ToolItem(tBar, SWT.SEPARATOR); final ToolItem tiFilePrint = new ToolItem(tBar, SWT.PUSH); final Image imFilePrint = new Image(disp, getClass().getResourceAsStream(Const.IMAGE_DIRECTORY+"print.png")); tiFilePrint.setImage(imFilePrint); tiFilePrint.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { printFile(); }}); tiFilePrint.setToolTipText(Messages.getString("Spoon.Tooltip.Print"));//Print new ToolItem(tBar, SWT.SEPARATOR); final ToolItem tiFileRun = new ToolItem(tBar, SWT.PUSH); final Image imFileRun = new Image(disp, getClass().getResourceAsStream(Const.IMAGE_DIRECTORY+"run.png")); tiFileRun.setImage(imFileRun); tiFileRun.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { tabfolder.setSelection(1); spoonlog.startstop(); }}); tiFileRun.setToolTipText(Messages.getString("Spoon.Tooltip.RunTranformation"));//Run this transformation final ToolItem tiFilePreview = new ToolItem(tBar, SWT.PUSH); final Image imFilePreview = new Image(disp, getClass().getResourceAsStream(Const.IMAGE_DIRECTORY+"preview.png")); tiFilePreview.setImage(imFilePreview); tiFilePreview.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { spoonlog.preview(); }}); tiFilePreview.setToolTipText(Messages.getString("Spoon.Tooltip.PreviewTranformation"));//Preview this transformation final ToolItem tiFileReplay = new ToolItem(tBar, SWT.PUSH); final Image imFileReplay = new Image(disp, getClass().getResourceAsStream(Const.IMAGE_DIRECTORY+"replay.png")); tiFileReplay.setImage(imFileReplay); tiFileReplay.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { tabfolder.setSelection(1); spoonlog.startstopReplay(); }}); tiFileReplay.setToolTipText("Replay this transformation"); new ToolItem(tBar, SWT.SEPARATOR); final ToolItem tiFileCheck = new ToolItem(tBar, SWT.PUSH); final Image imFileCheck = new Image(disp, getClass().getResourceAsStream(Const.IMAGE_DIRECTORY+"check.png")); tiFileCheck.setImage(imFileCheck); tiFileCheck.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { checkTrans(); }}); tiFileCheck.setToolTipText(Messages.getString("Spoon.Tooltip.VerifyTranformation"));//Verify this transformation new ToolItem(tBar, SWT.SEPARATOR); final ToolItem tiImpact = new ToolItem(tBar, SWT.PUSH); final Image imImpact = new Image(disp, getClass().getResourceAsStream(Const.IMAGE_DIRECTORY+"impact.png")); // Can't seem to get the transparency correct for this image! ImageData idImpact = imImpact.getImageData(); int impactPixel = idImpact.palette.getPixel(new RGB(255, 255, 255)); idImpact.transparentPixel = impactPixel; Image imImpact2 = new Image(disp, idImpact); tiImpact.setImage(imImpact2); tiImpact.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { analyseImpact(); }}); tiImpact.setToolTipText(Messages.getString("Spoon.Tooltip.AnalyzeTranformation"));//Analyze the impact of this transformation on the database(s) new ToolItem(tBar, SWT.SEPARATOR); final ToolItem tiSQL = new ToolItem(tBar, SWT.PUSH); final Image imSQL = new Image(disp, getClass().getResourceAsStream(Const.IMAGE_DIRECTORY+"SQLbutton.png")); // Can't seem to get the transparency correct for this image! ImageData idSQL = imSQL.getImageData(); int sqlPixel= idSQL.palette.getPixel(new RGB(255, 255, 255)); idSQL.transparentPixel = sqlPixel; Image imSQL2= new Image(disp, idSQL); tiSQL.setImage(imSQL2); tiSQL.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { getSQL(); }}); tiSQL.setToolTipText(Messages.getString("Spoon.Tooltip.GenerateSQLForTranformation"));//Generate the SQL needed to run this transformation tBar.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { imFileNew.dispose(); imFileOpen.dispose(); imFileSave.dispose(); imFileSaveAs.dispose(); } } ); tBar.addKeyListener(defKeys); tBar.addKeyListener(modKeys); tBar.pack(); } private void addTree() { if (leftSash!=null) { leftSash.dispose(); } // Split the left side of the screen in half leftSash = new SashForm(sashform, SWT.VERTICAL); // Now set up the main CSH tree selectionTree = new Tree(leftSash, SWT.SINGLE | SWT.BORDER); props.setLook(selectionTree); selectionTree.setLayout(new FillLayout()); tiConn = new TreeItem(selectionTree, SWT.NONE); tiConn.setText(STRING_CONNECTIONS); tiStep = new TreeItem(selectionTree, SWT.NONE); tiStep.setText(STRING_STEPS); tiHops = new TreeItem(selectionTree, SWT.NONE); tiHops.setText(STRING_HOPS); tiBase = new TreeItem(selectionTree, SWT.NONE); tiBase.setText(STRING_BASE); tiPlug = new TreeItem(selectionTree, SWT.NONE); tiPlug.setText(STRING_PLUGIN); // Fill the base components... StepLoader steploader = StepLoader.getInstance(); StepPlugin basesteps[] = steploader.getStepsWithType(StepPlugin.TYPE_NATIVE); String basecat[] = steploader.getCategories(StepPlugin.TYPE_NATIVE); TreeItem tiBaseCat[] = new TreeItem[basecat.length]; for (int i=0;i<basecat.length;i++) { tiBaseCat[i] = new TreeItem(tiBase, SWT.NONE); tiBaseCat[i].setText(basecat[i]); for (int j=0;j<basesteps.length;j++) { if (basesteps[j].getCategory().equalsIgnoreCase(basecat[i])) { TreeItem ti = new TreeItem(tiBaseCat[i], 0); ti.setText(basesteps[j].getDescription()); } } } // Show the plugins... StepPlugin plugins[] = steploader.getStepsWithType(StepPlugin.TYPE_PLUGIN); String plugcat[] = steploader.getCategories(StepPlugin.TYPE_PLUGIN); TreeItem tiPlugCat[] = new TreeItem[plugcat.length]; for (int i=0;i<plugcat.length;i++) { tiPlugCat[i] = new TreeItem(tiPlug, SWT.NONE); tiPlugCat[i].setText(plugcat[i]); for (int j=0;j<plugins.length;j++) { if (plugins[j].getCategory().equalsIgnoreCase(plugcat[i])) { TreeItem ti = new TreeItem(tiPlugCat[i], 0); ti.setText(plugins[j].getDescription()); } } } tiConn.setExpanded(true); tiStep.setExpanded(false); tiBase.setExpanded(true); tiPlug.setExpanded(true); addToolTipsToTree(selectionTree); // Popup-menu selection lsNew = new Listener() { public void handleEvent(Event e) { newSelected(); } }; lsEdit = new Listener() { public void handleEvent(Event e) { editSelected(); } }; lsDupe = new Listener() { public void handleEvent(Event e) { dupeSelected(); } }; lsCopy = new Listener() { public void handleEvent(Event e) { clipSelected(); } }; lsDel = new Listener() { public void handleEvent(Event e) { delSelected(); } }; lsSQL = new Listener() { public void handleEvent(Event e) { sqlSelected(); } }; lsCache = new Listener() { public void handleEvent(Event e) { clearDBCache(); } }; lsExpl = new Listener() { public void handleEvent(Event e) { exploreDB(); } }; // Default selection (double-click, enter) lsEditDef = new SelectionAdapter() { public void widgetDefaultSelected(SelectionEvent e){ editSelected(); } }; //lsNewDef = new SelectionAdapter() { public void widgetDefaultSelected(SelectionEvent e){ newSelected(); } }; lsEditSel = new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { setMenu(e); } }; // Add all the listeners... selectionTree.addSelectionListener(lsEditDef); // double click somewhere in the tree... //tCSH.addSelectionListener(lsNewDef); // double click somewhere in the tree... selectionTree.addSelectionListener(lsEditSel); // Keyboard shortcuts! selectionTree.addKeyListener(defKeys); selectionTree.addKeyListener(modKeys); // Set a listener on the tree addDragSourceToTree(selectionTree); // OK, now add a list of often-used icons to the bottom of the tree... pluginHistoryTree = new Tree(leftSash, SWT.SINGLE ); // Add tooltips for history tree too addToolTipsToTree(pluginHistoryTree); // Set the same listener on this tree addDragSourceToTree(pluginHistoryTree); leftSash.setWeights(new int[] { 70, 30 } ); } private void addToolTipsToTree(Tree tree) { tree.addListener(SWT.MouseHover, new Listener() { public void handleEvent(Event e) { String tooltip=null; Tree tree = (Tree)e.widget; TreeItem item = tree.getItem(new org.eclipse.swt.graphics.Point(e.x, e.y)); if (item!=null) { StepLoader steploader = StepLoader.getInstance(); StepPlugin sp = steploader.findStepPluginWithDescription(item.getText()); if (sp!=null) { tooltip = sp.getTooltip(); } else if (item.getText().equalsIgnoreCase(STRING_BASE) || item.getText().equalsIgnoreCase(STRING_PLUGIN) ) { tooltip=Messages.getString("Spoon.Tooltip.SelectStepType",Const.CR); //"Select one of the step types listed below and"+Const.CR+"drag it onto the graphical view tab to the right."; } } tree.setToolTipText(tooltip); } } ); } private void addDragSourceToTree(Tree tree) { final Tree fTree = tree; // Drag & Drop for steps Transfer[] ttypes = new Transfer[] { XMLTransfer.getInstance() }; DragSource ddSource = new DragSource(fTree, DND.DROP_MOVE); ddSource.setTransfer(ttypes); ddSource.addDragListener(new DragSourceListener() { public void dragStart(DragSourceEvent event){ } public void dragSetData(DragSourceEvent event) { TreeItem ti[] = fTree.getSelection(); if (ti.length>0) { String data = null; int type = 0; String ts[] = Const.getTreeStrings(ti[0]); if (ts!=null && ts.length > 0) { // Drop of existing hidden step onto canvas? if (ts[0].equalsIgnoreCase(STRING_STEPS)) { type = DragAndDropContainer.TYPE_STEP; data=ti[0].getText(); // name of the step. } else if ( ts[0].equalsIgnoreCase(STRING_BASE) || ts[0].equalsIgnoreCase(STRING_PLUGIN) || ts[0].equalsIgnoreCase(STRING_HISTORY) ) { type = DragAndDropContainer.TYPE_BASE_STEP_TYPE; data=ti[0].getText(); // Step type } else if (ts[0].equalsIgnoreCase(STRING_CONNECTIONS)) { type = DragAndDropContainer.TYPE_DATABASE_CONNECTION; data=ti[0].getText(); // Database connection name to use } else if (ts[0].equalsIgnoreCase(STRING_HOPS)) { type = DragAndDropContainer.TYPE_TRANS_HOP; data=ti[0].getText(); // nothing for really ;-) } else { event.doit=false; return; // ignore anything else you drag. } event.data = new DragAndDropContainer(type, data); } } else // Nothing got dragged, only can happen on OSX :-) { event.doit=false; } } public void dragFinished(DragSourceEvent event) {} } ); } public void refreshPluginHistory() { pluginHistoryTree.removeAll(); TreeItem tiMain = new TreeItem(pluginHistoryTree, SWT.NONE); tiMain.setText(STRING_HISTORY); List pluginHistory = props.getPluginHistory(); for (int i=0;i<pluginHistory.size();i++) { String pluginID = (String)pluginHistory.get(i); StepPlugin stepPlugin = StepLoader.getInstance().findStepPluginWithID(pluginID); if (stepPlugin!=null) { Image image = (Image) GUIResource.getInstance().getImagesSteps().get(pluginID); TreeItem ti = new TreeItem(tiMain, SWT.NONE); ti.setText(stepPlugin.getDescription()); ti.setImage(image); } } tiMain.setExpanded(true); } private void setMenu(SelectionEvent e) { TreeItem ti = (TreeItem)e.item; String strti = ti.getText(); Tree root = ti.getParent(); log.logDebug(toString(), Messages.getString("Spoon.Log.ClickedOn") +ti.getText());//Clicked on TreeItem sel[] = root.getSelection(); Menu mCSH = new Menu(shell, SWT.POP_UP); // Find the level we clicked on: Top level (only NEW in the menu) or below (edit, insert, ...) TreeItem parent = ti.getParentItem(); if (parent==null) // Top level { if (!strti.equalsIgnoreCase(STRING_BASE) && !strti.equalsIgnoreCase(STRING_PLUGIN)) { MenuItem miNew = new MenuItem(mCSH, SWT.PUSH); miNew.setText(Messages.getString("Spoon.Menu.Popup.BASE.New"));//"New" miNew.addListener( SWT.Selection, lsNew ); } if (strti.equalsIgnoreCase(STRING_STEPS)) { MenuItem miNew = new MenuItem(mCSH, SWT.PUSH); miNew.setText(Messages.getString("Spoon.Menu.Popup.STEPS.SortSteps"));//Sort steps miNew.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent arg0) { transMeta.sortSteps(); refreshTree(true); } }); } if (strti.equalsIgnoreCase(STRING_HOPS)) { MenuItem miNew = new MenuItem(mCSH, SWT.PUSH); miNew.setText(Messages.getString("Spoon.Menu.Popup.HOPS.SortHops"));//Sort hops miNew.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent arg0) { transMeta.sortHops(); refreshTree(true); } }); } if (strti.equalsIgnoreCase(STRING_CONNECTIONS)) { MenuItem miNew = new MenuItem(mCSH, SWT.PUSH); miNew.setText(Messages.getString("Spoon.Menu.Popup.CONNECTIONS.NewConnectionWizard"));//New Connection Wizard miNew.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent arg0) { createDatabaseWizard(); } } ); MenuItem miCache = new MenuItem(mCSH, SWT.PUSH); miCache.setText(Messages.getString("Spoon.Menu.Popup.CONNECTIONS.ClearDBCacheComplete"));//Clear complete DB Cache miCache.addListener( SWT.Selection, lsCache ); } } else { String strparent = parent.getText(); if (strparent.equalsIgnoreCase(STRING_CONNECTIONS)) { MenuItem miNew = new MenuItem(mCSH, SWT.PUSH); miNew.setText(Messages.getString("Spoon.Menu.Popup.CONNECTIONS.New"));//New MenuItem miEdit = new MenuItem(mCSH, SWT.PUSH); miEdit.setText(Messages.getString("Spoon.Menu.Popup.CONNECTIONS.Edit"));//Edit MenuItem miDupe = new MenuItem(mCSH, SWT.PUSH); miDupe.setText(Messages.getString("Spoon.Menu.Popup.CONNECTIONS.Duplicate"));//Duplicate MenuItem miCopy = new MenuItem(mCSH, SWT.PUSH); miCopy.setText(Messages.getString("Spoon.Menu.Popup.CONNECTIONS.CopyToClipboard"));//Copy to clipboard MenuItem miDel = new MenuItem(mCSH, SWT.PUSH); miDel.setText(Messages.getString("Spoon.Menu.Popup.CONNECTIONS.Delete"));//Delete new MenuItem(mCSH, SWT.SEPARATOR); MenuItem miSQL = new MenuItem(mCSH, SWT.PUSH); miSQL.setText(Messages.getString("Spoon.Menu.Popup.CONNECTIONS.SQLEditor"));//SQL Editor MenuItem miCache= new MenuItem(mCSH, SWT.PUSH); miCache.setText(Messages.getString("Spoon.Menu.Popup.CONNECTIONS.ClearDBCache")+ti.getText());//Clear DB Cache of new MenuItem(mCSH, SWT.SEPARATOR); MenuItem miExpl = new MenuItem(mCSH, SWT.PUSH); miExpl.setText(Messages.getString("Spoon.Menu.Popup.CONNECTIONS.Explore"));//Explore // disable for now if the connection is an SAP R/3 type of database... DatabaseMeta dbMeta = transMeta.findDatabase(strti); if (dbMeta==null || dbMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_SAPR3) miExpl.setEnabled(false); miNew.addListener( SWT.Selection, lsNew ); miEdit.addListener(SWT.Selection, lsEdit ); miDupe.addListener(SWT.Selection, lsDupe ); miCopy.addListener(SWT.Selection, lsCopy ); miDel.addListener(SWT.Selection, lsDel ); miSQL.addListener(SWT.Selection, lsSQL ); miCache.addListener(SWT.Selection, lsCache); miExpl.addListener(SWT.Selection, lsExpl); } if (strparent.equalsIgnoreCase(STRING_STEPS)) { if (sel.length==2) { MenuItem miNewHop = new MenuItem(mCSH, SWT.PUSH); miNewHop.setText(Messages.getString("Spoon.Menu.Popup.STEPS.NewHop"));//New Hop miNewHop.addListener(SWT.Selection, lsNew); } MenuItem miEdit = new MenuItem(mCSH, SWT.PUSH); miEdit.setText(Messages.getString("Spoon.Menu.Popup.STEPS.Edit"));//Edit MenuItem miDupe = new MenuItem(mCSH, SWT.PUSH); miDupe.setText(Messages.getString("Spoon.Menu.Popup.STEPS.Duplicate"));//Duplicate MenuItem miDel = new MenuItem(mCSH, SWT.PUSH); miDel.setText(Messages.getString("Spoon.Menu.Popup.STEPS.Delete"));//Delete miEdit.addListener(SWT.Selection, lsEdit ); miDupe.addListener(SWT.Selection, lsDupe ); miDel.addListener(SWT.Selection, lsDel ); } if (strparent.equalsIgnoreCase(STRING_HOPS)) { MenuItem miEdit = new MenuItem(mCSH, SWT.PUSH); miEdit.setText(Messages.getString("Spoon.Menu.Popup.HOPS.Edit"));//Edit MenuItem miDel = new MenuItem(mCSH, SWT.PUSH); miDel.setText(Messages.getString("Spoon.Menu.Popup.HOPS.Delete"));//Delete miEdit.addListener( SWT.Selection, lsEdit ); miDel.addListener ( SWT.Selection, lsDel ); } TreeItem grandparent = parent.getParentItem(); if (grandparent!=null) { String strgrandparent = grandparent.getText(); if (strgrandparent.equalsIgnoreCase(STRING_BASE) || strgrandparent.equalsIgnoreCase(STRING_PLUGIN)) { MenuItem miNew = new MenuItem(mCSH, SWT.PUSH); miNew.setText(Messages.getString("Spoon.Menu.Popup.BASE_PLUGIN.New"));//New miNew.addListener( SWT.Selection, lsNew ); } } } selectionTree.setMenu(mCSH); } private void addTabs() { if (tabComp!=null) { tabComp.dispose(); } tabComp = new Composite(sashform, SWT.BORDER ); props.setLook(tabComp); FormLayout childLayout = new FormLayout(); childLayout.marginWidth = 0; childLayout.marginHeight = 0; tabComp.setLayout(childLayout); tabfolder= new CTabFolder(tabComp, SWT.BORDER); props.setLook(tabfolder, Props.WIDGET_STYLE_TAB); FormData fdTabfolder = new FormData(); fdTabfolder.left = new FormAttachment(0, 0); fdTabfolder.right = new FormAttachment(100, 0); fdTabfolder.top = new FormAttachment(0, 0); fdTabfolder.bottom = new FormAttachment(100, 0); tabfolder.setLayoutData(fdTabfolder); CTabItem tiTabsGraph = new CTabItem(tabfolder, SWT.NONE); tiTabsGraph.setText(Messages.getString("Spoon.Title.GraphicalView"));//"Graphical view" tiTabsGraph.setToolTipText(Messages.getString("Spoon.Tooltip.DisplaysTransformationGraphical"));//Displays the transformation graphically. CTabItem tiTabsList = new CTabItem(tabfolder, SWT.NULL); tiTabsList.setText(Messages.getString("Spoon.Title.LogView"));//Log view tiTabsList.setToolTipText(Messages.getString("Spoon.Tooltip.DisplaysTransformationLog"));//Displays the log of the running transformation. CTabItem tiTabsHist = new CTabItem(tabfolder, SWT.NULL); tiTabsHist.setText(Messages.getString("Spoon.Title.LogHistory"));//Log view tiTabsHist.setToolTipText(Messages.getString("Spoon.Tooltip.DisplaysHistoryLogging"));//Displays the history of previous transformation runs. spoongraph = new SpoonGraph(tabfolder, SWT.V_SCROLL | SWT.H_SCROLL | SWT.NO_BACKGROUND, log, this); spoonlog = new SpoonLog(tabfolder, SWT.NONE, this, log, null); spoonhist = new SpoonHistory(tabfolder, SWT.NONE, this, log, null, spoonlog, shell); tabfolder.addKeyListener(defKeys); tabfolder.addKeyListener(modKeys); SpoonHistoryRefresher spoonHistoryRefresher = new SpoonHistoryRefresher(tiTabsHist, spoonhist); tabfolder.addSelectionListener(spoonHistoryRefresher); spoonlog.setSpoonHistoryRefresher(spoonHistoryRefresher); tiTabsGraph.setControl(spoongraph); tiTabsList.setControl(spoonlog); tiTabsHist.setControl(spoonhist); tabfolder.setSelection(0); sashform.addKeyListener(defKeys); sashform.addKeyListener(modKeys); int weights[] = props.getSashWeights(); sashform.setWeights(weights); sashform.setVisible(true); } public String getRepositoryName() { if (rep==null) return null; return rep.getRepositoryInfo().getName(); } public void newSelected() { log.logDebug(toString(), Messages.getString("Spoon.Log.NewSelected"));//"New Selected" // Determine what menu we selected from... TreeItem ti[] = selectionTree.getSelection(); // Then call newConnection or newTrans if (ti.length>=1) { String name = ti[0].getText(); TreeItem parent = ti[0].getParentItem(); if (parent == null) { log.logDebug(toString(), Messages.getString("Spoon.Log.ElementHasNoParent"));//Element has no parent if (name.equalsIgnoreCase(STRING_CONNECTIONS)) newConnection(); if (name.equalsIgnoreCase(STRING_HOPS )) newHop(); if (name.equalsIgnoreCase(STRING_STEPS )) { MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION); mb.setMessage(Messages.getString("Spoon.Dialog.WarningCreateNewSteps.Message"));//Please use the 'Base step types' below to create new steps. mb.setText(Messages.getString("Spoon.Dialog.WarningCreateNewSteps.Title"));//Tip! mb.open(); } //refreshTree(); } else { String strparent = parent.getText(); log.logDebug(toString(), Messages.getString("Spoon.Log.ElementHasParent")+strparent);//Element has parent: if (strparent.equalsIgnoreCase(STRING_CONNECTIONS)) newConnection(); if (strparent.equalsIgnoreCase(STRING_STEPS )) { log.logDebug(toString(), Messages.getString("Spoon.Log.NewHop"));//New hop! StepMeta from = transMeta.findStep( ti[0].getText() ); StepMeta to = transMeta.findStep( ti[1].getText() ); if (from!=null && to!=null) newHop(from, to); } TreeItem grandparent = parent.getParentItem(); if (grandparent!=null) { String strgrandparent = grandparent.getText(); if (strgrandparent.equalsIgnoreCase(STRING_BASE) || strgrandparent.equalsIgnoreCase(STRING_PLUGIN)) { newStep(); } } } } } public void editSelected() { // Determine what menu we selected from... TreeItem ti[] = selectionTree.getSelection(); // Then call editConnection or editStep or editTrans if (ti.length==1) { String name = ti[0].getText(); TreeItem parent = ti[0].getParentItem(); if (parent != null) { log.logDebug(toString(), Messages.getString("Spoon.Log.EDIT.ElementHasParent"));//(EDIT) Element has parent. String strparent = parent.getText(); if (strparent.equalsIgnoreCase(STRING_CONNECTIONS)) editConnection(name); if (strparent.equalsIgnoreCase(STRING_STEPS )) editStep(name); if (strparent.equalsIgnoreCase(STRING_HOPS )) editHop(name); TreeItem grandparent = parent.getParentItem(); if (grandparent!=null) { String strgrandparent = grandparent.getText(); if (strgrandparent.equalsIgnoreCase(STRING_BASE ) || strgrandparent.equalsIgnoreCase(STRING_PLUGIN ) ) { newStep(); } } } else { log.logDebug(toString(), Messages.getString("Spoon.Log.ElementHasNoParent"));//Element has no parent if (name.equalsIgnoreCase(STRING_CONNECTIONS)) newConnection(); if (name.equalsIgnoreCase(STRING_HOPS )) newHop(); } } } public void dupeSelected() { // Determine what menu we selected from... TreeItem ti[] = selectionTree.getSelection(); // Then call editConnection or editStep or editTrans if (ti.length==1) { String name = ti[0].getText(); TreeItem parent = ti[0].getParentItem(); if (parent != null) { log.logDebug(toString(), Messages.getString("Spoon.Log.DUPE.ElementHasParent"));//"(DUPE) Element has parent." String type = parent.getText(); if (type.equalsIgnoreCase(STRING_CONNECTIONS)) dupeConnection(name); if (type.equalsIgnoreCase(STRING_STEPS )) dupeStep(name); } } } /** * Copy selected tree item to the clipboard in XML format * */ public void clipSelected() { // Determine what menu we selected from... TreeItem ti[] = selectionTree.getSelection(); // Then call editConnection or editStep or editTrans if (ti.length==1) { String name = ti[0].getText(); TreeItem parent = ti[0].getParentItem(); if (parent != null) { log.logDebug(toString(), Messages.getString("Spoon.Log.DUPE.ElementHasParent"));//"(DUPE) Element has parent." String type = parent.getText(); if (type.equalsIgnoreCase(STRING_CONNECTIONS)) clipConnection(name); if (type.equalsIgnoreCase(STRING_STEPS )) clipStep(name); } } } public void delSelected() { // Determine what menu we selected from... int i; TreeItem ti[] = selectionTree.getSelection(); String name[] = new String[ti.length]; TreeItem parent[] = new TreeItem[ti.length]; for (i=0;i<ti.length;i++) { name[i] = ti[i].getText(); parent[i] = ti[i].getParentItem(); } // Then call editConnection or editStep or editTrans for (i=name.length-1;i>=0;i--) { log.logDebug(toString(), Messages.getString("Spoon.Log.DELETE.TryToDelete")+"#"+i+"/"+(ti.length-1)+" : "+name[i]);//(DELETE) Trying to delete if (parent[i] != null) { String type = parent[i].getText(); log.logDebug(toString(), Messages.getString("Spoon.Log.DELETE.ElementHasParent")+type);//(DELETE) Element has parent: if (type.equalsIgnoreCase(STRING_CONNECTIONS)) delConnection(name[i]); if (type.equalsIgnoreCase(STRING_STEPS )) delStep(name[i]); if (type.equalsIgnoreCase(STRING_HOPS )) delHop(name[i]); } } } public void sqlSelected() { // Determine what menu we selected from... int i; TreeItem ti[] = selectionTree.getSelection(); for (i=0;i<ti.length;i++) { String name = ti[i].getText(); TreeItem parent = ti[i].getParentItem(); String type = parent.getText(); if (type.equalsIgnoreCase(STRING_CONNECTIONS)) { DatabaseMeta ci = transMeta.findDatabase(name); SQLEditor sql = new SQLEditor(shell, SWT.NONE, ci, transMeta.getDbCache(), ""); sql.open(); } } } public void editConnection(String name) { DatabaseMeta db = transMeta.findDatabase(name); if (db!=null) { DatabaseMeta before = (DatabaseMeta)db.clone(); DatabaseDialog con = new DatabaseDialog(shell, SWT.NONE, log, db, props); con.setDatabases(transMeta.getDatabases()); String newname = con.open(); if (newname != null && newname.length()>0) // null: CANCEL { // Store undo/redo information DatabaseMeta after = (DatabaseMeta)db.clone(); addUndoChange(new DatabaseMeta[] { before }, new DatabaseMeta[] { after }, new int[] { transMeta.indexOfDatabase(db) } ); saveConnection(db); // The connection is saved, clear the changed flag. db.setChanged(false); if (!name.equalsIgnoreCase(newname)) refreshTree(true); } } setShellText(); } public void dupeConnection(String name) { DatabaseMeta db = transMeta.findDatabase(name); int pos = transMeta.indexOfDatabase(db); if (db!=null) { DatabaseMeta newdb = (DatabaseMeta)db.clone(); String dupename = Messages.getString("Spoon.Various.DupeName") +name; //"(copy of) " newdb.setName(dupename); transMeta.addDatabase(pos+1, newdb); refreshTree(); DatabaseDialog con = new DatabaseDialog(shell, SWT.NONE, log, newdb, props); String newname = con.open(); if (newname != null) // null: CANCEL { transMeta.removeDatabase(pos+1); transMeta.addDatabase(pos+1, newdb); if (!newname.equalsIgnoreCase(dupename)) refreshTree(); } else { addUndoNew(new DatabaseMeta[] { (DatabaseMeta)db.clone() }, new int[] { pos }); saveConnection(db); } } } public void clipConnection(String name) { DatabaseMeta db = transMeta.findDatabase(name); if (db!=null) { String xml = XMLHandler.getXMLHeader() + db.getXML(); toClipboard(xml); } } /** * Delete a database connection * @param name The name of the database connection. */ public void delConnection(String name) { DatabaseMeta db = transMeta.findDatabase(name); int pos = transMeta.indexOfDatabase(db); if (db!=null) { boolean worked=false; // delete from repository? if (rep!=null) { if (!rep.getUserInfo().isReadonly()) { try { long id_database = rep.getDatabaseID(db.getName()); rep.delDatabase(id_database); worked=true; } catch(KettleDatabaseException dbe) { new ErrorDialog(shell, props, Messages.getString("Spoon.Dialog.ErrorDeletingConnection.Title"), Messages.getString("Spoon.Dialog.ErrorDeletingConnection.Message",name), dbe);//"Error deleting connection ["+db+"] from repository!" } } else { new ErrorDialog(shell, props, Messages.getString("Spoon.Dialog.ErrorDeletingConnection.Title"),Messages.getString("Spoon.Dialog.ErrorDeletingConnection.Message",name) , new KettleException(Messages.getString("Spoon.Dialog.Exception.ReadOnlyUser")));//"Error deleting connection ["+db+"] from repository!" //This user is read-only! } } if (rep==null || worked) { addUndoDelete(new DatabaseMeta[] { (DatabaseMeta)db.clone() }, new int[] { pos }); transMeta.removeDatabase(pos); } refreshTree(); } setShellText(); } public void editStep(String name) { log.logDebug(toString(), Messages.getString("Spoon.Log.EditStep") +name);//"Edit step: " editStepInfo(transMeta.findStep(name)); } public String editStepInfo(StepMeta stepMeta) { String stepname = null; if (stepMeta != null) { try { String name = stepMeta.getName(); // Before we do anything, let's store the situation the way it was... StepMeta before = (StepMeta) stepMeta.clone(); StepMetaInterface stepint = stepMeta.getStepMetaInterface(); StepDialogInterface dialog = stepint.getDialog(shell, stepMeta.getStepMetaInterface(), transMeta, name); dialog.setRepository(rep); stepname = dialog.open(); if (stepname != null) { // OK, so the step has changed... // // First, backup the situation for undo/redo StepMeta after = (StepMeta) stepMeta.clone(); addUndoChange(new StepMeta[] { before }, new StepMeta[] { after }, new int[] { transMeta.indexOfStep(stepMeta) }); // Then, store the size of the // See if the new name the user enter, doesn't collide with another step. // If so, change the stepname and warn the user! // String newname = stepname; StepMeta smeta = transMeta.findStep(newname, stepMeta); int nr = 2; while (smeta != null) { newname = stepname + " " + nr; smeta = transMeta.findStep(newname); nr++; } if (nr > 2) { stepname = newname; MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION); mb.setMessage(Messages.getString("Spoon.Dialog.StepnameExists.Message", stepname)); // $NON-NLS-1$ mb.setText(Messages.getString("Spoon.Dialog.StepnameExists.Title")); // $NON-NLS-1$ mb.open(); } stepMeta.setName(stepname); refreshTree(true); // Perhaps new connections were created in the step dialog. } else { // Scenario: change connections and click cancel... // Perhaps new connections were created in the step dialog? if (transMeta.haveConnectionsChanged()) { refreshTree(true); } } refreshGraph(); // name is displayed on the graph too. setShellText(); } catch (Throwable e) { if (shell.isDisposed()) return null; new ErrorDialog(shell, props, Messages.getString("Spoon.Dialog.UnableOpenDialog.Title"), Messages .getString("Spoon.Dialog.UnableOpenDialog.Message"), new Exception(e));//"Unable to open dialog for this step" } } return stepname; } public void dupeStep(String name) { log.logDebug(toString(), Messages.getString("Spoon.Log.DuplicateStep")+name);//Duplicate step: StepMeta stMeta = null, stepMeta = null, look=null; for (int i=0;i<transMeta.nrSteps() && stepMeta==null;i++) { look = transMeta.getStep(i); if (look.getName().equalsIgnoreCase(name)) { stepMeta=look; } } if (stepMeta!=null) { stMeta = (StepMeta)stepMeta.clone(); if (stMeta!=null) { String newname = transMeta.getAlternativeStepname(stepMeta.getName()); int nr=2; while (transMeta.findStep(newname)!=null) { newname = stepMeta.getName()+" (copy "+nr+")"; nr++; } stMeta.setName(newname); // Don't select this new step! stMeta.setSelected(false); Point loc = stMeta.getLocation(); stMeta.setLocation(loc.x+20, loc.y+20); transMeta.addStep(stMeta); addUndoNew(new StepMeta[] { (StepMeta)stMeta.clone() }, new int[] { transMeta.indexOfStep(stMeta) }); refreshTree(); refreshGraph(); } } } public void clipStep(String name) { log.logDebug(toString(), Messages.getString("Spoon.Log.CopyStepToClipboard")+name);//copy step to clipboard: StepMeta stepMeta = transMeta.findStep(name); if (stepMeta!=null) { String xml = stepMeta.getXML(); toClipboard(xml); } } public void pasteXML(String clipcontent, Point loc) { try { //System.out.println(clipcontent); Document doc = XMLHandler.loadXMLString(clipcontent); Node transnode = XMLHandler.getSubNode(doc, "transformation"); // De-select all, re-select pasted steps... transMeta.unselectAll(); Node stepsnode = XMLHandler.getSubNode(transnode, "steps"); int nr = XMLHandler.countNodes(stepsnode, "step"); log.logDebug(toString(), Messages.getString("Spoon.Log.FoundSteps",""+nr)+loc);//"I found "+nr+" steps to paste on location: " StepMeta steps[] = new StepMeta[nr]; //Point min = new Point(loc.x, loc.y); Point min = new Point(99999999,99999999); // Load the steps... for (int i=0;i<nr;i++) { Node stepnode = XMLHandler.getSubNodeByNr(stepsnode, "step", i); steps[i] = new StepMeta(log, stepnode, transMeta.getDatabases(), transMeta.getCounters()); if (loc!=null) { Point p = steps[i].getLocation(); if (min.x > p.x) min.x = p.x; if (min.y > p.y) min.y = p.y; } } // Load the hops... Node hopsnode = XMLHandler.getSubNode(transnode, "order"); nr = XMLHandler.countNodes(hopsnode, "hop"); log.logDebug(toString(), Messages.getString("Spoon.Log.FoundHops",""+nr));//"I found "+nr+" hops to paste." TransHopMeta hops[] = new TransHopMeta[nr]; ArrayList alSteps = new ArrayList(); for (int i=0;i<steps.length;i++) alSteps.add(steps[i]); for (int i=0;i<nr;i++) { Node hopnode = XMLHandler.getSubNodeByNr(hopsnode, "hop", i); hops[i] = new TransHopMeta(hopnode, alSteps); } // What's the difference between loc and min? // This is the offset: Point offset = new Point(loc.x-min.x, loc.y-min.y); // Undo/redo object positions... int position[] = new int[steps.length]; for (int i=0;i<steps.length;i++) { Point p = steps[i].getLocation(); String name = steps[i].getName(); steps[i].setLocation(p.x+offset.x, p.y+offset.y); steps[i].setDraw(true); // Check the name, find alternative... steps[i].setName( transMeta.getAlternativeStepname(name) ); transMeta.addStep(steps[i]); position[i] = transMeta.indexOfStep(steps[i]); } // Add the hops too... for (int i=0;i<hops.length;i++) { transMeta.addTransHop(hops[i]); } // Load the notes... Node notesnode = XMLHandler.getSubNode(transnode, "notepads"); nr = XMLHandler.countNodes(notesnode, "notepad"); log.logDebug(toString(), Messages.getString("Spoon.Log.FoundNotepads",""+nr));//"I found "+nr+" notepads to paste." NotePadMeta notes[] = new NotePadMeta[nr]; for (int i=0;i<notes.length;i++) { Node notenode = XMLHandler.getSubNodeByNr(notesnode, "notepad", i); notes[i] = new NotePadMeta(notenode); Point p = notes[i].getLocation(); notes[i].setLocation(p.x+offset.x, p.y+offset.y); transMeta.addNote(notes[i]); } // Set the source and target steps ... for (int i=0;i<steps.length;i++) { StepMetaInterface smi = steps[i].getStepMetaInterface(); smi.searchInfoAndTargetSteps(transMeta.getSteps()); } // Save undo information too... addUndoNew(steps, position, false); int hoppos[] = new int[hops.length]; for (int i=0;i<hops.length;i++) hoppos[i] = transMeta.indexOfTransHop(hops[i]); addUndoNew(hops, hoppos, true); int notepos[] = new int[notes.length]; for (int i=0;i<notes.length;i++) notepos[i] = transMeta.indexOfNote(notes[i]); addUndoNew(notes, notepos, true); if (transMeta.haveStepsChanged()) { refreshTree(); refreshGraph(); } } catch(KettleException e) { new ErrorDialog(shell, props, Messages.getString("Spoon.Dialog.UnablePasteSteps.Title"),Messages.getString("Spoon.Dialog.UnablePasteSteps.Message") , e);//"Error pasting steps...", "I was unable to paste steps to this transformation" } } public void copySelected(StepMeta stepMeta[], NotePadMeta notePadMeta[]) { if (stepMeta==null || stepMeta.length==0) return; String xml = XMLHandler.getXMLHeader(); xml+="<transformation>"+Const.CR; xml+=" <steps>"+Const.CR; for (int i=0;i<stepMeta.length;i++) { xml+=stepMeta[i].getXML(); } xml+=" </steps>"+Const.CR; // // Also check for the hops in between the selected steps... // xml+="<order>"+Const.CR; if (stepMeta!=null) for (int i=0;i<stepMeta.length;i++) { for (int j=0;j<stepMeta.length;j++) { if (i!=j) { TransHopMeta hop = transMeta.findTransHop(stepMeta[i], stepMeta[j]); if (hop!=null) // Ok, we found one... { xml+=hop.getXML()+Const.CR; } } } } xml+=" </order>"+Const.CR; xml+=" <notepads>"+Const.CR; if (notePadMeta!=null) for (int i=0;i<notePadMeta.length;i++) { xml+= notePadMeta[i].getXML(); } xml+=" </notepads>"+Const.CR; xml+=" </transformation>"+Const.CR; toClipboard(xml); } public void delStep(String name) { log.logDebug(toString(), Messages.getString("Spoon.Log.DeleteStep")+name);//"Delete step: " int i, pos=0; StepMeta stepMeta = null, look=null; for (i=0;i<transMeta.nrSteps() && stepMeta==null;i++) { look = transMeta.getStep(i); if (look.getName().equalsIgnoreCase(name)) { stepMeta=look; pos=i; } } if (stepMeta!=null) { for (i=transMeta.nrTransHops()-1;i>=0;i--) { TransHopMeta hi = transMeta.getTransHop(i); if ( hi.getFromStep().equals(stepMeta) || hi.getToStep().equals(stepMeta) ) { addUndoDelete(new TransHopMeta[] { hi }, new int[] { transMeta.indexOfTransHop(hi) }, true); transMeta.removeTransHop(i); refreshTree(); } } transMeta.removeStep(pos); addUndoDelete(new StepMeta[] { stepMeta }, new int[] { pos }); refreshTree(); refreshGraph(); } else { log.logDebug(toString(),Messages.getString("Spoon.Log.UnableFindStepToDelete",name) );//"Couldn't find step ["+name+"] to delete..." } } public void editHop(String name) { TransHopMeta hi = transMeta.findTransHop(name); if (hi!=null) { // Backup situation BEFORE edit: TransHopMeta before = (TransHopMeta)hi.clone(); TransHopDialog hd = new TransHopDialog(shell, SWT.NONE, hi, transMeta); if (hd.open()!=null) { // Backup situation for redo/undo: TransHopMeta after = (TransHopMeta)hi.clone(); addUndoChange(new TransHopMeta[] { before }, new TransHopMeta[] { after }, new int[] { transMeta.indexOfTransHop(hi) } ); String newname = hi.toString(); if (!name.equalsIgnoreCase(newname)) { refreshTree(); refreshGraph(); // color, nr of copies... } } } setShellText(); } public void delHop(String name) { int i,n; n=transMeta.nrTransHops(); for (i=0;i<n;i++) { TransHopMeta hi = transMeta.getTransHop(i); if (hi.toString().equalsIgnoreCase(name)) { addUndoDelete(new Object[] { (TransHopMeta)hi.clone() }, new int[] { transMeta.indexOfTransHop(hi) }); transMeta.removeTransHop(i); refreshTree(); refreshGraph(); return; } } setShellText(); } public void newHop(StepMeta fr, StepMeta to) { TransHopMeta hi = new TransHopMeta(fr, to); TransHopDialog hd = new TransHopDialog(shell, SWT.NONE, hi, transMeta); if (hd.open()!=null) { boolean error=false; if (transMeta.findTransHop(hi.getFromStep(), hi.getToStep())!=null) { MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR ); mb.setMessage(Messages.getString("Spoon.Dialog.HopExists.Message"));//"This hop already exists!" mb.setText(Messages.getString("Spoon.Dialog.HopExists.Title"));//Error! mb.open(); error=true; } if (transMeta.hasLoop(fr) || transMeta.hasLoop(to)) { refreshTree(); refreshGraph(); MessageBox mb = new MessageBox(shell, SWT.YES | SWT.ICON_WARNING ); mb.setMessage(Messages.getString("Spoon.Dialog.AddingHopCausesLoop.Message"));//Adding this hop causes a loop in the transformation. Loops are not allowed! mb.setText(Messages.getString("Spoon.Dialog.AddingHopCausesLoop.Title"));//Warning! mb.open(); error=true; } if (!error) { transMeta.addTransHop(hi); addUndoNew(new TransHopMeta[] { (TransHopMeta)hi.clone() }, new int[] { transMeta.indexOfTransHop(hi) }); hi.getFromStep().drawStep(); hi.getToStep().drawStep(); refreshTree(); refreshGraph(); } } } public void newHop() { newHop(null, null); } public void newConnection() { DatabaseMeta db = new DatabaseMeta(); DatabaseDialog con = new DatabaseDialog(shell, SWT.APPLICATION_MODAL, log, db, props); String con_name = con.open(); if (con_name!=null && con_name.length()>0) { transMeta.addDatabase(db); addUndoNew(new DatabaseMeta[] { (DatabaseMeta)db.clone() }, new int[] { transMeta.indexOfDatabase(db) }); saveConnection(db); refreshTree(); } } public void saveConnection(DatabaseMeta db) { // Also add to repository? if (rep!=null) { if (!rep.userinfo.isReadonly()) { try { db.saveRep(rep); log.logDetailed(toString(), Messages.getString("Spoon.Log.SavedDatabaseConnection",db.getDatabaseName()));//"Saved database connection ["+db+"] to the repository." // Put a commit behind it! rep.commit(); } catch(KettleException ke) { rep.rollback(); // In case of failure: undo changes! new ErrorDialog(shell, props, Messages.getString("Spoon.Dialog.ErrorSavingConnection.Title"),Messages.getString("Spoon.Dialog.ErrorSavingConnection.Message",db.getDatabaseName()), ke);//"Can't save...","Error saving connection ["+db+"] to repository!" } } else { new ErrorDialog(shell, props, Messages.getString("Spoon.Dialog.UnableSave.Title"),Messages.getString("Spoon.Dialog.ErrorSavingConnection.Message",db.getDatabaseName()), new KettleException(Messages.getString("Spoon.Dialog.Exception.ReadOnlyRepositoryUser")));//This repository user is read-only! } } } /** * Shows a 'model has changed' warning if required * @return true if nothing has changed or the changes are rejected by the user. */ public boolean showChangedWarning() { boolean answer = true; if (transMeta.hasChanged()) { MessageBox mb = new MessageBox(shell, SWT.YES | SWT.NO | SWT.CANCEL | SWT.ICON_WARNING ); mb.setMessage(Messages.getString("Spoon.Dialog.PromptSave.Message"));//"This model has changed. Do you want to save it?" mb.setText(Messages.getString("Spoon.Dialog.PromptSave.Title")); int reply = mb.open(); if (reply==SWT.YES) { answer=saveFile(); } else { if (reply==SWT.CANCEL) { answer = false; } else { answer = true; } } } return answer; } public void openRepository() { int perms[] = new int[] { PermissionMeta.TYPE_PERMISSION_TRANSFORMATION }; RepositoriesDialog rd = new RepositoriesDialog(disp, SWT.NONE, perms, APP_NAME); rd.getShell().setImage(GUIResource.getInstance().getImageSpoon()); if (rd.open()) { // Close previous repository... if (rep!=null) { rep.disconnect(); } rep = new Repository(log, rd.getRepository(), rd.getUser()); try { rep.connect(APP_NAME); } catch(KettleException ke) { rep=null; new ErrorDialog(shell, props, Messages.getString("Spoon.Dialog.ErrorConnectingRepository.Title"), Messages.getString("Spoon.Dialog.ErrorConnectingRepository.Message",Const.CR), ke); //$NON-NLS-1$ //$NON-NLS-2$ } // Set for the existing databases, the ID's at -1! for (int i=0;i<transMeta.nrDatabases();i++) { transMeta.getDatabase(i).setID(-1L); } // Set for the existing transformation the ID at -1! transMeta.setID(-1L); // Keep track of the old databases for now. ArrayList oldDatabases = transMeta.getDatabases(); // In order to re-match the databases on name (not content), we need to load the databases from the new repository. // NOTE: for purposes such as DEVELOP - TEST - PRODUCTION sycles. // first clear the list of databases. transMeta.setDatabases(new ArrayList()); // Read them from the new repository. readDatabases(); /* for (int i=0;i<transMeta.nrDatabases();i++) { System.out.println("NEW REP: ["+transMeta.getDatabase(i).getName()+"]"); } */ // Then we need to re-match the databases at save time... for (int i=0;i<oldDatabases.size();i++) { DatabaseMeta oldDatabase = (DatabaseMeta) oldDatabases.get(i); DatabaseMeta newDatabase = Const.findDatabase(transMeta.getDatabases(), oldDatabase.getName()); // If it exists, change the settings... if (newDatabase!=null) { // System.out.println("Found the new database in the repository ["+oldDatabase.getName()+"]"); // A database connection with the same name exists in the new repository. // Change the old connections to reflect the settings in the new repository oldDatabase.setDatabaseInterface(newDatabase.getDatabaseInterface()); } else { // System.out.println("Couldn't find the new database in the repository ["+oldDatabase.getName()+"]"); // The old database is not present in the new repository: simply add it to the list. // When the transformation gets saved, it will be added to the repository. transMeta.addDatabase(oldDatabase); } } // For the existing transformation, change the directory too: // Try to find the same directory in the new repository... RepositoryDirectory redi = rep.getDirectoryTree().findDirectory(transMeta.getDirectory().getPath()); if (redi!=null) { transMeta.setDirectory(redi); } else { transMeta.setDirectory(rep.getDirectoryTree()); // the root is the default! } refreshTree(true); setShellText(); } else { // Not cancelled? --> Clear repository... if (!rd.isCancelled()) { closeRepository(); } } } public void exploreRepository() { if (rep!=null) { RepositoryExplorerDialog erd = new RepositoryExplorerDialog(shell, SWT.NONE, rep, rep.getUserInfo()); String objname = erd.open(); if (objname!=null) { String object_type = erd.getObjectType(); RepositoryDirectory repdir = erd.getObjectDirectory(); // System.out.println("Load ["+object_type+"] --> ["+objname+"] from dir ["+(repdir==null)+"]"); // Try to open it as a transformation. if (object_type.equals(RepositoryExplorerDialog.STRING_TRANSFORMATIONS)) { if (showChangedWarning()) { try { transMeta = new TransMeta(rep, objname, repdir); transMeta.clearChanged(); setFilename(objname); refreshTree(); refreshGraph(); } catch(KettleException e) { MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR ); mb.setMessage(Messages.getString("Spoon.Dialog.ErrorOpening.Message")+objname+Const.CR+e.getMessage());//"Error opening : " mb.setText(Messages.getString("Spoon.Dialog.ErrorOpening.Title")); mb.open(); } } } } } } public void editRepositoryUser() { if (rep!=null) { UserInfo userinfo = rep.getUserInfo(); UserDialog ud = new UserDialog(shell, SWT.NONE, log, props, rep, userinfo); UserInfo ui = ud.open(); if (!userinfo.isReadonly()) { if (ui!=null) { try { ui.saveRep(rep); } catch(KettleException e) { MessageBox mb = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK); mb.setMessage(Messages.getString("Spoon.Dialog.UnableChangeUser.Message")+Const.CR+e.getMessage());//Sorry, I was unable to change this user in the repository: mb.setText(Messages.getString("Spoon.Dialog.UnableChangeUser.Title"));//"Edit user" mb.open(); } } } else { MessageBox mb = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK); mb.setMessage(Messages.getString("Spoon.Dialog.NotAllowedChangeUser.Message"));//"Sorry, you are not allowed to change this user." mb.setText(Messages.getString("Spoon.Dialog.NotAllowedChangeUser.Title")); mb.open(); } } } public void readDatabases() { transMeta.readDatabases(rep); } public void closeRepository() { if (rep!=null) rep.disconnect(); rep = null; setShellText(); } public void openFile(boolean importfile) { if (showChangedWarning()) { if (rep==null || importfile) // Load from XML { FileDialog dialog = new FileDialog(shell, SWT.OPEN); // dialog.setFilterPath("C:\\Projects\\kettle\\source\\"); dialog.setFilterExtensions(Const.STRING_TRANS_FILTER_EXT); dialog.setFilterNames(Const.STRING_TRANS_FILTER_NAMES); String fname = dialog.open(); if (fname!=null) { try { transMeta = new TransMeta(fname); props.addLastFile(Props.TYPE_PROPERTIES_SPOON, fname, Const.FILE_SEPARATOR, false, ""); addMenuLast(); if (!importfile) transMeta.clearChanged(); setFilename(fname); } catch(KettleException e) { clear(); MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR ); mb.setMessage(Messages.getString("Spoon.Dialog.ErrorOpening.Message")+fname+Const.CR+e.getMessage());//"Error opening : " mb.setText(Messages.getString("Spoon.Dialog.ErrorOpening.Title"));//"Error!" mb.open(); } refreshGraph(); refreshTree(true); refreshHistory(); } } else // Read a transformation from the repository! { SelectObjectDialog sod = new SelectObjectDialog(shell, props, rep, true, false, false); String transname = sod.open(); RepositoryDirectory repdir = sod.getDirectory(); if (transname!=null && repdir!=null) { TransLoadProgressDialog tlpd = new TransLoadProgressDialog(shell, rep, transname, repdir); TransMeta transInfo = tlpd.open(); if (transInfo!=null) { transMeta = transInfo; // transMeta = new TransInfo(log, rep, transname, repdir); log.logDetailed(toString(),Messages.getString("Spoon.Log.LoadToTransformation",transname,repdir.getDirectoryName()) );//"Transformation ["+transname+"] in directory ["+repdir+"] loaded from the repository." //System.out.println("name="+transMeta.getName()); props.addLastFile(Props.TYPE_PROPERTIES_SPOON, transname, repdir.getPath(), true, rep.getName()); addMenuLast(); transMeta.clearChanged(); setFilename(transname); } refreshGraph(); refreshTree(true); refreshHistory(); } } } } public void newFile() { if (showChangedWarning()) { clear(); loadRepositoryObjects(); // Add databases if connected to repository setFilename(null); refreshTree(true); refreshGraph(); refreshHistory(); } } public void loadRepositoryObjects() { // Load common database info from active repository... if (rep!=null) { transMeta.readDatabases(rep); } } public boolean quitFile() { boolean exit = true; boolean showWarning = true; log.logDetailed(toString(), Messages.getString("Spoon.Log.QuitApplication"));//"Quit application." saveSettings(); if (transMeta.hasChanged()) { MessageBox mb = new MessageBox(shell, SWT.YES | SWT.NO | SWT.CANCEL | SWT.ICON_WARNING ); mb.setMessage(Messages.getString("Spoon.Dialog.SaveChangedFile.Message"));//"File has changed! Do you want to save first?" mb.setText(Messages.getString("Spoon.Dialog.SaveChangedFile.Title"));//"Warning!" int answer = mb.open(); switch(answer) { case SWT.YES: exit=saveFile(); showWarning=false; break; case SWT.NO: exit=true; showWarning=false; break; case SWT.CANCEL: exit=false; showWarning=false; break; } } // System.out.println("exit="+exit+", showWarning="+showWarning+", running="+spoonlog.isRunning()+", showExitWarning="+props.showExitWarning()); // Show warning on exit when spoon is still running // Show warning on exit when a warning needs to be displayed, but only if we didn't ask to save before. (could have pressed cancel then!) // if ( (exit && spoonlog.isRunning() ) || (exit && showWarning && props.showExitWarning() ) ) { String message = Messages.getString("Spoon.Message.Warning.PromptExit"); //"Are you sure you want to exit?" if (spoonlog.isRunning()) message = Messages.getString("Spoon.Message.Warning.PromptExitWhenRunTransformation");//There is a running transformation. Are you sure you want to exit? MessageDialogWithToggle md = new MessageDialogWithToggle(shell, Messages.getString("System.Warning"),//"Warning!" null, message, MessageDialog.WARNING, new String[] { Messages.getString("Spoon.Message.Warning.Yes"), Messages.getString("Spoon.Message.Warning.No") },//"Yes", "No" 1, Messages.getString("Spoon.Message.Warning.NotShowWarning"),//"Please, don't show this warning anymore." !props.showExitWarning() ); int idx = md.open(); props.setExitWarningShown(!md.getToggleState()); props.saveProps(); if (idx==1) exit=false; // No selected: don't exit! else exit=true; } if (exit) dispose(); return exit; } public boolean saveFile() { boolean saved=false; log.logDetailed(toString(), Messages.getString("Spoon.Log.SaveToFileOrRepository"));//"Save to file or repository..." if (rep!=null) { saved=saveRepository(); } else { if (transMeta.getFilename()!=null) { saved=save(transMeta.getFilename()); } else { saved=saveFileAs(); } } try { if (props.useDBCache()) transMeta.getDbCache().saveCache(log); } catch(KettleException e) { new ErrorDialog(shell, props, Messages.getString("Spoon.Dialog.ErrorSavingDatabaseCache.Title"), Messages.getString("Spoon.Dialog.ErrorSavingDatabaseCache.Message"), e);//"An error occured saving the database cache to disk" } return saved; } public boolean saveRepository() { return saveRepository(false); } public boolean saveRepository(boolean ask_name) { log.logDetailed(toString(), Messages.getString("Spoon.Log.SaveToRepository"));//"Save to repository..." if (rep!=null) { boolean answer = true; boolean ask = ask_name; while (answer && ( ask || transMeta.getName()==null || transMeta.getName().length()==0 ) ) { if (!ask) { MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_WARNING); mb.setMessage(Messages.getString("Spoon.Dialog.PromptTransformationName.Message"));//"Please give this transformation a name before saving it in the database." mb.setText(Messages.getString("Spoon.Dialog.PromptTransformationName.Title"));//"Transformation has no name." mb.open(); } ask=false; answer = setTrans(); // System.out.println("answer="+answer+", ask="+ask+", transMeta.getName()="+transMeta.getName()); } if (answer && transMeta.getName()!=null && transMeta.getName().length()>0) { if (!rep.getUserInfo().isReadonly()) { int response = SWT.YES; if (transMeta.showReplaceWarning(rep)) { MessageBox mb = new MessageBox(shell, SWT.YES | SWT.NO | SWT.ICON_QUESTION); mb.setMessage(Messages.getString("Spoon.Dialog.PromptOverwriteTransformation.Message",transMeta.getName(),Const.CR));//"There already is a transformation called ["+transMeta.getName()+"] in the repository."+Const.CR+"Do you want to overwrite the transformation?" mb.setText(Messages.getString("Spoon.Dialog.PromptOverwriteTransformation.Title"));//"Overwrite?" response = mb.open(); } boolean saved=false; if (response == SWT.YES) { shell.setCursor(cursor_hourglass); // Keep info on who & when this transformation was changed... transMeta.setModifiedDate( new Value("MODIFIED_DATE", Value.VALUE_TYPE_DATE) ); transMeta.getModifiedDate().sysdate(); transMeta.setModifiedUser( rep.getUserInfo().getLogin() ); TransSaveProgressDialog tspd = new TransSaveProgressDialog(log, props, shell, rep, transMeta); if (tspd.open()) { saved=true; if (!props.getSaveConfirmation()) { MessageDialogWithToggle md = new MessageDialogWithToggle(shell, Messages.getString("Spoon.Message.Warning.SaveOK"), //"Save OK!" null, Messages.getString("Spoon.Message.Warning.TransformationWasStored"),//"This transformation was stored in repository" MessageDialog.QUESTION, new String[] { Messages.getString("Spoon.Message.Warning.OK") },//"OK!" 0, Messages.getString("Spoon.Message.Warning.NotShowThisMessage"),//"Don't show this message again." props.getSaveConfirmation() ); md.open(); props.setSaveConfirmation(md.getToggleState()); } // Handle last opened files... props.addLastFile(Props.TYPE_PROPERTIES_SPOON, transMeta.getName(), transMeta.getDirectory().getPath(), true, getRepositoryName()); saveSettings(); addMenuLast(); setShellText(); } shell.setCursor(null); } return saved; } else { MessageBox mb = new MessageBox(shell, SWT.CLOSE | SWT.ICON_ERROR); mb.setMessage(Messages.getString("Spoon.Dialog.OnlyreadRepository.Message"));//"Sorry, the user you're logged on with, can only read from the repository" mb.setText(Messages.getString("Spoon.Dialog.OnlyreadRepository.Title"));//"Transformation not saved!" mb.open(); } } } else { MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR); mb.setMessage(Messages.getString("Spoon.Dialog.NoRepositoryConnection.Message"));//"There is no repository connection available." mb.setText(Messages.getString("Spoon.Dialog.NoRepositoryConnection.Title"));//"No repository available." mb.open(); } return false; } public boolean saveFileAs() { boolean saved=false; log.logBasic(toString(), Messages.getString("Spoon.Log.SaveAs"));//"Save as..." if (rep!=null) { transMeta.setID(-1L); saved=saveRepository(true); } else { saved=saveXMLFile(); } return saved; } private boolean saveXMLFile() { boolean saved=false; FileDialog dialog = new FileDialog(shell, SWT.SAVE); dialog.setFilterPath("C:\\Projects\\kettle\\source\\"); dialog.setFilterExtensions(Const.STRING_TRANS_FILTER_EXT); dialog.setFilterNames(Const.STRING_TRANS_FILTER_NAMES); String fname = dialog.open(); if (fname!=null) { // Is the filename ending on .ktr, .xml? boolean ending=false; for (int i=0;i<Const.STRING_TRANS_FILTER_EXT.length-1;i++) { if (fname.endsWith(Const.STRING_TRANS_FILTER_EXT[i].substring(1))) { ending=true; } } if (fname.endsWith(Const.STRING_TRANS_DEFAULT_EXT)) ending=true; if (!ending) { fname+=Const.STRING_TRANS_DEFAULT_EXT; } // See if the file already exists... File f = new File(fname); int id = SWT.YES; if (f.exists()) { MessageBox mb = new MessageBox(shell, SWT.NO | SWT.YES | SWT.ICON_WARNING); mb.setMessage(Messages.getString("Spoon.Dialog.PromptOverwriteFile.Message"));//"This file already exists. Do you want to overwrite it?" mb.setText(Messages.getString("Spoon.Dialog.PromptOverwriteFile.Title"));//"This file already exists!" id = mb.open(); } if (id==SWT.YES) { saved=save(fname); setFilename(fname); } } return saved; } private boolean save(String fname) { boolean saved = false; String xml = XMLHandler.getXMLHeader() + transMeta.getXML(); try { DataOutputStream dos = new DataOutputStream(new FileOutputStream(new File(fname))); dos.write(xml.getBytes(Const.XML_ENCODING)); dos.close(); saved=true; // Handle last opened files... props.addLastFile(Props.TYPE_PROPERTIES_SPOON, fname, Const.FILE_SEPARATOR, false, ""); saveSettings(); addMenuLast(); transMeta.clearChanged(); setShellText(); log.logDebug(toString(), Messages.getString("Spoon.Log.FileWritten")+" ["+fname+"]"); //"File written to } catch(Exception e) { log.logDebug(toString(), Messages.getString("Spoon.Log.ErrorOpeningFileForWriting")+e.toString());//"Error opening file for writing! --> " MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR); mb.setMessage(Messages.getString("Spoon.Dialog.ErrorSavingFile.Message")+Const.CR+e.toString());//"Error saving file:" mb.setText(Messages.getString("Spoon.Dialog.ErrorSavingFile.Title"));//"ERROR" mb.open(); } return saved; } public void helpAbout() { MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION | SWT.CENTER); String mess = Messages.getString("System.ProductInfo")+Const.VERSION+Const.CR+Const.CR+Const.CR;//Kettle - Spoon version mess+=Messages.getString("System.CompanyInfo")+Const.CR; mess+=" "+Messages.getString("System.ProductWebsiteUrl")+Const.CR; //(c) 2001-2004 i-Bridge bvba www.kettle.be mess+=" "+BuildVersion.getInstance().getVersion()+Const.CR; mb.setMessage(mess); mb.setText(APP_NAME); mb.open(); } public void editUnselectAll() { transMeta.unselectAll(); spoongraph.redraw(); } public void editSelectAll() { transMeta.selectAll(); spoongraph.redraw(); } public void editOptions() { EnterOptionsDialog eod = new EnterOptionsDialog(shell, props); if (eod.open()!=null) { props.saveProps(); loadSettings(); changeLooks(); MessageBox mb = new MessageBox(shell, SWT.ICON_INFORMATION); mb.setMessage(Messages.getString("Spoon.Dialog.PleaseRestartApplication.Message")); mb.setText(Messages.getString("Spoon.Dialog.PleaseRestartApplication.Title")); mb.open(); } } public int getTreePosition(TreeItem ti, String item) { if (ti!=null) { TreeItem items[] = ti.getItems(); for (int x=0;x<items.length;x++) { if (items[x].getText().equalsIgnoreCase(item)) { return x; } } } return -1; } public void refreshTree() { refreshTree(false); refreshPluginHistory(); } /** * Refresh the object selection tree (on the left of the screen) * @param complete true refreshes the complete tree, false tries to do a differential update to avoid flickering. */ public void refreshTree(boolean complete) { if (shell.isDisposed()) return; if (!transMeta.hasChanged() && !complete) return; // Nothing changed: nothing to do! int idx; TreeItem ti[]; // Refresh the connections... // if (transMeta.haveConnectionsChanged() || complete) { tiConn.setText(STRING_CONNECTIONS); // TreeItem tiConn= this.tiConn (TreeItem)widgets.getWidget(STRING_CONNECTIONS); ti = tiConn.getItems(); // In complete refresh: delete all items first if (complete) { for (int i=0;i<ti.length;i++) ti[i].dispose(); ti = tiConn.getItems(); } // First delete no longer used items... for (int i=0;i<ti.length;i++) { String str = ti[i].getText(); DatabaseMeta inf = transMeta.findDatabase(str); if (inf!=null) idx = transMeta.indexOfDatabase(inf); else idx=-1; if (idx<0 || idx>i) ti[i].dispose(); } ti = tiConn.getItems(); // Insert missing items in tree... int j=0; for (int i=0;i<transMeta.nrDatabases();i++) { DatabaseMeta inf = transMeta.getDatabase(i); String con_name = inf.getName(); String ti_name = ""; if (j<ti.length) ti_name = ti[j].getText(); if (!con_name.equalsIgnoreCase(ti_name)) { // insert at position j in tree TreeItem newitem = new TreeItem(tiConn, j); newitem.setText(inf.getName()); newitem.setForeground(GUIResource.getInstance().getColorBlack()); newitem.setImage(GUIResource.getInstance().getImageConnection()); j++; ti = tiConn.getItems(); } else { j++; } } // tiConn.setExpanded(true); } //ni.setImage(gv.hop_image); //ni.setImage(gv.step_images_small[steptype]); // Refresh the Steps... // if (transMeta.haveStepsChanged() || complete) { tiStep.setText(STRING_STEPS); ti = tiStep.getItems(); // In complete refresh: delete all items first if (complete) { for (int i=0;i<ti.length;i++) ti[i].dispose(); ti = tiStep.getItems(); } // First delete no longer used items... log.logDebug(toString(), Messages.getString("Spoon.Log.CheckSteps"));//"check steps" for (int i=0;i<ti.length;i++) { String str = ti[i].getText(); log.logDebug(toString(), " "+Messages.getString("Spoon.Log.CheckStepTreeItem")+i+" : ["+str+"]"); StepMeta inf = transMeta.findStep(str); if (inf!=null) idx = transMeta.indexOfStep(inf); else idx=-1; if (idx<0 || idx>i) { log.logDebug(toString(), " "+ Messages.getString("Spoon.Log.RemoveTreeItem")+ "["+str+"]");//remove tree item ti[i].dispose(); } } ti = tiStep.getItems(); // Insert missing items in tree... int j=0; for (int i=0;i<transMeta.nrSteps();i++) { StepMeta inf = transMeta.getStep(i); String step_name = inf.getName(); String step_id = inf.getStepID(); String ti_name = ""; if (j<ti.length) ti_name = ti[j].getText(); if (!step_name.equalsIgnoreCase(ti_name)) { // insert at position j in tree TreeItem newitem = new TreeItem(tiStep, j); newitem.setText(inf.getName()); // Set the small image... Image img = (Image)GUIResource.getInstance().getImagesStepsSmall().get(step_id); newitem.setImage(img); j++; ti = tiStep.getItems(); } else { j++; } } // See if the colors are still OK! for (int i=0;i<ti.length;i++) { StepMeta inf = transMeta.findStep(ti[i].getText()); Color col = ti[i].getForeground(); Color newcol; if (transMeta.isStepUsedInTransHops(inf)) newcol=GUIResource.getInstance().getColorBlack(); else newcol=GUIResource.getInstance().getColorGray(); if (!newcol.equals(col)) ti[i].setForeground(newcol); } //tiStep.setExpanded(true); } // Refresh the Hops... // if (transMeta.haveHopsChanged() || complete) { tiHops.setText(STRING_HOPS); ti = tiHops.getItems(); // In complete refresh: delete all items first if (complete) { for (int i=0;i<ti.length;i++) ti[i].dispose(); ti = tiHops.getItems(); } // First delete no longer used items... for (int i=0;i<ti.length;i++) { String str = ti[i].getText(); TransHopMeta inf = transMeta.findTransHop(str); if (inf!=null) idx = transMeta.indexOfTransHop(inf); else idx=-1; if (idx<0 || idx>i) ti[i].dispose(); } ti = tiHops.getItems(); // Insert missing items in tree... int j=0; for (int i=0;i<transMeta.nrTransHops();i++) { TransHopMeta inf = transMeta.getTransHop(i); String trans_name = inf.toString(); String ti_name = ""; if (j<ti.length) ti_name = ti[j].getText(); if (!trans_name.equalsIgnoreCase(ti_name)) { // insert at position j in tree TreeItem newitem = new TreeItem(tiHops, j); newitem.setText(inf.toString()); newitem.setForeground(GUIResource.getInstance().getColorBlack()); newitem.setImage(GUIResource.getInstance().getImageHop()); j++; ti = tiHops.getItems(); } else { j++; } } // tiTrns.setExpanded(false); } selectionTree.setFocus(); setShellText(); } public void refreshGraph() { if (shell.isDisposed()) return; spoongraph.redraw(); setShellText(); } public void refreshHistory() { spoonhist.refreshHistory(); } public StepMeta newStep() { return newStep(true, true); } public StepMeta newStep(boolean openit, boolean rename) { TreeItem ti[] = selectionTree.getSelection(); StepMeta inf = null; if (ti.length==1) { String steptype = ti[0].getText(); log.logDebug(toString(), Messages.getString("Spoon.Log.NewStep")+steptype);//"New step: " inf = newStep(steptype, steptype, openit, rename); } return inf; } /** * Allocate new step, optionally open and rename it. * * @param name Name of the new step * @param description Description of the type of step * @param openit Open the dialog for this step? * @param rename Rename this step? * * @return The newly created StepMeta object. * */ public StepMeta newStep(String name, String description, boolean openit, boolean rename) { StepMeta inf = null; // See if we need to rename the step to avoid doubles! if (rename && transMeta.findStep(name)!=null) { int i=2; String newname = name+" "+i; while (transMeta.findStep(newname)!=null) { i++; newname = name+" "+i; } name=newname; } StepLoader steploader = StepLoader.getInstance(); StepPlugin stepPlugin = null; try { stepPlugin = steploader.findStepPluginWithDescription(description); if (stepPlugin!=null) { StepMetaInterface info = BaseStep.getStepInfo(stepPlugin, steploader); info.setDefault(); if (openit) { StepDialogInterface dialog = info.getDialog(shell, info, transMeta, name); name = dialog.open(); } inf=new StepMeta(log, stepPlugin.getID()[0], name, info); if (name!=null) // OK pressed in the dialog: we have a step-name { String newname=name; StepMeta stepMeta = transMeta.findStep(newname); int nr=2; while (stepMeta!=null) { newname = name+" "+nr; stepMeta = transMeta.findStep(newname); nr++; } if (nr>2) { inf.setName(newname); MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION); mb.setMessage(Messages.getString("Spoon.Dialog.ChangeStepname.Message",newname));//"This stepname already exists. Spoon changed the stepname to ["+newname+"]" mb.setText(Messages.getString("Spoon.Dialog.ChangeStepname.Title"));//"Info!" mb.open(); } inf.setLocation(20, 20); // default location at (20,20) transMeta.addStep(inf); // Save for later: // if openit is false: we drag&drop it onto the canvas! if (openit) { addUndoNew(new StepMeta[] { inf }, new int[] { transMeta.indexOfStep(inf) }); } // Also store it in the pluginHistory list... props.addPluginHistory(stepPlugin.getID()[0]); refreshTree(); } else { return null; // Cancel pressed in dialog. } setShellText(); } } catch(KettleException e) { String filename = stepPlugin.getErrorHelpFile(); if (stepPlugin!=null && filename!=null) { // OK, in stead of a normal error message, we give back the content of the error help file... (HTML) try { StringBuffer content=new StringBuffer(); System.out.println("Filename = "+filename); FileInputStream fis = new FileInputStream(new File(filename)); int ch = fis.read(); while (ch>=0) { content.append( (char)ch); ch = fis.read(); } System.out.println("Content = "+content); ShowBrowserDialog sbd = new ShowBrowserDialog(shell, Messages.getString("Spoon.Dialog.ErrorHelpText.Title"), content.toString());//"Error help text" sbd.open(); } catch(Exception ex) { new ErrorDialog(shell, props, Messages.getString("Spoon.Dialog.ErrorShowingHelpText.Title"), Messages.getString("Spoon.Dialog.ErrorShowingHelpText.Message"), ex);//"Error showing help text" } } else { new ErrorDialog(shell, props, Messages.getString("Spoon.Dialog.UnableCreateNewStep.Title"),Messages.getString("Spoon.Dialog.UnableCreateNewStep.Message") , e);//"Error creating step" "I was unable to create a new step" } return null; } catch(Throwable e) { if (!shell.isDisposed()) new ErrorDialog(shell, props, Messages.getString("Spoon.Dialog.ErrorCreatingStep.Title"), Messages.getString("Spoon.Dialog.UnableCreateNewStep.Message"), new Exception(e));//"Error creating step" return null; } return inf; } private void setTreeImages() { tiConn.setImage(GUIResource.getInstance().getImageConnection()); tiHops.setImage(GUIResource.getInstance().getImageHop()); tiStep.setImage(GUIResource.getInstance().getImageBol()); tiBase.setImage(GUIResource.getInstance().getImageBol()); tiPlug.setImage(GUIResource.getInstance().getImageBol()); TreeItem tiBaseCat[]=tiBase.getItems(); for (int x=0;x<tiBaseCat.length;x++) { tiBaseCat[x].setImage(GUIResource.getInstance().getImageBol()); TreeItem ti[] = tiBaseCat[x].getItems(); for (int i=0;i<ti.length;i++) { TreeItem stepitem = ti[i]; String description = stepitem.getText(); StepLoader steploader = StepLoader.getInstance(); StepPlugin sp = steploader.findStepPluginWithDescription(description); if (sp!=null) { Image stepimg = (Image)GUIResource.getInstance().getImagesStepsSmall().get(sp.getID()[0]); if (stepimg!=null) { stepitem.setImage(stepimg); } } } } TreeItem tiPlugCat[]=tiPlug.getItems(); for (int x=0;x<tiPlugCat.length;x++) { tiPlugCat[x].setImage(GUIResource.getInstance().getImageBol()); TreeItem ti[] = tiPlugCat[x].getItems(); for (int i=0;i<ti.length;i++) { TreeItem stepitem = ti[i]; String description = stepitem.getText(); StepLoader steploader = StepLoader.getInstance(); StepPlugin sp = steploader.findStepPluginWithDescription(description); if (sp!=null) { Image stepimg = (Image)GUIResource.getInstance().getImagesStepsSmall().get(sp.getID()); if (stepimg!=null) { stepitem.setImage(stepimg); } } } } } public DatabaseMeta getConnection(String name) { int i; for (i=0;i<transMeta.nrDatabases();i++) { DatabaseMeta ci = transMeta.getDatabase(i); if (ci.getName().equalsIgnoreCase(name)) { return ci; } } return null; } public void setShellText() { String fname = transMeta.getFilename(); if (shell.isDisposed()) return; if (rep!=null) { String repository = "["+getRepositoryName()+"]"; String transname = transMeta.getName(); if (transname==null) transname=Messages.getString("Spoon.Various.NoName");//"[no name]" shell.setText(APPL_TITLE+" - "+repository+" "+transname+(transMeta.hasChanged()?(" "+Messages.getString("Spoon.Various.Changed")):""));//(changed) } else { String repository = Messages.getString("Spoon.Various.NoRepository");//"[no repository]" if (fname!=null) { shell.setText(APPL_TITLE+" - "+repository+" File: "+fname+(transMeta.hasChanged()?(" "+Messages.getString("Spoon.Various.Changed")):"")); } else { shell.setText(APPL_TITLE+" - "+repository+" "+(transMeta.hasChanged()?(" "+Messages.getString("Spoon.Various.Changed")):"")); } } } public void setFilename(String fname) { if (fname!=null) transMeta.setFilename(fname); setShellText(); } private void printFile() { PrintSpool ps = new PrintSpool(); Printer printer = ps.getPrinter(shell); // Create an image of the screen Point max = transMeta.getMaximum(); Image img = spoongraph.getTransformationImage(printer, max.x, max.y); ps.printImage(shell, props, img); img.dispose(); ps.dispose(); } private boolean setTrans() { TransDialog tid = new TransDialog(shell, SWT.NONE, transMeta, rep); TransMeta ti = tid.open(); setShellText(); return ti!=null; } public void saveSettings() { WindowProperty winprop = new WindowProperty(shell); winprop.setName(APPL_TITLE); props.setScreen(winprop); props.setLogLevel(log.getLogLevelDesc()); props.setLogFilter(log.getFilter()); props.setSashWeights(sashform.getWeights()); props.saveProps(); } public void loadSettings() { log.setLogLevel(props.getLogLevel()); log.setFilter(props.getLogFilter()); transMeta.setMaxUndo(props.getMaxUndo()); transMeta.getDbCache().setActive(props.useDBCache()); } public void changeLooks() { props.setLook(selectionTree); props.setLook(tabfolder, Props.WIDGET_STYLE_TAB); spoongraph.newProps(); refreshTree(); refreshGraph(); } public void undoAction() { spoongraph.forceFocus(); TransAction ta = transMeta.previousUndo(); if (ta==null) return; setUndoMenu(); // something changed: change the menu switch(ta.getType()) { // // NEW // // We created a new step : undo this... case TransAction.TYPE_ACTION_NEW_STEP: // Delete the step at correct location: for (int i=ta.getCurrent().length-1;i>=0;i--) { int idx = ta.getCurrentIndex()[i]; transMeta.removeStep(idx); } refreshTree(); refreshGraph(); break; // We created a new connection : undo this... case TransAction.TYPE_ACTION_NEW_CONNECTION: // Delete the connection at correct location: for (int i=ta.getCurrent().length-1;i>=0;i--) { int idx = ta.getCurrentIndex()[i]; transMeta.removeDatabase(idx); } refreshTree(); refreshGraph(); break; // We created a new note : undo this... case TransAction.TYPE_ACTION_NEW_NOTE: // Delete the note at correct location: for (int i=ta.getCurrent().length-1;i>=0;i--) { int idx = ta.getCurrentIndex()[i]; transMeta.removeNote(idx); } refreshTree(); refreshGraph(); break; // We created a new hop : undo this... case TransAction.TYPE_ACTION_NEW_HOP: // Delete the hop at correct location: for (int i=ta.getCurrent().length-1;i>=0;i--) { int idx = ta.getCurrentIndex()[i]; transMeta.removeTransHop(idx); } refreshTree(); refreshGraph(); break; // // DELETE // // We delete a step : undo this... case TransAction.TYPE_ACTION_DELETE_STEP: // un-Delete the step at correct location: re-insert for (int i=0;i<ta.getCurrent().length;i++) { StepMeta stepMeta = (StepMeta)ta.getCurrent()[i]; int idx = ta.getCurrentIndex()[i]; transMeta.addStep(idx, stepMeta); } refreshTree(); refreshGraph(); break; // We deleted a connection : undo this... case TransAction.TYPE_ACTION_DELETE_CONNECTION: // re-insert the connection at correct location: for (int i=0;i<ta.getCurrent().length;i++) { DatabaseMeta ci = (DatabaseMeta)ta.getCurrent()[i]; int idx = ta.getCurrentIndex()[i]; transMeta.addDatabase(idx, ci); } refreshTree(); refreshGraph(); break; // We delete new note : undo this... case TransAction.TYPE_ACTION_DELETE_NOTE: // re-insert the note at correct location: for (int i=0;i<ta.getCurrent().length;i++) { NotePadMeta ni = (NotePadMeta)ta.getCurrent()[i]; int idx = ta.getCurrentIndex()[i]; transMeta.addNote(idx, ni); } refreshTree(); refreshGraph(); break; // We deleted a hop : undo this... case TransAction.TYPE_ACTION_DELETE_HOP: // re-insert the hop at correct location: for (int i=0;i<ta.getCurrent().length;i++) { TransHopMeta hi = (TransHopMeta)ta.getCurrent()[i]; int idx = ta.getCurrentIndex()[i]; // Build a new hop: StepMeta from = transMeta.findStep(hi.getFromStep().getName()); StepMeta to = transMeta.findStep(hi.getToStep().getName()); TransHopMeta hinew = new TransHopMeta(from, to); transMeta.addTransHop(idx, hinew); } refreshTree(); refreshGraph(); break; // // CHANGE // // We changed a step : undo this... case TransAction.TYPE_ACTION_CHANGE_STEP: // Delete the current step, insert previous version. for (int i=0;i<ta.getCurrent().length;i++) { StepMeta prev = (StepMeta)ta.getPrevious()[i]; int idx = ta.getCurrentIndex()[i]; transMeta.removeStep(idx); transMeta.addStep(idx, prev); } refreshTree(); refreshGraph(); break; // We changed a connection : undo this... case TransAction.TYPE_ACTION_CHANGE_CONNECTION: // Delete & re-insert for (int i=0;i<ta.getCurrent().length;i++) { DatabaseMeta prev = (DatabaseMeta)ta.getPrevious()[i]; int idx = ta.getCurrentIndex()[i]; transMeta.removeDatabase(idx); transMeta.addDatabase(idx, prev); } refreshTree(); refreshGraph(); break; // We changed a note : undo this... case TransAction.TYPE_ACTION_CHANGE_NOTE: // Delete & re-insert for (int i=0;i<ta.getCurrent().length;i++) { int idx = ta.getCurrentIndex()[i]; transMeta.removeNote(idx); NotePadMeta prev = (NotePadMeta)ta.getPrevious()[i]; transMeta.addNote(idx, prev); } refreshTree(); refreshGraph(); break; // We changed a hop : undo this... case TransAction.TYPE_ACTION_CHANGE_HOP: // Delete & re-insert for (int i=0;i<ta.getCurrent().length;i++) { TransHopMeta prev = (TransHopMeta)ta.getPrevious()[i]; int idx = ta.getCurrentIndex()[i]; transMeta.removeTransHop(idx); transMeta.addTransHop(idx, prev); } refreshTree(); refreshGraph(); break; // // POSITION // // The position of a step has changed: undo this... case TransAction.TYPE_ACTION_POSITION_STEP: // Find the location of the step: for (int i = 0; i < ta.getCurrentIndex().length; i++) { StepMeta stepMeta = transMeta.getStep(ta.getCurrentIndex()[i]); stepMeta.setLocation(ta.getPreviousLocation()[i]); } refreshGraph(); break; // The position of a note has changed: undo this... case TransAction.TYPE_ACTION_POSITION_NOTE: for (int i=0;i<ta.getCurrentIndex().length;i++) { int idx = ta.getCurrentIndex()[i]; NotePadMeta npi = transMeta.getNote(idx); Point prev = ta.getPreviousLocation()[i]; npi.setLocation(prev); } refreshGraph(); break; default: break; } // OK, now check if we need to do this again... if (transMeta.viewNextUndo()!=null) { if (transMeta.viewNextUndo().getNextAlso()) undoAction(); } } public void redoAction() { spoongraph.forceFocus(); TransAction ta = transMeta.nextUndo(); if (ta==null) return; setUndoMenu(); // something changed: change the menu switch(ta.getType()) { // // NEW // case TransAction.TYPE_ACTION_NEW_STEP: // re-delete the step at correct location: for (int i=0;i<ta.getCurrent().length;i++) { StepMeta stepMeta = (StepMeta)ta.getCurrent()[i]; int idx = ta.getCurrentIndex()[i]; transMeta.addStep(idx, stepMeta); refreshTree(); refreshGraph(); } break; case TransAction.TYPE_ACTION_NEW_CONNECTION: // re-insert the connection at correct location: for (int i=0;i<ta.getCurrent().length;i++) { DatabaseMeta ci = (DatabaseMeta)ta.getCurrent()[i]; int idx = ta.getCurrentIndex()[i]; transMeta.addDatabase(idx, ci); refreshTree(); refreshGraph(); } break; case TransAction.TYPE_ACTION_NEW_NOTE: // re-insert the note at correct location: for (int i=0;i<ta.getCurrent().length;i++) { NotePadMeta ni = (NotePadMeta)ta.getCurrent()[i]; int idx = ta.getCurrentIndex()[i]; transMeta.addNote(idx, ni); refreshTree(); refreshGraph(); } break; case TransAction.TYPE_ACTION_NEW_HOP: // re-insert the hop at correct location: for (int i=0;i<ta.getCurrent().length;i++) { TransHopMeta hi = (TransHopMeta)ta.getCurrent()[i]; int idx = ta.getCurrentIndex()[i]; transMeta.addTransHop(idx, hi); refreshTree(); refreshGraph(); } break; // // DELETE // case TransAction.TYPE_ACTION_DELETE_STEP: // re-remove the step at correct location: for (int i=ta.getCurrent().length-1;i>=0;i--) { int idx = ta.getCurrentIndex()[i]; transMeta.removeStep(idx); } refreshTree(); refreshGraph(); break; case TransAction.TYPE_ACTION_DELETE_CONNECTION: // re-remove the connection at correct location: for (int i=ta.getCurrent().length-1;i>=0;i--) { int idx = ta.getCurrentIndex()[i]; transMeta.removeDatabase(idx); } refreshTree(); refreshGraph(); break; case TransAction.TYPE_ACTION_DELETE_NOTE: // re-remove the note at correct location: for (int i=ta.getCurrent().length-1;i>=0;i--) { int idx = ta.getCurrentIndex()[i]; transMeta.removeNote(idx); } refreshTree(); refreshGraph(); break; case TransAction.TYPE_ACTION_DELETE_HOP: // re-remove the hop at correct location: for (int i=ta.getCurrent().length-1;i>=0;i--) { int idx = ta.getCurrentIndex()[i]; transMeta.removeTransHop(idx); } refreshTree(); refreshGraph(); break; // // CHANGE // // We changed a step : undo this... case TransAction.TYPE_ACTION_CHANGE_STEP: // Delete the current step, insert previous version. for (int i=0;i<ta.getCurrent().length;i++) { StepMeta stepMeta = (StepMeta)ta.getCurrent()[i]; int idx = ta.getCurrentIndex()[i]; transMeta.removeStep(idx); transMeta.addStep(idx, stepMeta); } refreshTree(); refreshGraph(); break; // We changed a connection : undo this... case TransAction.TYPE_ACTION_CHANGE_CONNECTION: // Delete & re-insert for (int i=0;i<ta.getCurrent().length;i++) { DatabaseMeta ci = (DatabaseMeta)ta.getCurrent()[i]; int idx = ta.getCurrentIndex()[i]; transMeta.removeDatabase(idx); transMeta.addDatabase(idx, ci); } refreshTree(); refreshGraph(); break; // We changed a note : undo this... case TransAction.TYPE_ACTION_CHANGE_NOTE: // Delete & re-insert for (int i=0;i<ta.getCurrent().length;i++) { NotePadMeta ni = (NotePadMeta)ta.getCurrent()[i]; int idx = ta.getCurrentIndex()[i]; transMeta.removeNote(idx); transMeta.addNote(idx, ni); } refreshTree(); refreshGraph(); break; // We changed a hop : undo this... case TransAction.TYPE_ACTION_CHANGE_HOP: // Delete & re-insert for (int i=0;i<ta.getCurrent().length;i++) { TransHopMeta hi = (TransHopMeta)ta.getCurrent()[i]; int idx = ta.getCurrentIndex()[i]; transMeta.removeTransHop(idx); transMeta.addTransHop(idx, hi); } refreshTree(); refreshGraph(); break; // // CHANGE POSITION // case TransAction.TYPE_ACTION_POSITION_STEP: for (int i=0;i<ta.getCurrentIndex().length;i++) { // Find & change the location of the step: StepMeta stepMeta = transMeta.getStep(ta.getCurrentIndex()[i]); stepMeta.setLocation(ta.getCurrentLocation()[i]); } refreshGraph(); break; case TransAction.TYPE_ACTION_POSITION_NOTE: for (int i=0;i<ta.getCurrentIndex().length;i++) { int idx = ta.getCurrentIndex()[i]; NotePadMeta npi = transMeta.getNote(idx); Point curr = ta.getCurrentLocation()[i]; npi.setLocation(curr); } refreshGraph(); break; default: break; } // OK, now check if we need to do this again... if (transMeta.viewNextUndo()!=null) { if (transMeta.viewNextUndo().getNextAlso()) redoAction(); } } public void setUndoMenu() { if (shell.isDisposed()) return; TransAction prev = transMeta.viewThisUndo(); TransAction next = transMeta.viewNextUndo(); if (prev!=null) { miEditUndo.setEnabled(true); miEditUndo.setText(Messages.getString("Spoon.Menu.Undo.Available", prev.toString()));//"Undo : "+prev.toString()+" \tCTRL-Z" } else { miEditUndo.setEnabled(false); miEditUndo.setText(Messages.getString("Spoon.Menu.Undo.NotAvailable"));//"Undo : not available \tCTRL-Z" } if (next!=null) { miEditRedo.setEnabled(true); miEditRedo.setText(Messages.getString("Spoon.Menu.Redo.Available",next.toString()));//"Redo : "+next.toString()+" \tCTRL-Y" } else { miEditRedo.setEnabled(false); miEditRedo.setText(Messages.getString("Spoon.Menu.Redo.NotAvailable"));//"Redo : not available \tCTRL-Y" } } public void addUndoNew(Object obj[], int position[]) { addUndoNew(obj, position, false); } public void addUndoNew(Object obj[], int position[], boolean nextAlso) { // New object? transMeta.addUndo(obj, null, position, null, null, TransMeta.TYPE_UNDO_NEW, nextAlso); setUndoMenu(); } // Undo delete object public void addUndoDelete(Object obj[], int position[]) { addUndoDelete(obj, position, false); } // Undo delete object public void addUndoDelete(Object obj[], int position[], boolean nextAlso) { transMeta.addUndo(obj, null, position, null, null, TransMeta.TYPE_UNDO_DELETE, nextAlso); setUndoMenu(); } // Change of step, connection, hop or note... public void addUndoPosition(Object obj[], int pos[], Point prev[], Point curr[]) { addUndoPosition(obj, pos, prev, curr, false); } // Change of step, connection, hop or note... public void addUndoPosition(Object obj[], int pos[], Point prev[], Point curr[], boolean nextAlso) { // It's better to store the indexes of the objects, not the objects itself! transMeta.addUndo(obj, null, pos, prev, curr, TransMeta.TYPE_UNDO_POSITION, nextAlso); setUndoMenu(); } // Change of step, connection, hop or note... public void addUndoChange(Object from[], Object to[], int[] pos) { addUndoChange(from, to, pos, false); } // Change of step, connection, hop or note... public void addUndoChange(Object from[], Object to[], int[] pos, boolean nextAlso) { transMeta.addUndo(from, to, pos, null, null, TransMeta.TYPE_UNDO_CHANGE, nextAlso); setUndoMenu(); } /** * Checks *all* the steps in the transformation, puts the result in remarks list */ public void checkTrans() { checkTrans(false); } /** * Check the steps in a transformation * * @param only_selected True: Check only the selected steps... */ public void checkTrans(boolean only_selected) { CheckTransProgressDialog ctpd = new CheckTransProgressDialog(log, props, shell, transMeta, remarks, only_selected); ctpd.open(); // manages the remarks arraylist... showLastTransCheck(); } /** * Show the remarks of the last transformation check that was run. * @see #checkTrans() */ public void showLastTransCheck() { CheckResultDialog crd = new CheckResultDialog(shell, SWT.NONE, remarks); String stepname = crd.open(); if (stepname!=null) { // Go to the indicated step! StepMeta stepMeta = transMeta.findStep(stepname); if (stepMeta!=null) { editStepInfo(stepMeta); } } } public void clearDBCache() { // Determine what menu we selected from... TreeItem ti[] = selectionTree.getSelection(); // Then call editConnection or editStep or editTrans if (ti.length==1) { String name = ti[0].getText(); TreeItem parent = ti[0].getParentItem(); if (parent != null) { String type = parent.getText(); if (type.equalsIgnoreCase(STRING_CONNECTIONS)) { transMeta.getDbCache().clear(name); } } else { if (name.equalsIgnoreCase(STRING_CONNECTIONS)) transMeta.getDbCache().clear(null); } } } public void exploreDB() { // Determine what menu we selected from... TreeItem ti[] = selectionTree.getSelection(); // Then call editConnection or editStep or editTrans if (ti.length==1) { String name = ti[0].getText(); TreeItem parent = ti[0].getParentItem(); if (parent != null) { String type = parent.getText(); if (type.equalsIgnoreCase(STRING_CONNECTIONS)) { DatabaseMeta dbinfo = transMeta.findDatabase(name); if (dbinfo!=null) { DatabaseExplorerDialog std = new DatabaseExplorerDialog(shell, props, SWT.NONE, dbinfo, transMeta.getDatabases(), true ); std.open(); } else { MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR ); mb.setMessage(Messages.getString("Spoon.Dialog.CannotFindConnection.Message"));//"Couldn't find connection, please refresh the tree (F5)!" mb.setText(Messages.getString("Spoon.Dialog.CannotFindConnection.Title"));//"Error!" mb.open(); } } } else { if (name.equalsIgnoreCase(STRING_CONNECTIONS)) transMeta.getDbCache().clear(null); } } } public void analyseImpact() { AnalyseImpactProgressDialog aipd = new AnalyseImpactProgressDialog(log, props, shell, transMeta, impact); impactHasRun = aipd.open(); if (impactHasRun) showLastImpactAnalyses(); } public void showLastImpactAnalyses() { ArrayList rows = new ArrayList(); for (int i=0;i<impact.size();i++) { DatabaseImpact ii = (DatabaseImpact)impact.get(i); rows.add(ii.getRow()); } if (rows.size()>0) { // Display all the rows... PreviewRowsDialog prd = new PreviewRowsDialog(shell, SWT.NONE, "-", rows); prd.setTitleMessage(Messages.getString("Spoon.Dialog.ImpactAnalyses.Title"), Messages.getString("Spoon.Dialog.ImpactAnalyses.Message"));//"Impact analyses" "Result of analyses:" prd.open(); } else { MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION ); if (impactHasRun) { mb.setMessage(Messages.getString("Spoon.Dialog.TransformationNoImpactOnDatabase.Message"));//"As far as I can tell, this transformation has no impact on any database." } else { mb.setMessage(Messages.getString("Spoon.Dialog.RunImpactAnalysesFirst.Message"));//"Please run the impact analyses first on this transformation." } mb.setText(Messages.getString("Spoon.Dialog.ImpactAnalyses.Title"));//Impact mb.open(); } } /** * Get & show the SQL required to run the loaded transformation... * */ public void getSQL() { GetSQLProgressDialog pspd = new GetSQLProgressDialog(log, props, shell, transMeta); ArrayList stats = pspd.open(); if (stats!=null) // null means error, but we already displayed the error { if (stats.size()>0) { SQLStatementsDialog ssd = new SQLStatementsDialog(shell, SWT.NONE, stats); ssd.open(); } else { MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION ); mb.setMessage(Messages.getString("Spoon.Dialog.NoSQLNeedEexecuted.Message"));//As far as I can tell, no SQL statements need to be executed before this transformation can run. mb.setText(Messages.getString("Spoon.Dialog.NoSQLNeedEexecuted.Title"));//"SQL" mb.open(); } } } public void toClipboard(String cliptext) { props.toClipboard(cliptext); } public String fromClipboard() { return props.fromClipboard(); } /** * Paste transformation from the clipboard... * */ public void pasteTransformation() { log.logDetailed(toString(), Messages.getString("Spoon.Log.PasteTransformationFromClipboard"));//"Paste transformation from the clipboard!" if (showChangedWarning()) { String xml = fromClipboard(); try { Document doc = XMLHandler.loadXMLString(xml); transMeta = new TransMeta(XMLHandler.getSubNode(doc, "transformation")); refreshGraph(); refreshTree(true); } catch(KettleException e) { new ErrorDialog(shell, props, Messages.getString("Spoon.Dialog.ErrorPastingTransformation.Title"), Messages.getString("Spoon.Dialog.ErrorPastingTransformation.Message"), e);//Error pasting transformation "An error occurred pasting a transformation from the clipboard" } } } public void copyTransformation() { toClipboard(XMLHandler.getXMLHeader()+transMeta.getXML()); } public void copyTransformationImage() { Clipboard clipboard = props.getNewClipboard(); Point area = transMeta.getMaximum(); Image image = spoongraph.getTransformationImage(Display.getCurrent(), area.x, area.y); clipboard.setContents(new Object[] { image.getImageData() }, new Transfer[]{ImageDataTransfer.getInstance()}); /** System.out.println("image obtained: "+area.x+"x"+area.y); ShowImageDialog sid = new ShowImageDialog(shell, image); sid.open(); */ } /** * Shows a wizard that creates a new database connection... * */ private void createDatabaseWizard() { CreateDatabaseWizard cdw=new CreateDatabaseWizard(); DatabaseMeta newDBInfo=cdw.createAndRunDatabaseWizard(shell, props, transMeta.getDatabases()); if(newDBInfo!=null){ //finished transMeta.addDatabase(newDBInfo); refreshTree(true); refreshGraph(); } } /** * Create a transformation that extracts tables & data from a database.<p><p> * * 0) Select the database to rip<p> * 1) Select the table in the database to copy<p> * 2) Select the database to dump to<p> * 3) Select the repository directory in which it will end up<p> * 4) Select a name for the new transformation<p> * 6) Create 1 transformation for the selected table<p> */ private void copyTableWizard() { if (showChangedWarning()) { final CopyTableWizardPage1 page1 = new CopyTableWizardPage1("1", transMeta.getDatabases()); page1.createControl(shell); final CopyTableWizardPage2 page2 = new CopyTableWizardPage2("2"); page2.createControl(shell); final CopyTableWizardPage3 page3 = new CopyTableWizardPage3 ("3", rep); page3.createControl(shell); Wizard wizard = new Wizard() { public boolean performFinish() { return copyTable(page3.getTransformationName(), page3.getDirectory(), page1.getSourceDatabase(), page1.getTargetDatabase(), page2.getSelection() ); } /** * @see org.eclipse.jface.wizard.Wizard#canFinish() */ public boolean canFinish() { return page3.canFinish(); } }; wizard.addPage(page1); wizard.addPage(page2); wizard.addPage(page3); WizardDialog wd = new WizardDialog(shell, wizard); wd.setMinimumPageSize(700,400); wd.open(); } } public boolean copyTable( String transname, RepositoryDirectory repdir, DatabaseMeta sourceDBInfo, DatabaseMeta targetDBInfo, String tablename ) { try { // // Create a new transformation... // TransMeta ti = new TransMeta(); ti.setName(transname); ti.setDirectory(repdir); ti.setDatabases(transMeta.getDatabases()); // // Add a note // String note = Messages.getString("Spoon.Message.Note.ReadInformationFromTableOnDB",tablename,sourceDBInfo.getDatabaseName() )+Const.CR;//"Reads information from table ["+tablename+"] on database ["+sourceDBInfo+"]" note+=Messages.getString("Spoon.Message.Note.WriteInformationToTableOnDB",tablename,targetDBInfo.getDatabaseName() );//"After that, it writes the information to table ["+tablename+"] on database ["+targetDBInfo+"]" NotePadMeta ni = new NotePadMeta(note, 150, 10, -1, -1); ti.addNote(ni); // // create the source step... // String fromstepname = Messages.getString("Spoon.Message.Note.ReadFromTable",tablename); //"read from ["+tablename+"]"; TableInputMeta tii = new TableInputMeta(); tii.setDatabaseMeta(sourceDBInfo); tii.setSQL("SELECT * FROM "+tablename); StepLoader steploader = StepLoader.getInstance(); String fromstepid = steploader.getStepPluginID(tii); StepMeta fromstep = new StepMeta(log, fromstepid, fromstepname, (StepMetaInterface)tii ); fromstep.setLocation(150,100); fromstep.setDraw(true); fromstep.setDescription(Messages.getString("Spoon.Message.Note.ReadInformationFromTableOnDB",tablename,sourceDBInfo.getDatabaseName() )); ti.addStep(fromstep); // // add logic to rename fields in case any of the field names contain reserved words... // Use metadata logic in SelectValues, use SelectValueInfo... // Database sourceDB = new Database(sourceDBInfo); sourceDB.connect(); // Get the fields for the input table... Row fields = sourceDB.getTableFields(tablename); // See if we need to deal with reserved words... int nrReserved = targetDBInfo.getNrReservedWords(fields); if (nrReserved>0) { SelectValuesMeta svi = new SelectValuesMeta(); svi.allocate(0,0,nrReserved); int nr = 0; for (int i=0;i<fields.size();i++) { Value v = fields.getValue(i); if (targetDBInfo.isReservedWord( v.getName() ) ) { svi.getMetaName()[nr] = v.getName(); svi.getMetaRename()[nr] = targetDBInfo.quoteField( v.getName() ); nr++; } } String selstepname =Messages.getString("Spoon.Message.Note.HandleReservedWords"); //"Handle reserved words"; String selstepid = steploader.getStepPluginID(svi); StepMeta selstep = new StepMeta(log, selstepid, selstepname, (StepMetaInterface)svi ); selstep.setLocation(350,100); selstep.setDraw(true); selstep.setDescription(Messages.getString("Spoon.Message.Note.RenamesReservedWords",targetDBInfo.getDatabaseTypeDesc()) );//"Renames reserved words for "+targetDBInfo.getDatabaseTypeDesc() ti.addStep(selstep); TransHopMeta shi = new TransHopMeta(fromstep, selstep); ti.addTransHop(shi); fromstep = selstep; } // // Create the target step... // // // Add the TableOutputMeta step... // String tostepname = Messages.getString("Spoon.Message.Note.WriteToTable",tablename); // "write to ["+tablename+"]"; TableOutputMeta toi = new TableOutputMeta(); toi.setDatabase( targetDBInfo ); toi.setTablename( tablename ); toi.setCommitSize( 200 ); toi.setTruncateTable( true ); String tostepid = steploader.getStepPluginID(toi); StepMeta tostep = new StepMeta(log, tostepid, tostepname, (StepMetaInterface)toi ); tostep.setLocation(550,100); tostep.setDraw(true); tostep.setDescription(Messages.getString("Spoon.Message.Note.WriteInformationToTableOnDB2",tablename,targetDBInfo.getDatabaseName() ));//"Write information to table ["+tablename+"] on database ["+targetDBInfo+"]" ti.addStep(tostep); // // Add a hop between the two steps... // TransHopMeta hi = new TransHopMeta(fromstep, tostep); ti.addTransHop(hi); // OK, if we're still here: overwrite the current transformation... transMeta = ti; refreshGraph(); refreshTree(true); } catch(Exception e) { new ErrorDialog(shell, props, Messages.getString("Spoon.Dialog.UnexpectedError.Title"), Messages.getString("Spoon.Dialog.UnexpectedError.Message"), new KettleException(e.getMessage(), e));//"Unexpected error" "An unexpected error occurred creating the new transformation" return false; } return true; } public String toString() { return APP_NAME; } /** * This is the main procedure for Spoon. * * @param a Arguments are available in the "Get System Info" step. */ public static void main (String [] a) throws KettleException { EnvUtil.environmentInit(); ArrayList args = new ArrayList(); for (int i=0;i<a.length;i++) args.add(a[i]); Display display = new Display(); Splash splash = new Splash(display); StringBuffer optionRepname, optionUsername, optionPassword, optionTransname, optionFilename, optionDirname, optionLogfile, optionLoglevel; CommandLineOption options[] = new CommandLineOption[] { new CommandLineOption("rep", "Repository name", optionRepname=new StringBuffer()), new CommandLineOption("user", "Repository username", optionUsername=new StringBuffer()), new CommandLineOption("pass", "Repository password", optionPassword=new StringBuffer()), new CommandLineOption("trans", "The name of the transformation to launch", optionTransname=new StringBuffer()), new CommandLineOption("dir", "The directory (don't forget the leading /)", optionDirname=new StringBuffer()), new CommandLineOption("file", "The filename (Transformation in XML) to launch", optionFilename=new StringBuffer()), new CommandLineOption("level", "The logging level (Basic, Detailed, Debug, Rowlevel, Error, Nothing)", optionLoglevel=new StringBuffer()), new CommandLineOption("logfile", "The logging file to write to", optionLogfile=new StringBuffer()), new CommandLineOption("log", "The logging file to write to (deprecated)", optionLogfile=new StringBuffer(), false, true), }; // Parse the options... CommandLineOption.parseArguments(args, options); String kettleRepname = Const.getEnvironmentVariable("KETTLE_REPOSITORY", null); String kettleUsername = Const.getEnvironmentVariable("KETTLE_USER", null); String kettlePassword = Const.getEnvironmentVariable("KETTLE_PASSWORD", null); if (!Const.isEmpty(kettleRepname )) optionRepname = new StringBuffer(kettleRepname); if (!Const.isEmpty(kettleUsername)) optionUsername = new StringBuffer(kettleUsername); if (!Const.isEmpty(kettlePassword)) optionPassword = new StringBuffer(kettlePassword); // Before anything else, check the runtime version!!! String version = Const.JAVA_VERSION; if ("1.4".compareToIgnoreCase(version)>0) { System.out.println("The System is running on Java version "+version); System.out.println("Unfortunately, it needs version 1.4 or higher to run."); return; } // Set default Locale: Locale.setDefault(Const.DEFAULT_LOCALE); LogWriter log; if (Const.isEmpty(optionLogfile)) { log=LogWriter.getInstance(Const.SPOON_LOG_FILE, false, LogWriter.LOG_LEVEL_BASIC); } else { log=LogWriter.getInstance( optionLogfile.toString(), true, LogWriter.LOG_LEVEL_BASIC ); } if (log.getRealFilename()!=null) log.logBasic(APP_NAME, Messages.getString("Spoon.Log.LoggingToFile")+log.getRealFilename());//"Logging goes to " if (!Const.isEmpty(optionLoglevel)) { log.setLogLevel(optionLoglevel.toString()); log.logBasic(APP_NAME, Messages.getString("Spoon.Log.LoggingAtLevel")+log.getLogLevelDesc());//"Logging is at level : " } /* Load the plugins etc.*/ StepLoader stloader = StepLoader.getInstance(); if (!stloader.read()) { log.logError(APP_NAME, Messages.getString("Spoon.Log.ErrorLoadingAndHaltSystem"));//Error loading steps & plugins... halting Spoon! return; } /* Load the plugins etc. we need to load jobentry*/ JobEntryLoader jeloader = JobEntryLoader.getInstance(); if (!jeloader.read()) { log.logError("Spoon", "Error loading job entries & plugins... halting Kitchen!"); return; } final Spoon win = new Spoon(log, display, null); win.setDestroy(true); win.setArguments((String[])args.toArray(new String[args.size()])); log.logBasic(APP_NAME, Messages.getString("Spoon.Log.MainWindowCreated"));//Main window is created. RepositoryMeta repinfo = null; UserInfo userinfo = null; if (Const.isEmpty(optionRepname) && Const.isEmpty(optionFilename) && win.props.showRepositoriesDialogAtStartup()) { log.logBasic(APP_NAME, Messages.getString("Spoon.Log.AskingForRepository"));//"Asking for repository" int perms[] = new int[] { PermissionMeta.TYPE_PERMISSION_TRANSFORMATION }; splash.hide(); RepositoriesDialog rd = new RepositoriesDialog(win.disp, SWT.NONE, perms, Messages.getString("Spoon.Application.Name"));//"Spoon" if (rd.open()) { repinfo = rd.getRepository(); userinfo = rd.getUser(); if (!userinfo.useTransformations()) { MessageBox mb = new MessageBox(win.shell, SWT.OK | SWT.ICON_ERROR ); mb.setMessage(Messages.getString("Spoon.Dialog.RepositoryUserCannotWork.Message"));//"Sorry, this repository user can't work with transformations from the repository." mb.setText(Messages.getString("Spoon.Dialog.RepositoryUserCannotWork.Title"));//"Error!" mb.open(); userinfo = null; repinfo = null; } } else { // Exit point: user pressed CANCEL! if (rd.isCancelled()) { splash.dispose(); win.quitFile(); return; } } } try { // Read kettle transformation specified on command-line? if (!Const.isEmpty(optionRepname) || !Const.isEmpty(optionFilename)) { if (!Const.isEmpty(optionRepname)) { RepositoriesMeta repsinfo = new RepositoriesMeta(log); if (repsinfo.readData()) { repinfo = repsinfo.findRepository(optionRepname.toString()); if (repinfo!=null) { // Define and connect to the repository... win.rep = new Repository(log, repinfo, userinfo); if (win.rep.connect(Messages.getString("Spoon.Application.Name")))//"Spoon" { if (Const.isEmpty(optionDirname)) optionDirname=new StringBuffer(RepositoryDirectory.DIRECTORY_SEPARATOR); // Check username, password win.rep.userinfo = new UserInfo(win.rep, optionUsername.toString(), optionPassword.toString()); if (win.rep.userinfo.getID()>0) { - RepositoryDirectory repdir = win.rep.getDirectoryTree().findDirectory(optionDirname.toString()); - if (repdir!=null) - { - win.transMeta = new TransMeta(win.rep, optionTransname.toString(), repdir); - win.setFilename(optionRepname.toString()); - win.transMeta.clearChanged(); - } - else + // OK, if we have a specified transformation, try to load it... + // If not, keep the repository logged in. + if (!Const.isEmpty(optionTransname)) { - log.logError(APP_NAME, Messages.getString("Spoon.Log.UnableFindDirectory",optionDirname.toString()));//"Can't find directory ["+dirname+"] in the repository." + RepositoryDirectory repdir = win.rep.getDirectoryTree().findDirectory(optionDirname.toString()); + if (repdir!=null) + { + win.transMeta = new TransMeta(win.rep, optionTransname.toString(), repdir); + win.setFilename(optionRepname.toString()); + win.transMeta.clearChanged(); + } + else + { + log.logError(APP_NAME, Messages.getString("Spoon.Log.UnableFindDirectory",optionDirname.toString()));//"Can't find directory ["+dirname+"] in the repository." + } } } else { log.logError(APP_NAME, Messages.getString("Spoon.Log.UnableVerifyUser"));//"Can't verify username and password." win.rep.disconnect(); win.rep=null; } } else { log.logError(APP_NAME, Messages.getString("Spoon.Log.UnableConnectToRepository"));//"Can't connect to the repository." } } else { log.logError(APP_NAME, Messages.getString("Spoon.Log.NoRepositoryRrovided"));//"No repository provided, can't load transformation." } } else { log.logError(APP_NAME, Messages.getString("Spoon.Log.NoRepositoriesDefined"));//"No repositories defined on this system." } } else if (!Const.isEmpty(optionFilename)) { win.transMeta = new TransMeta(optionFilename.toString()); win.setFilename(optionFilename.toString()); win.transMeta.clearChanged(); } } else // Normal operations, nothing on the commandline... { // Can we connect to the repository? if (repinfo!=null && userinfo!=null) { win.rep = new Repository(log, repinfo, userinfo); if (!win.rep.connect(Messages.getString("Spoon.Application.Name"))) //"Spoon" { win.rep = null; } } if (win.props.openLastFile()) { log.logDetailed(APP_NAME, Messages.getString("Spoon.Log.TryingOpenLastUsedFile"));//"Trying to open the last file used." String lastfiles[] = win.props.getLastFiles(); String lastdirs[] = win.props.getLastDirs(); boolean lasttypes[] = win.props.getLastTypes(); String lastrepos[] = win.props.getLastRepositories(); if (lastfiles.length>0) { boolean use_repository = repinfo!=null; // Perhaps we need to connect to the repository? if (lasttypes[0]) { if (lastrepos[0]!=null && lastrepos[0].length()>0) { if (use_repository && !lastrepos[0].equalsIgnoreCase(repinfo.getName())) { // We just asked... use_repository = false; } } } if (use_repository || !lasttypes[0]) { if (win.rep!=null) // load from repository... { if (win.rep.getName().equalsIgnoreCase(lastrepos[0])) { RepositoryDirectory repdir = win.rep.getDirectoryTree().findDirectory(lastdirs[0]); if (repdir!=null) { log.logDetailed(APP_NAME, Messages.getString("Spoon.Log.AutoLoadingTransformation",lastfiles[0],lastdirs[0]));//"Auto loading transformation ["+lastfiles[0]+"] from repository directory ["+lastdirs[0]+"]" TransLoadProgressDialog tlpd = new TransLoadProgressDialog(win.shell, win.rep, lastfiles[0], repdir); TransMeta transInfo = tlpd.open(); // = new TransInfo(log, win.rep, lastfiles[0], repdir); if (transInfo != null) { win.transMeta = transInfo; win.setFilename(lastfiles[0]); } } } } else // Load from XML? { win.transMeta = new TransMeta(lastfiles[0]); win.setFilename(lastfiles[0]); } } win.transMeta.clearChanged(); } } } } catch(KettleException ke) { log.logError(APP_NAME, Messages.getString("Spoon.Log.ErrorOccurred")+Const.CR+ke.getMessage());//"An error occurred: " win.rep=null; // ke.printStackTrace(); } win.open (); splash.dispose(); try { while (!win.isDisposed ()) { if (!win.readAndDispatch ()) win.sleep (); } } catch(Throwable e) { log.logError(APP_NAME, Messages.getString("Spoon.Log.UnexpectedErrorOccurred")+Const.CR+e.getMessage());//"An unexpected error occurred in Spoon: probable cause: please close all windows before stopping Spoon! " e.printStackTrace(); } win.dispose(); log.logBasic(APP_NAME, APP_NAME+" "+Messages.getString("Spoon.Log.AppHasEnded"));//" has ended." // Close the logfile log.close(); // Kill all remaining things in this VM! System.exit(0); } /** * @return Returns the transMeta. */ public TransMeta getTransMeta() { return transMeta; } /** * @param transMeta The transMeta to set. */ public void setTransMeta(TransMeta transMeta) { this.transMeta = transMeta; } /** * Create a new SelectValues step in between this step and the previous. * If the previous fields are not there, no mapping can be made, same with the required fields. * @param stepMeta The target step to map against. */ public void generateMapping(StepMeta stepMeta) { try { if (stepMeta!=null) { StepMetaInterface smi = stepMeta.getStepMetaInterface(); Row targetFields = smi.getRequiredFields(); Row sourceFields = transMeta.getPrevStepFields(stepMeta); // Build the mapping: let the user decide!! String[] source = sourceFields.getFieldNames(); for (int i=0;i<source.length;i++) { Value v = sourceFields.getValue(i); source[i]+=EnterMappingDialog.STRING_ORIGIN_SEPARATOR+v.getOrigin()+")"; } String[] target = targetFields.getFieldNames(); EnterMappingDialog dialog = new EnterMappingDialog(shell, source, target); ArrayList mappings = dialog.open(); if (mappings!=null) { // OK, so we now know which field maps where. // This allows us to generate the mapping using a SelectValues Step... SelectValuesMeta svm = new SelectValuesMeta(); svm.allocate(mappings.size(), 0, 0); for (int i=0;i<mappings.size();i++) { SourceToTargetMapping mapping = (SourceToTargetMapping) mappings.get(i); svm.getSelectName()[i] = sourceFields.getValue(mapping.getSourcePosition()).getName(); svm.getSelectRename()[i] = target[mapping.getTargetPosition()]; svm.getSelectLength()[i] = -1; svm.getSelectPrecision()[i] = -1; } // Now that we have the meta-data, create a new step info object String stepName = stepMeta.getName()+" Mapping"; stepName = transMeta.getAlternativeStepname(stepName); // if it's already there, rename it. StepMeta newStep = new StepMeta(log, "SelectValues", stepName, svm); newStep.setLocation(stepMeta.getLocation().x+20, stepMeta.getLocation().y+20); newStep.setDraw(true); transMeta.addStep(newStep); addUndoNew(new StepMeta[] { newStep }, new int[] { transMeta.indexOfStep(newStep) }); // Redraw stuff... refreshTree(); refreshGraph(); } } else { System.out.println("No target to do mapping against!"); } } catch(KettleException e) { new ErrorDialog(shell, Props.getInstance(), "Error creating mapping", "There was an error when Kettle tried to generate a mapping against the target step", e); } } }
false
true
public boolean quitFile() { boolean exit = true; boolean showWarning = true; log.logDetailed(toString(), Messages.getString("Spoon.Log.QuitApplication"));//"Quit application." saveSettings(); if (transMeta.hasChanged()) { MessageBox mb = new MessageBox(shell, SWT.YES | SWT.NO | SWT.CANCEL | SWT.ICON_WARNING ); mb.setMessage(Messages.getString("Spoon.Dialog.SaveChangedFile.Message"));//"File has changed! Do you want to save first?" mb.setText(Messages.getString("Spoon.Dialog.SaveChangedFile.Title"));//"Warning!" int answer = mb.open(); switch(answer) { case SWT.YES: exit=saveFile(); showWarning=false; break; case SWT.NO: exit=true; showWarning=false; break; case SWT.CANCEL: exit=false; showWarning=false; break; } } // System.out.println("exit="+exit+", showWarning="+showWarning+", running="+spoonlog.isRunning()+", showExitWarning="+props.showExitWarning()); // Show warning on exit when spoon is still running // Show warning on exit when a warning needs to be displayed, but only if we didn't ask to save before. (could have pressed cancel then!) // if ( (exit && spoonlog.isRunning() ) || (exit && showWarning && props.showExitWarning() ) ) { String message = Messages.getString("Spoon.Message.Warning.PromptExit"); //"Are you sure you want to exit?" if (spoonlog.isRunning()) message = Messages.getString("Spoon.Message.Warning.PromptExitWhenRunTransformation");//There is a running transformation. Are you sure you want to exit? MessageDialogWithToggle md = new MessageDialogWithToggle(shell, Messages.getString("System.Warning"),//"Warning!" null, message, MessageDialog.WARNING, new String[] { Messages.getString("Spoon.Message.Warning.Yes"), Messages.getString("Spoon.Message.Warning.No") },//"Yes", "No" 1, Messages.getString("Spoon.Message.Warning.NotShowWarning"),//"Please, don't show this warning anymore." !props.showExitWarning() ); int idx = md.open(); props.setExitWarningShown(!md.getToggleState()); props.saveProps(); if (idx==1) exit=false; // No selected: don't exit! else exit=true; } if (exit) dispose(); return exit; } public boolean saveFile() { boolean saved=false; log.logDetailed(toString(), Messages.getString("Spoon.Log.SaveToFileOrRepository"));//"Save to file or repository..." if (rep!=null) { saved=saveRepository(); } else { if (transMeta.getFilename()!=null) { saved=save(transMeta.getFilename()); } else { saved=saveFileAs(); } } try { if (props.useDBCache()) transMeta.getDbCache().saveCache(log); } catch(KettleException e) { new ErrorDialog(shell, props, Messages.getString("Spoon.Dialog.ErrorSavingDatabaseCache.Title"), Messages.getString("Spoon.Dialog.ErrorSavingDatabaseCache.Message"), e);//"An error occured saving the database cache to disk" } return saved; } public boolean saveRepository() { return saveRepository(false); } public boolean saveRepository(boolean ask_name) { log.logDetailed(toString(), Messages.getString("Spoon.Log.SaveToRepository"));//"Save to repository..." if (rep!=null) { boolean answer = true; boolean ask = ask_name; while (answer && ( ask || transMeta.getName()==null || transMeta.getName().length()==0 ) ) { if (!ask) { MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_WARNING); mb.setMessage(Messages.getString("Spoon.Dialog.PromptTransformationName.Message"));//"Please give this transformation a name before saving it in the database." mb.setText(Messages.getString("Spoon.Dialog.PromptTransformationName.Title"));//"Transformation has no name." mb.open(); } ask=false; answer = setTrans(); // System.out.println("answer="+answer+", ask="+ask+", transMeta.getName()="+transMeta.getName()); } if (answer && transMeta.getName()!=null && transMeta.getName().length()>0) { if (!rep.getUserInfo().isReadonly()) { int response = SWT.YES; if (transMeta.showReplaceWarning(rep)) { MessageBox mb = new MessageBox(shell, SWT.YES | SWT.NO | SWT.ICON_QUESTION); mb.setMessage(Messages.getString("Spoon.Dialog.PromptOverwriteTransformation.Message",transMeta.getName(),Const.CR));//"There already is a transformation called ["+transMeta.getName()+"] in the repository."+Const.CR+"Do you want to overwrite the transformation?" mb.setText(Messages.getString("Spoon.Dialog.PromptOverwriteTransformation.Title"));//"Overwrite?" response = mb.open(); } boolean saved=false; if (response == SWT.YES) { shell.setCursor(cursor_hourglass); // Keep info on who & when this transformation was changed... transMeta.setModifiedDate( new Value("MODIFIED_DATE", Value.VALUE_TYPE_DATE) ); transMeta.getModifiedDate().sysdate(); transMeta.setModifiedUser( rep.getUserInfo().getLogin() ); TransSaveProgressDialog tspd = new TransSaveProgressDialog(log, props, shell, rep, transMeta); if (tspd.open()) { saved=true; if (!props.getSaveConfirmation()) { MessageDialogWithToggle md = new MessageDialogWithToggle(shell, Messages.getString("Spoon.Message.Warning.SaveOK"), //"Save OK!" null, Messages.getString("Spoon.Message.Warning.TransformationWasStored"),//"This transformation was stored in repository" MessageDialog.QUESTION, new String[] { Messages.getString("Spoon.Message.Warning.OK") },//"OK!" 0, Messages.getString("Spoon.Message.Warning.NotShowThisMessage"),//"Don't show this message again." props.getSaveConfirmation() ); md.open(); props.setSaveConfirmation(md.getToggleState()); } // Handle last opened files... props.addLastFile(Props.TYPE_PROPERTIES_SPOON, transMeta.getName(), transMeta.getDirectory().getPath(), true, getRepositoryName()); saveSettings(); addMenuLast(); setShellText(); } shell.setCursor(null); } return saved; } else { MessageBox mb = new MessageBox(shell, SWT.CLOSE | SWT.ICON_ERROR); mb.setMessage(Messages.getString("Spoon.Dialog.OnlyreadRepository.Message"));//"Sorry, the user you're logged on with, can only read from the repository" mb.setText(Messages.getString("Spoon.Dialog.OnlyreadRepository.Title"));//"Transformation not saved!" mb.open(); } } } else { MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR); mb.setMessage(Messages.getString("Spoon.Dialog.NoRepositoryConnection.Message"));//"There is no repository connection available." mb.setText(Messages.getString("Spoon.Dialog.NoRepositoryConnection.Title"));//"No repository available." mb.open(); } return false; } public boolean saveFileAs() { boolean saved=false; log.logBasic(toString(), Messages.getString("Spoon.Log.SaveAs"));//"Save as..." if (rep!=null) { transMeta.setID(-1L); saved=saveRepository(true); } else { saved=saveXMLFile(); } return saved; } private boolean saveXMLFile() { boolean saved=false; FileDialog dialog = new FileDialog(shell, SWT.SAVE); dialog.setFilterPath("C:\\Projects\\kettle\\source\\"); dialog.setFilterExtensions(Const.STRING_TRANS_FILTER_EXT); dialog.setFilterNames(Const.STRING_TRANS_FILTER_NAMES); String fname = dialog.open(); if (fname!=null) { // Is the filename ending on .ktr, .xml? boolean ending=false; for (int i=0;i<Const.STRING_TRANS_FILTER_EXT.length-1;i++) { if (fname.endsWith(Const.STRING_TRANS_FILTER_EXT[i].substring(1))) { ending=true; } } if (fname.endsWith(Const.STRING_TRANS_DEFAULT_EXT)) ending=true; if (!ending) { fname+=Const.STRING_TRANS_DEFAULT_EXT; } // See if the file already exists... File f = new File(fname); int id = SWT.YES; if (f.exists()) { MessageBox mb = new MessageBox(shell, SWT.NO | SWT.YES | SWT.ICON_WARNING); mb.setMessage(Messages.getString("Spoon.Dialog.PromptOverwriteFile.Message"));//"This file already exists. Do you want to overwrite it?" mb.setText(Messages.getString("Spoon.Dialog.PromptOverwriteFile.Title"));//"This file already exists!" id = mb.open(); } if (id==SWT.YES) { saved=save(fname); setFilename(fname); } } return saved; } private boolean save(String fname) { boolean saved = false; String xml = XMLHandler.getXMLHeader() + transMeta.getXML(); try { DataOutputStream dos = new DataOutputStream(new FileOutputStream(new File(fname))); dos.write(xml.getBytes(Const.XML_ENCODING)); dos.close(); saved=true; // Handle last opened files... props.addLastFile(Props.TYPE_PROPERTIES_SPOON, fname, Const.FILE_SEPARATOR, false, ""); saveSettings(); addMenuLast(); transMeta.clearChanged(); setShellText(); log.logDebug(toString(), Messages.getString("Spoon.Log.FileWritten")+" ["+fname+"]"); //"File written to } catch(Exception e) { log.logDebug(toString(), Messages.getString("Spoon.Log.ErrorOpeningFileForWriting")+e.toString());//"Error opening file for writing! --> " MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR); mb.setMessage(Messages.getString("Spoon.Dialog.ErrorSavingFile.Message")+Const.CR+e.toString());//"Error saving file:" mb.setText(Messages.getString("Spoon.Dialog.ErrorSavingFile.Title"));//"ERROR" mb.open(); } return saved; } public void helpAbout() { MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION | SWT.CENTER); String mess = Messages.getString("System.ProductInfo")+Const.VERSION+Const.CR+Const.CR+Const.CR;//Kettle - Spoon version mess+=Messages.getString("System.CompanyInfo")+Const.CR; mess+=" "+Messages.getString("System.ProductWebsiteUrl")+Const.CR; //(c) 2001-2004 i-Bridge bvba www.kettle.be mess+=" "+BuildVersion.getInstance().getVersion()+Const.CR; mb.setMessage(mess); mb.setText(APP_NAME); mb.open(); } public void editUnselectAll() { transMeta.unselectAll(); spoongraph.redraw(); } public void editSelectAll() { transMeta.selectAll(); spoongraph.redraw(); } public void editOptions() { EnterOptionsDialog eod = new EnterOptionsDialog(shell, props); if (eod.open()!=null) { props.saveProps(); loadSettings(); changeLooks(); MessageBox mb = new MessageBox(shell, SWT.ICON_INFORMATION); mb.setMessage(Messages.getString("Spoon.Dialog.PleaseRestartApplication.Message")); mb.setText(Messages.getString("Spoon.Dialog.PleaseRestartApplication.Title")); mb.open(); } } public int getTreePosition(TreeItem ti, String item) { if (ti!=null) { TreeItem items[] = ti.getItems(); for (int x=0;x<items.length;x++) { if (items[x].getText().equalsIgnoreCase(item)) { return x; } } } return -1; } public void refreshTree() { refreshTree(false); refreshPluginHistory(); } /** * Refresh the object selection tree (on the left of the screen) * @param complete true refreshes the complete tree, false tries to do a differential update to avoid flickering. */ public void refreshTree(boolean complete) { if (shell.isDisposed()) return; if (!transMeta.hasChanged() && !complete) return; // Nothing changed: nothing to do! int idx; TreeItem ti[]; // Refresh the connections... // if (transMeta.haveConnectionsChanged() || complete) { tiConn.setText(STRING_CONNECTIONS); // TreeItem tiConn= this.tiConn (TreeItem)widgets.getWidget(STRING_CONNECTIONS); ti = tiConn.getItems(); // In complete refresh: delete all items first if (complete) { for (int i=0;i<ti.length;i++) ti[i].dispose(); ti = tiConn.getItems(); } // First delete no longer used items... for (int i=0;i<ti.length;i++) { String str = ti[i].getText(); DatabaseMeta inf = transMeta.findDatabase(str); if (inf!=null) idx = transMeta.indexOfDatabase(inf); else idx=-1; if (idx<0 || idx>i) ti[i].dispose(); } ti = tiConn.getItems(); // Insert missing items in tree... int j=0; for (int i=0;i<transMeta.nrDatabases();i++) { DatabaseMeta inf = transMeta.getDatabase(i); String con_name = inf.getName(); String ti_name = ""; if (j<ti.length) ti_name = ti[j].getText(); if (!con_name.equalsIgnoreCase(ti_name)) { // insert at position j in tree TreeItem newitem = new TreeItem(tiConn, j); newitem.setText(inf.getName()); newitem.setForeground(GUIResource.getInstance().getColorBlack()); newitem.setImage(GUIResource.getInstance().getImageConnection()); j++; ti = tiConn.getItems(); } else { j++; } } // tiConn.setExpanded(true); } //ni.setImage(gv.hop_image); //ni.setImage(gv.step_images_small[steptype]); // Refresh the Steps... // if (transMeta.haveStepsChanged() || complete) { tiStep.setText(STRING_STEPS); ti = tiStep.getItems(); // In complete refresh: delete all items first if (complete) { for (int i=0;i<ti.length;i++) ti[i].dispose(); ti = tiStep.getItems(); } // First delete no longer used items... log.logDebug(toString(), Messages.getString("Spoon.Log.CheckSteps"));//"check steps" for (int i=0;i<ti.length;i++) { String str = ti[i].getText(); log.logDebug(toString(), " "+Messages.getString("Spoon.Log.CheckStepTreeItem")+i+" : ["+str+"]"); StepMeta inf = transMeta.findStep(str); if (inf!=null) idx = transMeta.indexOfStep(inf); else idx=-1; if (idx<0 || idx>i) { log.logDebug(toString(), " "+ Messages.getString("Spoon.Log.RemoveTreeItem")+ "["+str+"]");//remove tree item ti[i].dispose(); } } ti = tiStep.getItems(); // Insert missing items in tree... int j=0; for (int i=0;i<transMeta.nrSteps();i++) { StepMeta inf = transMeta.getStep(i); String step_name = inf.getName(); String step_id = inf.getStepID(); String ti_name = ""; if (j<ti.length) ti_name = ti[j].getText(); if (!step_name.equalsIgnoreCase(ti_name)) { // insert at position j in tree TreeItem newitem = new TreeItem(tiStep, j); newitem.setText(inf.getName()); // Set the small image... Image img = (Image)GUIResource.getInstance().getImagesStepsSmall().get(step_id); newitem.setImage(img); j++; ti = tiStep.getItems(); } else { j++; } } // See if the colors are still OK! for (int i=0;i<ti.length;i++) { StepMeta inf = transMeta.findStep(ti[i].getText()); Color col = ti[i].getForeground(); Color newcol; if (transMeta.isStepUsedInTransHops(inf)) newcol=GUIResource.getInstance().getColorBlack(); else newcol=GUIResource.getInstance().getColorGray(); if (!newcol.equals(col)) ti[i].setForeground(newcol); } //tiStep.setExpanded(true); } // Refresh the Hops... // if (transMeta.haveHopsChanged() || complete) { tiHops.setText(STRING_HOPS); ti = tiHops.getItems(); // In complete refresh: delete all items first if (complete) { for (int i=0;i<ti.length;i++) ti[i].dispose(); ti = tiHops.getItems(); } // First delete no longer used items... for (int i=0;i<ti.length;i++) { String str = ti[i].getText(); TransHopMeta inf = transMeta.findTransHop(str); if (inf!=null) idx = transMeta.indexOfTransHop(inf); else idx=-1; if (idx<0 || idx>i) ti[i].dispose(); } ti = tiHops.getItems(); // Insert missing items in tree... int j=0; for (int i=0;i<transMeta.nrTransHops();i++) { TransHopMeta inf = transMeta.getTransHop(i); String trans_name = inf.toString(); String ti_name = ""; if (j<ti.length) ti_name = ti[j].getText(); if (!trans_name.equalsIgnoreCase(ti_name)) { // insert at position j in tree TreeItem newitem = new TreeItem(tiHops, j); newitem.setText(inf.toString()); newitem.setForeground(GUIResource.getInstance().getColorBlack()); newitem.setImage(GUIResource.getInstance().getImageHop()); j++; ti = tiHops.getItems(); } else { j++; } } // tiTrns.setExpanded(false); } selectionTree.setFocus(); setShellText(); } public void refreshGraph() { if (shell.isDisposed()) return; spoongraph.redraw(); setShellText(); } public void refreshHistory() { spoonhist.refreshHistory(); } public StepMeta newStep() { return newStep(true, true); } public StepMeta newStep(boolean openit, boolean rename) { TreeItem ti[] = selectionTree.getSelection(); StepMeta inf = null; if (ti.length==1) { String steptype = ti[0].getText(); log.logDebug(toString(), Messages.getString("Spoon.Log.NewStep")+steptype);//"New step: " inf = newStep(steptype, steptype, openit, rename); } return inf; } /** * Allocate new step, optionally open and rename it. * * @param name Name of the new step * @param description Description of the type of step * @param openit Open the dialog for this step? * @param rename Rename this step? * * @return The newly created StepMeta object. * */ public StepMeta newStep(String name, String description, boolean openit, boolean rename) { StepMeta inf = null; // See if we need to rename the step to avoid doubles! if (rename && transMeta.findStep(name)!=null) { int i=2; String newname = name+" "+i; while (transMeta.findStep(newname)!=null) { i++; newname = name+" "+i; } name=newname; } StepLoader steploader = StepLoader.getInstance(); StepPlugin stepPlugin = null; try { stepPlugin = steploader.findStepPluginWithDescription(description); if (stepPlugin!=null) { StepMetaInterface info = BaseStep.getStepInfo(stepPlugin, steploader); info.setDefault(); if (openit) { StepDialogInterface dialog = info.getDialog(shell, info, transMeta, name); name = dialog.open(); } inf=new StepMeta(log, stepPlugin.getID()[0], name, info); if (name!=null) // OK pressed in the dialog: we have a step-name { String newname=name; StepMeta stepMeta = transMeta.findStep(newname); int nr=2; while (stepMeta!=null) { newname = name+" "+nr; stepMeta = transMeta.findStep(newname); nr++; } if (nr>2) { inf.setName(newname); MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION); mb.setMessage(Messages.getString("Spoon.Dialog.ChangeStepname.Message",newname));//"This stepname already exists. Spoon changed the stepname to ["+newname+"]" mb.setText(Messages.getString("Spoon.Dialog.ChangeStepname.Title"));//"Info!" mb.open(); } inf.setLocation(20, 20); // default location at (20,20) transMeta.addStep(inf); // Save for later: // if openit is false: we drag&drop it onto the canvas! if (openit) { addUndoNew(new StepMeta[] { inf }, new int[] { transMeta.indexOfStep(inf) }); } // Also store it in the pluginHistory list... props.addPluginHistory(stepPlugin.getID()[0]); refreshTree(); } else { return null; // Cancel pressed in dialog. } setShellText(); } } catch(KettleException e) { String filename = stepPlugin.getErrorHelpFile(); if (stepPlugin!=null && filename!=null) { // OK, in stead of a normal error message, we give back the content of the error help file... (HTML) try { StringBuffer content=new StringBuffer(); System.out.println("Filename = "+filename); FileInputStream fis = new FileInputStream(new File(filename)); int ch = fis.read(); while (ch>=0) { content.append( (char)ch); ch = fis.read(); } System.out.println("Content = "+content); ShowBrowserDialog sbd = new ShowBrowserDialog(shell, Messages.getString("Spoon.Dialog.ErrorHelpText.Title"), content.toString());//"Error help text" sbd.open(); } catch(Exception ex) { new ErrorDialog(shell, props, Messages.getString("Spoon.Dialog.ErrorShowingHelpText.Title"), Messages.getString("Spoon.Dialog.ErrorShowingHelpText.Message"), ex);//"Error showing help text" } } else { new ErrorDialog(shell, props, Messages.getString("Spoon.Dialog.UnableCreateNewStep.Title"),Messages.getString("Spoon.Dialog.UnableCreateNewStep.Message") , e);//"Error creating step" "I was unable to create a new step" } return null; } catch(Throwable e) { if (!shell.isDisposed()) new ErrorDialog(shell, props, Messages.getString("Spoon.Dialog.ErrorCreatingStep.Title"), Messages.getString("Spoon.Dialog.UnableCreateNewStep.Message"), new Exception(e));//"Error creating step" return null; } return inf; } private void setTreeImages() { tiConn.setImage(GUIResource.getInstance().getImageConnection()); tiHops.setImage(GUIResource.getInstance().getImageHop()); tiStep.setImage(GUIResource.getInstance().getImageBol()); tiBase.setImage(GUIResource.getInstance().getImageBol()); tiPlug.setImage(GUIResource.getInstance().getImageBol()); TreeItem tiBaseCat[]=tiBase.getItems(); for (int x=0;x<tiBaseCat.length;x++) { tiBaseCat[x].setImage(GUIResource.getInstance().getImageBol()); TreeItem ti[] = tiBaseCat[x].getItems(); for (int i=0;i<ti.length;i++) { TreeItem stepitem = ti[i]; String description = stepitem.getText(); StepLoader steploader = StepLoader.getInstance(); StepPlugin sp = steploader.findStepPluginWithDescription(description); if (sp!=null) { Image stepimg = (Image)GUIResource.getInstance().getImagesStepsSmall().get(sp.getID()[0]); if (stepimg!=null) { stepitem.setImage(stepimg); } } } } TreeItem tiPlugCat[]=tiPlug.getItems(); for (int x=0;x<tiPlugCat.length;x++) { tiPlugCat[x].setImage(GUIResource.getInstance().getImageBol()); TreeItem ti[] = tiPlugCat[x].getItems(); for (int i=0;i<ti.length;i++) { TreeItem stepitem = ti[i]; String description = stepitem.getText(); StepLoader steploader = StepLoader.getInstance(); StepPlugin sp = steploader.findStepPluginWithDescription(description); if (sp!=null) { Image stepimg = (Image)GUIResource.getInstance().getImagesStepsSmall().get(sp.getID()); if (stepimg!=null) { stepitem.setImage(stepimg); } } } } } public DatabaseMeta getConnection(String name) { int i; for (i=0;i<transMeta.nrDatabases();i++) { DatabaseMeta ci = transMeta.getDatabase(i); if (ci.getName().equalsIgnoreCase(name)) { return ci; } } return null; } public void setShellText() { String fname = transMeta.getFilename(); if (shell.isDisposed()) return; if (rep!=null) { String repository = "["+getRepositoryName()+"]"; String transname = transMeta.getName(); if (transname==null) transname=Messages.getString("Spoon.Various.NoName");//"[no name]" shell.setText(APPL_TITLE+" - "+repository+" "+transname+(transMeta.hasChanged()?(" "+Messages.getString("Spoon.Various.Changed")):""));//(changed) } else { String repository = Messages.getString("Spoon.Various.NoRepository");//"[no repository]" if (fname!=null) { shell.setText(APPL_TITLE+" - "+repository+" File: "+fname+(transMeta.hasChanged()?(" "+Messages.getString("Spoon.Various.Changed")):"")); } else { shell.setText(APPL_TITLE+" - "+repository+" "+(transMeta.hasChanged()?(" "+Messages.getString("Spoon.Various.Changed")):"")); } } } public void setFilename(String fname) { if (fname!=null) transMeta.setFilename(fname); setShellText(); } private void printFile() { PrintSpool ps = new PrintSpool(); Printer printer = ps.getPrinter(shell); // Create an image of the screen Point max = transMeta.getMaximum(); Image img = spoongraph.getTransformationImage(printer, max.x, max.y); ps.printImage(shell, props, img); img.dispose(); ps.dispose(); } private boolean setTrans() { TransDialog tid = new TransDialog(shell, SWT.NONE, transMeta, rep); TransMeta ti = tid.open(); setShellText(); return ti!=null; } public void saveSettings() { WindowProperty winprop = new WindowProperty(shell); winprop.setName(APPL_TITLE); props.setScreen(winprop); props.setLogLevel(log.getLogLevelDesc()); props.setLogFilter(log.getFilter()); props.setSashWeights(sashform.getWeights()); props.saveProps(); } public void loadSettings() { log.setLogLevel(props.getLogLevel()); log.setFilter(props.getLogFilter()); transMeta.setMaxUndo(props.getMaxUndo()); transMeta.getDbCache().setActive(props.useDBCache()); } public void changeLooks() { props.setLook(selectionTree); props.setLook(tabfolder, Props.WIDGET_STYLE_TAB); spoongraph.newProps(); refreshTree(); refreshGraph(); } public void undoAction() { spoongraph.forceFocus(); TransAction ta = transMeta.previousUndo(); if (ta==null) return; setUndoMenu(); // something changed: change the menu switch(ta.getType()) { // // NEW // // We created a new step : undo this... case TransAction.TYPE_ACTION_NEW_STEP: // Delete the step at correct location: for (int i=ta.getCurrent().length-1;i>=0;i--) { int idx = ta.getCurrentIndex()[i]; transMeta.removeStep(idx); } refreshTree(); refreshGraph(); break; // We created a new connection : undo this... case TransAction.TYPE_ACTION_NEW_CONNECTION: // Delete the connection at correct location: for (int i=ta.getCurrent().length-1;i>=0;i--) { int idx = ta.getCurrentIndex()[i]; transMeta.removeDatabase(idx); } refreshTree(); refreshGraph(); break; // We created a new note : undo this... case TransAction.TYPE_ACTION_NEW_NOTE: // Delete the note at correct location: for (int i=ta.getCurrent().length-1;i>=0;i--) { int idx = ta.getCurrentIndex()[i]; transMeta.removeNote(idx); } refreshTree(); refreshGraph(); break; // We created a new hop : undo this... case TransAction.TYPE_ACTION_NEW_HOP: // Delete the hop at correct location: for (int i=ta.getCurrent().length-1;i>=0;i--) { int idx = ta.getCurrentIndex()[i]; transMeta.removeTransHop(idx); } refreshTree(); refreshGraph(); break; // // DELETE // // We delete a step : undo this... case TransAction.TYPE_ACTION_DELETE_STEP: // un-Delete the step at correct location: re-insert for (int i=0;i<ta.getCurrent().length;i++) { StepMeta stepMeta = (StepMeta)ta.getCurrent()[i]; int idx = ta.getCurrentIndex()[i]; transMeta.addStep(idx, stepMeta); } refreshTree(); refreshGraph(); break; // We deleted a connection : undo this... case TransAction.TYPE_ACTION_DELETE_CONNECTION: // re-insert the connection at correct location: for (int i=0;i<ta.getCurrent().length;i++) { DatabaseMeta ci = (DatabaseMeta)ta.getCurrent()[i]; int idx = ta.getCurrentIndex()[i]; transMeta.addDatabase(idx, ci); } refreshTree(); refreshGraph(); break; // We delete new note : undo this... case TransAction.TYPE_ACTION_DELETE_NOTE: // re-insert the note at correct location: for (int i=0;i<ta.getCurrent().length;i++) { NotePadMeta ni = (NotePadMeta)ta.getCurrent()[i]; int idx = ta.getCurrentIndex()[i]; transMeta.addNote(idx, ni); } refreshTree(); refreshGraph(); break; // We deleted a hop : undo this... case TransAction.TYPE_ACTION_DELETE_HOP: // re-insert the hop at correct location: for (int i=0;i<ta.getCurrent().length;i++) { TransHopMeta hi = (TransHopMeta)ta.getCurrent()[i]; int idx = ta.getCurrentIndex()[i]; // Build a new hop: StepMeta from = transMeta.findStep(hi.getFromStep().getName()); StepMeta to = transMeta.findStep(hi.getToStep().getName()); TransHopMeta hinew = new TransHopMeta(from, to); transMeta.addTransHop(idx, hinew); } refreshTree(); refreshGraph(); break; // // CHANGE // // We changed a step : undo this... case TransAction.TYPE_ACTION_CHANGE_STEP: // Delete the current step, insert previous version. for (int i=0;i<ta.getCurrent().length;i++) { StepMeta prev = (StepMeta)ta.getPrevious()[i]; int idx = ta.getCurrentIndex()[i]; transMeta.removeStep(idx); transMeta.addStep(idx, prev); } refreshTree(); refreshGraph(); break; // We changed a connection : undo this... case TransAction.TYPE_ACTION_CHANGE_CONNECTION: // Delete & re-insert for (int i=0;i<ta.getCurrent().length;i++) { DatabaseMeta prev = (DatabaseMeta)ta.getPrevious()[i]; int idx = ta.getCurrentIndex()[i]; transMeta.removeDatabase(idx); transMeta.addDatabase(idx, prev); } refreshTree(); refreshGraph(); break; // We changed a note : undo this... case TransAction.TYPE_ACTION_CHANGE_NOTE: // Delete & re-insert for (int i=0;i<ta.getCurrent().length;i++) { int idx = ta.getCurrentIndex()[i]; transMeta.removeNote(idx); NotePadMeta prev = (NotePadMeta)ta.getPrevious()[i]; transMeta.addNote(idx, prev); } refreshTree(); refreshGraph(); break; // We changed a hop : undo this... case TransAction.TYPE_ACTION_CHANGE_HOP: // Delete & re-insert for (int i=0;i<ta.getCurrent().length;i++) { TransHopMeta prev = (TransHopMeta)ta.getPrevious()[i]; int idx = ta.getCurrentIndex()[i]; transMeta.removeTransHop(idx); transMeta.addTransHop(idx, prev); } refreshTree(); refreshGraph(); break; // // POSITION // // The position of a step has changed: undo this... case TransAction.TYPE_ACTION_POSITION_STEP: // Find the location of the step: for (int i = 0; i < ta.getCurrentIndex().length; i++) { StepMeta stepMeta = transMeta.getStep(ta.getCurrentIndex()[i]); stepMeta.setLocation(ta.getPreviousLocation()[i]); } refreshGraph(); break; // The position of a note has changed: undo this... case TransAction.TYPE_ACTION_POSITION_NOTE: for (int i=0;i<ta.getCurrentIndex().length;i++) { int idx = ta.getCurrentIndex()[i]; NotePadMeta npi = transMeta.getNote(idx); Point prev = ta.getPreviousLocation()[i]; npi.setLocation(prev); } refreshGraph(); break; default: break; } // OK, now check if we need to do this again... if (transMeta.viewNextUndo()!=null) { if (transMeta.viewNextUndo().getNextAlso()) undoAction(); } } public void redoAction() { spoongraph.forceFocus(); TransAction ta = transMeta.nextUndo(); if (ta==null) return; setUndoMenu(); // something changed: change the menu switch(ta.getType()) { // // NEW // case TransAction.TYPE_ACTION_NEW_STEP: // re-delete the step at correct location: for (int i=0;i<ta.getCurrent().length;i++) { StepMeta stepMeta = (StepMeta)ta.getCurrent()[i]; int idx = ta.getCurrentIndex()[i]; transMeta.addStep(idx, stepMeta); refreshTree(); refreshGraph(); } break; case TransAction.TYPE_ACTION_NEW_CONNECTION: // re-insert the connection at correct location: for (int i=0;i<ta.getCurrent().length;i++) { DatabaseMeta ci = (DatabaseMeta)ta.getCurrent()[i]; int idx = ta.getCurrentIndex()[i]; transMeta.addDatabase(idx, ci); refreshTree(); refreshGraph(); } break; case TransAction.TYPE_ACTION_NEW_NOTE: // re-insert the note at correct location: for (int i=0;i<ta.getCurrent().length;i++) { NotePadMeta ni = (NotePadMeta)ta.getCurrent()[i]; int idx = ta.getCurrentIndex()[i]; transMeta.addNote(idx, ni); refreshTree(); refreshGraph(); } break; case TransAction.TYPE_ACTION_NEW_HOP: // re-insert the hop at correct location: for (int i=0;i<ta.getCurrent().length;i++) { TransHopMeta hi = (TransHopMeta)ta.getCurrent()[i]; int idx = ta.getCurrentIndex()[i]; transMeta.addTransHop(idx, hi); refreshTree(); refreshGraph(); } break; // // DELETE // case TransAction.TYPE_ACTION_DELETE_STEP: // re-remove the step at correct location: for (int i=ta.getCurrent().length-1;i>=0;i--) { int idx = ta.getCurrentIndex()[i]; transMeta.removeStep(idx); } refreshTree(); refreshGraph(); break; case TransAction.TYPE_ACTION_DELETE_CONNECTION: // re-remove the connection at correct location: for (int i=ta.getCurrent().length-1;i>=0;i--) { int idx = ta.getCurrentIndex()[i]; transMeta.removeDatabase(idx); } refreshTree(); refreshGraph(); break; case TransAction.TYPE_ACTION_DELETE_NOTE: // re-remove the note at correct location: for (int i=ta.getCurrent().length-1;i>=0;i--) { int idx = ta.getCurrentIndex()[i]; transMeta.removeNote(idx); } refreshTree(); refreshGraph(); break; case TransAction.TYPE_ACTION_DELETE_HOP: // re-remove the hop at correct location: for (int i=ta.getCurrent().length-1;i>=0;i--) { int idx = ta.getCurrentIndex()[i]; transMeta.removeTransHop(idx); } refreshTree(); refreshGraph(); break; // // CHANGE // // We changed a step : undo this... case TransAction.TYPE_ACTION_CHANGE_STEP: // Delete the current step, insert previous version. for (int i=0;i<ta.getCurrent().length;i++) { StepMeta stepMeta = (StepMeta)ta.getCurrent()[i]; int idx = ta.getCurrentIndex()[i]; transMeta.removeStep(idx); transMeta.addStep(idx, stepMeta); } refreshTree(); refreshGraph(); break; // We changed a connection : undo this... case TransAction.TYPE_ACTION_CHANGE_CONNECTION: // Delete & re-insert for (int i=0;i<ta.getCurrent().length;i++) { DatabaseMeta ci = (DatabaseMeta)ta.getCurrent()[i]; int idx = ta.getCurrentIndex()[i]; transMeta.removeDatabase(idx); transMeta.addDatabase(idx, ci); } refreshTree(); refreshGraph(); break; // We changed a note : undo this... case TransAction.TYPE_ACTION_CHANGE_NOTE: // Delete & re-insert for (int i=0;i<ta.getCurrent().length;i++) { NotePadMeta ni = (NotePadMeta)ta.getCurrent()[i]; int idx = ta.getCurrentIndex()[i]; transMeta.removeNote(idx); transMeta.addNote(idx, ni); } refreshTree(); refreshGraph(); break; // We changed a hop : undo this... case TransAction.TYPE_ACTION_CHANGE_HOP: // Delete & re-insert for (int i=0;i<ta.getCurrent().length;i++) { TransHopMeta hi = (TransHopMeta)ta.getCurrent()[i]; int idx = ta.getCurrentIndex()[i]; transMeta.removeTransHop(idx); transMeta.addTransHop(idx, hi); } refreshTree(); refreshGraph(); break; // // CHANGE POSITION // case TransAction.TYPE_ACTION_POSITION_STEP: for (int i=0;i<ta.getCurrentIndex().length;i++) { // Find & change the location of the step: StepMeta stepMeta = transMeta.getStep(ta.getCurrentIndex()[i]); stepMeta.setLocation(ta.getCurrentLocation()[i]); } refreshGraph(); break; case TransAction.TYPE_ACTION_POSITION_NOTE: for (int i=0;i<ta.getCurrentIndex().length;i++) { int idx = ta.getCurrentIndex()[i]; NotePadMeta npi = transMeta.getNote(idx); Point curr = ta.getCurrentLocation()[i]; npi.setLocation(curr); } refreshGraph(); break; default: break; } // OK, now check if we need to do this again... if (transMeta.viewNextUndo()!=null) { if (transMeta.viewNextUndo().getNextAlso()) redoAction(); } } public void setUndoMenu() { if (shell.isDisposed()) return; TransAction prev = transMeta.viewThisUndo(); TransAction next = transMeta.viewNextUndo(); if (prev!=null) { miEditUndo.setEnabled(true); miEditUndo.setText(Messages.getString("Spoon.Menu.Undo.Available", prev.toString()));//"Undo : "+prev.toString()+" \tCTRL-Z" } else { miEditUndo.setEnabled(false); miEditUndo.setText(Messages.getString("Spoon.Menu.Undo.NotAvailable"));//"Undo : not available \tCTRL-Z" } if (next!=null) { miEditRedo.setEnabled(true); miEditRedo.setText(Messages.getString("Spoon.Menu.Redo.Available",next.toString()));//"Redo : "+next.toString()+" \tCTRL-Y" } else { miEditRedo.setEnabled(false); miEditRedo.setText(Messages.getString("Spoon.Menu.Redo.NotAvailable"));//"Redo : not available \tCTRL-Y" } } public void addUndoNew(Object obj[], int position[]) { addUndoNew(obj, position, false); } public void addUndoNew(Object obj[], int position[], boolean nextAlso) { // New object? transMeta.addUndo(obj, null, position, null, null, TransMeta.TYPE_UNDO_NEW, nextAlso); setUndoMenu(); } // Undo delete object public void addUndoDelete(Object obj[], int position[]) { addUndoDelete(obj, position, false); } // Undo delete object public void addUndoDelete(Object obj[], int position[], boolean nextAlso) { transMeta.addUndo(obj, null, position, null, null, TransMeta.TYPE_UNDO_DELETE, nextAlso); setUndoMenu(); } // Change of step, connection, hop or note... public void addUndoPosition(Object obj[], int pos[], Point prev[], Point curr[]) { addUndoPosition(obj, pos, prev, curr, false); } // Change of step, connection, hop or note... public void addUndoPosition(Object obj[], int pos[], Point prev[], Point curr[], boolean nextAlso) { // It's better to store the indexes of the objects, not the objects itself! transMeta.addUndo(obj, null, pos, prev, curr, TransMeta.TYPE_UNDO_POSITION, nextAlso); setUndoMenu(); } // Change of step, connection, hop or note... public void addUndoChange(Object from[], Object to[], int[] pos) { addUndoChange(from, to, pos, false); } // Change of step, connection, hop or note... public void addUndoChange(Object from[], Object to[], int[] pos, boolean nextAlso) { transMeta.addUndo(from, to, pos, null, null, TransMeta.TYPE_UNDO_CHANGE, nextAlso); setUndoMenu(); } /** * Checks *all* the steps in the transformation, puts the result in remarks list */ public void checkTrans() { checkTrans(false); } /** * Check the steps in a transformation * * @param only_selected True: Check only the selected steps... */ public void checkTrans(boolean only_selected) { CheckTransProgressDialog ctpd = new CheckTransProgressDialog(log, props, shell, transMeta, remarks, only_selected); ctpd.open(); // manages the remarks arraylist... showLastTransCheck(); } /** * Show the remarks of the last transformation check that was run. * @see #checkTrans() */ public void showLastTransCheck() { CheckResultDialog crd = new CheckResultDialog(shell, SWT.NONE, remarks); String stepname = crd.open(); if (stepname!=null) { // Go to the indicated step! StepMeta stepMeta = transMeta.findStep(stepname); if (stepMeta!=null) { editStepInfo(stepMeta); } } } public void clearDBCache() { // Determine what menu we selected from... TreeItem ti[] = selectionTree.getSelection(); // Then call editConnection or editStep or editTrans if (ti.length==1) { String name = ti[0].getText(); TreeItem parent = ti[0].getParentItem(); if (parent != null) { String type = parent.getText(); if (type.equalsIgnoreCase(STRING_CONNECTIONS)) { transMeta.getDbCache().clear(name); } } else { if (name.equalsIgnoreCase(STRING_CONNECTIONS)) transMeta.getDbCache().clear(null); } } } public void exploreDB() { // Determine what menu we selected from... TreeItem ti[] = selectionTree.getSelection(); // Then call editConnection or editStep or editTrans if (ti.length==1) { String name = ti[0].getText(); TreeItem parent = ti[0].getParentItem(); if (parent != null) { String type = parent.getText(); if (type.equalsIgnoreCase(STRING_CONNECTIONS)) { DatabaseMeta dbinfo = transMeta.findDatabase(name); if (dbinfo!=null) { DatabaseExplorerDialog std = new DatabaseExplorerDialog(shell, props, SWT.NONE, dbinfo, transMeta.getDatabases(), true ); std.open(); } else { MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR ); mb.setMessage(Messages.getString("Spoon.Dialog.CannotFindConnection.Message"));//"Couldn't find connection, please refresh the tree (F5)!" mb.setText(Messages.getString("Spoon.Dialog.CannotFindConnection.Title"));//"Error!" mb.open(); } } } else { if (name.equalsIgnoreCase(STRING_CONNECTIONS)) transMeta.getDbCache().clear(null); } } } public void analyseImpact() { AnalyseImpactProgressDialog aipd = new AnalyseImpactProgressDialog(log, props, shell, transMeta, impact); impactHasRun = aipd.open(); if (impactHasRun) showLastImpactAnalyses(); } public void showLastImpactAnalyses() { ArrayList rows = new ArrayList(); for (int i=0;i<impact.size();i++) { DatabaseImpact ii = (DatabaseImpact)impact.get(i); rows.add(ii.getRow()); } if (rows.size()>0) { // Display all the rows... PreviewRowsDialog prd = new PreviewRowsDialog(shell, SWT.NONE, "-", rows); prd.setTitleMessage(Messages.getString("Spoon.Dialog.ImpactAnalyses.Title"), Messages.getString("Spoon.Dialog.ImpactAnalyses.Message"));//"Impact analyses" "Result of analyses:" prd.open(); } else { MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION ); if (impactHasRun) { mb.setMessage(Messages.getString("Spoon.Dialog.TransformationNoImpactOnDatabase.Message"));//"As far as I can tell, this transformation has no impact on any database." } else { mb.setMessage(Messages.getString("Spoon.Dialog.RunImpactAnalysesFirst.Message"));//"Please run the impact analyses first on this transformation." } mb.setText(Messages.getString("Spoon.Dialog.ImpactAnalyses.Title"));//Impact mb.open(); } } /** * Get & show the SQL required to run the loaded transformation... * */ public void getSQL() { GetSQLProgressDialog pspd = new GetSQLProgressDialog(log, props, shell, transMeta); ArrayList stats = pspd.open(); if (stats!=null) // null means error, but we already displayed the error { if (stats.size()>0) { SQLStatementsDialog ssd = new SQLStatementsDialog(shell, SWT.NONE, stats); ssd.open(); } else { MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION ); mb.setMessage(Messages.getString("Spoon.Dialog.NoSQLNeedEexecuted.Message"));//As far as I can tell, no SQL statements need to be executed before this transformation can run. mb.setText(Messages.getString("Spoon.Dialog.NoSQLNeedEexecuted.Title"));//"SQL" mb.open(); } } } public void toClipboard(String cliptext) { props.toClipboard(cliptext); } public String fromClipboard() { return props.fromClipboard(); } /** * Paste transformation from the clipboard... * */ public void pasteTransformation() { log.logDetailed(toString(), Messages.getString("Spoon.Log.PasteTransformationFromClipboard"));//"Paste transformation from the clipboard!" if (showChangedWarning()) { String xml = fromClipboard(); try { Document doc = XMLHandler.loadXMLString(xml); transMeta = new TransMeta(XMLHandler.getSubNode(doc, "transformation")); refreshGraph(); refreshTree(true); } catch(KettleException e) { new ErrorDialog(shell, props, Messages.getString("Spoon.Dialog.ErrorPastingTransformation.Title"), Messages.getString("Spoon.Dialog.ErrorPastingTransformation.Message"), e);//Error pasting transformation "An error occurred pasting a transformation from the clipboard" } } } public void copyTransformation() { toClipboard(XMLHandler.getXMLHeader()+transMeta.getXML()); } public void copyTransformationImage() { Clipboard clipboard = props.getNewClipboard(); Point area = transMeta.getMaximum(); Image image = spoongraph.getTransformationImage(Display.getCurrent(), area.x, area.y); clipboard.setContents(new Object[] { image.getImageData() }, new Transfer[]{ImageDataTransfer.getInstance()}); /** System.out.println("image obtained: "+area.x+"x"+area.y); ShowImageDialog sid = new ShowImageDialog(shell, image); sid.open(); */ } /** * Shows a wizard that creates a new database connection... * */ private void createDatabaseWizard() { CreateDatabaseWizard cdw=new CreateDatabaseWizard(); DatabaseMeta newDBInfo=cdw.createAndRunDatabaseWizard(shell, props, transMeta.getDatabases()); if(newDBInfo!=null){ //finished transMeta.addDatabase(newDBInfo); refreshTree(true); refreshGraph(); } } /** * Create a transformation that extracts tables & data from a database.<p><p> * * 0) Select the database to rip<p> * 1) Select the table in the database to copy<p> * 2) Select the database to dump to<p> * 3) Select the repository directory in which it will end up<p> * 4) Select a name for the new transformation<p> * 6) Create 1 transformation for the selected table<p> */ private void copyTableWizard() { if (showChangedWarning()) { final CopyTableWizardPage1 page1 = new CopyTableWizardPage1("1", transMeta.getDatabases()); page1.createControl(shell); final CopyTableWizardPage2 page2 = new CopyTableWizardPage2("2"); page2.createControl(shell); final CopyTableWizardPage3 page3 = new CopyTableWizardPage3 ("3", rep); page3.createControl(shell); Wizard wizard = new Wizard() { public boolean performFinish() { return copyTable(page3.getTransformationName(), page3.getDirectory(), page1.getSourceDatabase(), page1.getTargetDatabase(), page2.getSelection() ); } /** * @see org.eclipse.jface.wizard.Wizard#canFinish() */ public boolean canFinish() { return page3.canFinish(); } }; wizard.addPage(page1); wizard.addPage(page2); wizard.addPage(page3); WizardDialog wd = new WizardDialog(shell, wizard); wd.setMinimumPageSize(700,400); wd.open(); } } public boolean copyTable( String transname, RepositoryDirectory repdir, DatabaseMeta sourceDBInfo, DatabaseMeta targetDBInfo, String tablename ) { try { // // Create a new transformation... // TransMeta ti = new TransMeta(); ti.setName(transname); ti.setDirectory(repdir); ti.setDatabases(transMeta.getDatabases()); // // Add a note // String note = Messages.getString("Spoon.Message.Note.ReadInformationFromTableOnDB",tablename,sourceDBInfo.getDatabaseName() )+Const.CR;//"Reads information from table ["+tablename+"] on database ["+sourceDBInfo+"]" note+=Messages.getString("Spoon.Message.Note.WriteInformationToTableOnDB",tablename,targetDBInfo.getDatabaseName() );//"After that, it writes the information to table ["+tablename+"] on database ["+targetDBInfo+"]" NotePadMeta ni = new NotePadMeta(note, 150, 10, -1, -1); ti.addNote(ni); // // create the source step... // String fromstepname = Messages.getString("Spoon.Message.Note.ReadFromTable",tablename); //"read from ["+tablename+"]"; TableInputMeta tii = new TableInputMeta(); tii.setDatabaseMeta(sourceDBInfo); tii.setSQL("SELECT * FROM "+tablename); StepLoader steploader = StepLoader.getInstance(); String fromstepid = steploader.getStepPluginID(tii); StepMeta fromstep = new StepMeta(log, fromstepid, fromstepname, (StepMetaInterface)tii ); fromstep.setLocation(150,100); fromstep.setDraw(true); fromstep.setDescription(Messages.getString("Spoon.Message.Note.ReadInformationFromTableOnDB",tablename,sourceDBInfo.getDatabaseName() )); ti.addStep(fromstep); // // add logic to rename fields in case any of the field names contain reserved words... // Use metadata logic in SelectValues, use SelectValueInfo... // Database sourceDB = new Database(sourceDBInfo); sourceDB.connect(); // Get the fields for the input table... Row fields = sourceDB.getTableFields(tablename); // See if we need to deal with reserved words... int nrReserved = targetDBInfo.getNrReservedWords(fields); if (nrReserved>0) { SelectValuesMeta svi = new SelectValuesMeta(); svi.allocate(0,0,nrReserved); int nr = 0; for (int i=0;i<fields.size();i++) { Value v = fields.getValue(i); if (targetDBInfo.isReservedWord( v.getName() ) ) { svi.getMetaName()[nr] = v.getName(); svi.getMetaRename()[nr] = targetDBInfo.quoteField( v.getName() ); nr++; } } String selstepname =Messages.getString("Spoon.Message.Note.HandleReservedWords"); //"Handle reserved words"; String selstepid = steploader.getStepPluginID(svi); StepMeta selstep = new StepMeta(log, selstepid, selstepname, (StepMetaInterface)svi ); selstep.setLocation(350,100); selstep.setDraw(true); selstep.setDescription(Messages.getString("Spoon.Message.Note.RenamesReservedWords",targetDBInfo.getDatabaseTypeDesc()) );//"Renames reserved words for "+targetDBInfo.getDatabaseTypeDesc() ti.addStep(selstep); TransHopMeta shi = new TransHopMeta(fromstep, selstep); ti.addTransHop(shi); fromstep = selstep; } // // Create the target step... // // // Add the TableOutputMeta step... // String tostepname = Messages.getString("Spoon.Message.Note.WriteToTable",tablename); // "write to ["+tablename+"]"; TableOutputMeta toi = new TableOutputMeta(); toi.setDatabase( targetDBInfo ); toi.setTablename( tablename ); toi.setCommitSize( 200 ); toi.setTruncateTable( true ); String tostepid = steploader.getStepPluginID(toi); StepMeta tostep = new StepMeta(log, tostepid, tostepname, (StepMetaInterface)toi ); tostep.setLocation(550,100); tostep.setDraw(true); tostep.setDescription(Messages.getString("Spoon.Message.Note.WriteInformationToTableOnDB2",tablename,targetDBInfo.getDatabaseName() ));//"Write information to table ["+tablename+"] on database ["+targetDBInfo+"]" ti.addStep(tostep); // // Add a hop between the two steps... // TransHopMeta hi = new TransHopMeta(fromstep, tostep); ti.addTransHop(hi); // OK, if we're still here: overwrite the current transformation... transMeta = ti; refreshGraph(); refreshTree(true); } catch(Exception e) { new ErrorDialog(shell, props, Messages.getString("Spoon.Dialog.UnexpectedError.Title"), Messages.getString("Spoon.Dialog.UnexpectedError.Message"), new KettleException(e.getMessage(), e));//"Unexpected error" "An unexpected error occurred creating the new transformation" return false; } return true; } public String toString() { return APP_NAME; } /** * This is the main procedure for Spoon. * * @param a Arguments are available in the "Get System Info" step. */ public static void main (String [] a) throws KettleException { EnvUtil.environmentInit(); ArrayList args = new ArrayList(); for (int i=0;i<a.length;i++) args.add(a[i]); Display display = new Display(); Splash splash = new Splash(display); StringBuffer optionRepname, optionUsername, optionPassword, optionTransname, optionFilename, optionDirname, optionLogfile, optionLoglevel; CommandLineOption options[] = new CommandLineOption[] { new CommandLineOption("rep", "Repository name", optionRepname=new StringBuffer()), new CommandLineOption("user", "Repository username", optionUsername=new StringBuffer()), new CommandLineOption("pass", "Repository password", optionPassword=new StringBuffer()), new CommandLineOption("trans", "The name of the transformation to launch", optionTransname=new StringBuffer()), new CommandLineOption("dir", "The directory (don't forget the leading /)", optionDirname=new StringBuffer()), new CommandLineOption("file", "The filename (Transformation in XML) to launch", optionFilename=new StringBuffer()), new CommandLineOption("level", "The logging level (Basic, Detailed, Debug, Rowlevel, Error, Nothing)", optionLoglevel=new StringBuffer()), new CommandLineOption("logfile", "The logging file to write to", optionLogfile=new StringBuffer()), new CommandLineOption("log", "The logging file to write to (deprecated)", optionLogfile=new StringBuffer(), false, true), }; // Parse the options... CommandLineOption.parseArguments(args, options); String kettleRepname = Const.getEnvironmentVariable("KETTLE_REPOSITORY", null); String kettleUsername = Const.getEnvironmentVariable("KETTLE_USER", null); String kettlePassword = Const.getEnvironmentVariable("KETTLE_PASSWORD", null); if (!Const.isEmpty(kettleRepname )) optionRepname = new StringBuffer(kettleRepname); if (!Const.isEmpty(kettleUsername)) optionUsername = new StringBuffer(kettleUsername); if (!Const.isEmpty(kettlePassword)) optionPassword = new StringBuffer(kettlePassword); // Before anything else, check the runtime version!!! String version = Const.JAVA_VERSION; if ("1.4".compareToIgnoreCase(version)>0) { System.out.println("The System is running on Java version "+version); System.out.println("Unfortunately, it needs version 1.4 or higher to run."); return; } // Set default Locale: Locale.setDefault(Const.DEFAULT_LOCALE); LogWriter log; if (Const.isEmpty(optionLogfile)) { log=LogWriter.getInstance(Const.SPOON_LOG_FILE, false, LogWriter.LOG_LEVEL_BASIC); } else { log=LogWriter.getInstance( optionLogfile.toString(), true, LogWriter.LOG_LEVEL_BASIC ); } if (log.getRealFilename()!=null) log.logBasic(APP_NAME, Messages.getString("Spoon.Log.LoggingToFile")+log.getRealFilename());//"Logging goes to " if (!Const.isEmpty(optionLoglevel)) { log.setLogLevel(optionLoglevel.toString()); log.logBasic(APP_NAME, Messages.getString("Spoon.Log.LoggingAtLevel")+log.getLogLevelDesc());//"Logging is at level : " } /* Load the plugins etc.*/ StepLoader stloader = StepLoader.getInstance(); if (!stloader.read()) { log.logError(APP_NAME, Messages.getString("Spoon.Log.ErrorLoadingAndHaltSystem"));//Error loading steps & plugins... halting Spoon! return; } /* Load the plugins etc. we need to load jobentry*/ JobEntryLoader jeloader = JobEntryLoader.getInstance(); if (!jeloader.read()) { log.logError("Spoon", "Error loading job entries & plugins... halting Kitchen!"); return; } final Spoon win = new Spoon(log, display, null); win.setDestroy(true); win.setArguments((String[])args.toArray(new String[args.size()])); log.logBasic(APP_NAME, Messages.getString("Spoon.Log.MainWindowCreated"));//Main window is created. RepositoryMeta repinfo = null; UserInfo userinfo = null; if (Const.isEmpty(optionRepname) && Const.isEmpty(optionFilename) && win.props.showRepositoriesDialogAtStartup()) { log.logBasic(APP_NAME, Messages.getString("Spoon.Log.AskingForRepository"));//"Asking for repository" int perms[] = new int[] { PermissionMeta.TYPE_PERMISSION_TRANSFORMATION }; splash.hide(); RepositoriesDialog rd = new RepositoriesDialog(win.disp, SWT.NONE, perms, Messages.getString("Spoon.Application.Name"));//"Spoon" if (rd.open()) { repinfo = rd.getRepository(); userinfo = rd.getUser(); if (!userinfo.useTransformations()) { MessageBox mb = new MessageBox(win.shell, SWT.OK | SWT.ICON_ERROR ); mb.setMessage(Messages.getString("Spoon.Dialog.RepositoryUserCannotWork.Message"));//"Sorry, this repository user can't work with transformations from the repository." mb.setText(Messages.getString("Spoon.Dialog.RepositoryUserCannotWork.Title"));//"Error!" mb.open(); userinfo = null; repinfo = null; } } else { // Exit point: user pressed CANCEL! if (rd.isCancelled()) { splash.dispose(); win.quitFile(); return; } } } try { // Read kettle transformation specified on command-line? if (!Const.isEmpty(optionRepname) || !Const.isEmpty(optionFilename)) { if (!Const.isEmpty(optionRepname)) { RepositoriesMeta repsinfo = new RepositoriesMeta(log); if (repsinfo.readData()) { repinfo = repsinfo.findRepository(optionRepname.toString()); if (repinfo!=null) { // Define and connect to the repository... win.rep = new Repository(log, repinfo, userinfo); if (win.rep.connect(Messages.getString("Spoon.Application.Name")))//"Spoon" { if (Const.isEmpty(optionDirname)) optionDirname=new StringBuffer(RepositoryDirectory.DIRECTORY_SEPARATOR); // Check username, password win.rep.userinfo = new UserInfo(win.rep, optionUsername.toString(), optionPassword.toString()); if (win.rep.userinfo.getID()>0) { RepositoryDirectory repdir = win.rep.getDirectoryTree().findDirectory(optionDirname.toString()); if (repdir!=null) { win.transMeta = new TransMeta(win.rep, optionTransname.toString(), repdir); win.setFilename(optionRepname.toString()); win.transMeta.clearChanged(); } else { log.logError(APP_NAME, Messages.getString("Spoon.Log.UnableFindDirectory",optionDirname.toString()));//"Can't find directory ["+dirname+"] in the repository." } } else { log.logError(APP_NAME, Messages.getString("Spoon.Log.UnableVerifyUser"));//"Can't verify username and password." win.rep.disconnect(); win.rep=null; } } else { log.logError(APP_NAME, Messages.getString("Spoon.Log.UnableConnectToRepository"));//"Can't connect to the repository." } } else { log.logError(APP_NAME, Messages.getString("Spoon.Log.NoRepositoryRrovided"));//"No repository provided, can't load transformation." } } else { log.logError(APP_NAME, Messages.getString("Spoon.Log.NoRepositoriesDefined"));//"No repositories defined on this system." } } else if (!Const.isEmpty(optionFilename)) { win.transMeta = new TransMeta(optionFilename.toString()); win.setFilename(optionFilename.toString()); win.transMeta.clearChanged(); } } else // Normal operations, nothing on the commandline... { // Can we connect to the repository? if (repinfo!=null && userinfo!=null) { win.rep = new Repository(log, repinfo, userinfo); if (!win.rep.connect(Messages.getString("Spoon.Application.Name"))) //"Spoon" { win.rep = null; } } if (win.props.openLastFile()) { log.logDetailed(APP_NAME, Messages.getString("Spoon.Log.TryingOpenLastUsedFile"));//"Trying to open the last file used." String lastfiles[] = win.props.getLastFiles(); String lastdirs[] = win.props.getLastDirs(); boolean lasttypes[] = win.props.getLastTypes(); String lastrepos[] = win.props.getLastRepositories(); if (lastfiles.length>0) { boolean use_repository = repinfo!=null; // Perhaps we need to connect to the repository? if (lasttypes[0]) { if (lastrepos[0]!=null && lastrepos[0].length()>0) { if (use_repository && !lastrepos[0].equalsIgnoreCase(repinfo.getName())) { // We just asked... use_repository = false; } } } if (use_repository || !lasttypes[0]) { if (win.rep!=null) // load from repository... { if (win.rep.getName().equalsIgnoreCase(lastrepos[0])) { RepositoryDirectory repdir = win.rep.getDirectoryTree().findDirectory(lastdirs[0]); if (repdir!=null) { log.logDetailed(APP_NAME, Messages.getString("Spoon.Log.AutoLoadingTransformation",lastfiles[0],lastdirs[0]));//"Auto loading transformation ["+lastfiles[0]+"] from repository directory ["+lastdirs[0]+"]" TransLoadProgressDialog tlpd = new TransLoadProgressDialog(win.shell, win.rep, lastfiles[0], repdir); TransMeta transInfo = tlpd.open(); // = new TransInfo(log, win.rep, lastfiles[0], repdir); if (transInfo != null) { win.transMeta = transInfo; win.setFilename(lastfiles[0]); } } } } else // Load from XML? { win.transMeta = new TransMeta(lastfiles[0]); win.setFilename(lastfiles[0]); } } win.transMeta.clearChanged(); } } } } catch(KettleException ke) { log.logError(APP_NAME, Messages.getString("Spoon.Log.ErrorOccurred")+Const.CR+ke.getMessage());//"An error occurred: " win.rep=null; // ke.printStackTrace(); } win.open (); splash.dispose(); try { while (!win.isDisposed ()) { if (!win.readAndDispatch ()) win.sleep (); } } catch(Throwable e) { log.logError(APP_NAME, Messages.getString("Spoon.Log.UnexpectedErrorOccurred")+Const.CR+e.getMessage());//"An unexpected error occurred in Spoon: probable cause: please close all windows before stopping Spoon! " e.printStackTrace(); } win.dispose(); log.logBasic(APP_NAME, APP_NAME+" "+Messages.getString("Spoon.Log.AppHasEnded"));//" has ended." // Close the logfile log.close(); // Kill all remaining things in this VM! System.exit(0); } /** * @return Returns the transMeta. */ public TransMeta getTransMeta() { return transMeta; } /** * @param transMeta The transMeta to set. */ public void setTransMeta(TransMeta transMeta) { this.transMeta = transMeta; } /** * Create a new SelectValues step in between this step and the previous. * If the previous fields are not there, no mapping can be made, same with the required fields. * @param stepMeta The target step to map against. */ public void generateMapping(StepMeta stepMeta) { try { if (stepMeta!=null) { StepMetaInterface smi = stepMeta.getStepMetaInterface(); Row targetFields = smi.getRequiredFields(); Row sourceFields = transMeta.getPrevStepFields(stepMeta); // Build the mapping: let the user decide!! String[] source = sourceFields.getFieldNames(); for (int i=0;i<source.length;i++) { Value v = sourceFields.getValue(i); source[i]+=EnterMappingDialog.STRING_ORIGIN_SEPARATOR+v.getOrigin()+")"; } String[] target = targetFields.getFieldNames(); EnterMappingDialog dialog = new EnterMappingDialog(shell, source, target); ArrayList mappings = dialog.open(); if (mappings!=null) { // OK, so we now know which field maps where. // This allows us to generate the mapping using a SelectValues Step... SelectValuesMeta svm = new SelectValuesMeta(); svm.allocate(mappings.size(), 0, 0); for (int i=0;i<mappings.size();i++) { SourceToTargetMapping mapping = (SourceToTargetMapping) mappings.get(i); svm.getSelectName()[i] = sourceFields.getValue(mapping.getSourcePosition()).getName(); svm.getSelectRename()[i] = target[mapping.getTargetPosition()]; svm.getSelectLength()[i] = -1; svm.getSelectPrecision()[i] = -1; } // Now that we have the meta-data, create a new step info object String stepName = stepMeta.getName()+" Mapping"; stepName = transMeta.getAlternativeStepname(stepName); // if it's already there, rename it. StepMeta newStep = new StepMeta(log, "SelectValues", stepName, svm); newStep.setLocation(stepMeta.getLocation().x+20, stepMeta.getLocation().y+20); newStep.setDraw(true); transMeta.addStep(newStep); addUndoNew(new StepMeta[] { newStep }, new int[] { transMeta.indexOfStep(newStep) }); // Redraw stuff... refreshTree(); refreshGraph(); } } else { System.out.println("No target to do mapping against!"); } } catch(KettleException e) { new ErrorDialog(shell, Props.getInstance(), "Error creating mapping", "There was an error when Kettle tried to generate a mapping against the target step", e); } } }
public boolean quitFile() { boolean exit = true; boolean showWarning = true; log.logDetailed(toString(), Messages.getString("Spoon.Log.QuitApplication"));//"Quit application." saveSettings(); if (transMeta.hasChanged()) { MessageBox mb = new MessageBox(shell, SWT.YES | SWT.NO | SWT.CANCEL | SWT.ICON_WARNING ); mb.setMessage(Messages.getString("Spoon.Dialog.SaveChangedFile.Message"));//"File has changed! Do you want to save first?" mb.setText(Messages.getString("Spoon.Dialog.SaveChangedFile.Title"));//"Warning!" int answer = mb.open(); switch(answer) { case SWT.YES: exit=saveFile(); showWarning=false; break; case SWT.NO: exit=true; showWarning=false; break; case SWT.CANCEL: exit=false; showWarning=false; break; } } // System.out.println("exit="+exit+", showWarning="+showWarning+", running="+spoonlog.isRunning()+", showExitWarning="+props.showExitWarning()); // Show warning on exit when spoon is still running // Show warning on exit when a warning needs to be displayed, but only if we didn't ask to save before. (could have pressed cancel then!) // if ( (exit && spoonlog.isRunning() ) || (exit && showWarning && props.showExitWarning() ) ) { String message = Messages.getString("Spoon.Message.Warning.PromptExit"); //"Are you sure you want to exit?" if (spoonlog.isRunning()) message = Messages.getString("Spoon.Message.Warning.PromptExitWhenRunTransformation");//There is a running transformation. Are you sure you want to exit? MessageDialogWithToggle md = new MessageDialogWithToggle(shell, Messages.getString("System.Warning"),//"Warning!" null, message, MessageDialog.WARNING, new String[] { Messages.getString("Spoon.Message.Warning.Yes"), Messages.getString("Spoon.Message.Warning.No") },//"Yes", "No" 1, Messages.getString("Spoon.Message.Warning.NotShowWarning"),//"Please, don't show this warning anymore." !props.showExitWarning() ); int idx = md.open(); props.setExitWarningShown(!md.getToggleState()); props.saveProps(); if (idx==1) exit=false; // No selected: don't exit! else exit=true; } if (exit) dispose(); return exit; } public boolean saveFile() { boolean saved=false; log.logDetailed(toString(), Messages.getString("Spoon.Log.SaveToFileOrRepository"));//"Save to file or repository..." if (rep!=null) { saved=saveRepository(); } else { if (transMeta.getFilename()!=null) { saved=save(transMeta.getFilename()); } else { saved=saveFileAs(); } } try { if (props.useDBCache()) transMeta.getDbCache().saveCache(log); } catch(KettleException e) { new ErrorDialog(shell, props, Messages.getString("Spoon.Dialog.ErrorSavingDatabaseCache.Title"), Messages.getString("Spoon.Dialog.ErrorSavingDatabaseCache.Message"), e);//"An error occured saving the database cache to disk" } return saved; } public boolean saveRepository() { return saveRepository(false); } public boolean saveRepository(boolean ask_name) { log.logDetailed(toString(), Messages.getString("Spoon.Log.SaveToRepository"));//"Save to repository..." if (rep!=null) { boolean answer = true; boolean ask = ask_name; while (answer && ( ask || transMeta.getName()==null || transMeta.getName().length()==0 ) ) { if (!ask) { MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_WARNING); mb.setMessage(Messages.getString("Spoon.Dialog.PromptTransformationName.Message"));//"Please give this transformation a name before saving it in the database." mb.setText(Messages.getString("Spoon.Dialog.PromptTransformationName.Title"));//"Transformation has no name." mb.open(); } ask=false; answer = setTrans(); // System.out.println("answer="+answer+", ask="+ask+", transMeta.getName()="+transMeta.getName()); } if (answer && transMeta.getName()!=null && transMeta.getName().length()>0) { if (!rep.getUserInfo().isReadonly()) { int response = SWT.YES; if (transMeta.showReplaceWarning(rep)) { MessageBox mb = new MessageBox(shell, SWT.YES | SWT.NO | SWT.ICON_QUESTION); mb.setMessage(Messages.getString("Spoon.Dialog.PromptOverwriteTransformation.Message",transMeta.getName(),Const.CR));//"There already is a transformation called ["+transMeta.getName()+"] in the repository."+Const.CR+"Do you want to overwrite the transformation?" mb.setText(Messages.getString("Spoon.Dialog.PromptOverwriteTransformation.Title"));//"Overwrite?" response = mb.open(); } boolean saved=false; if (response == SWT.YES) { shell.setCursor(cursor_hourglass); // Keep info on who & when this transformation was changed... transMeta.setModifiedDate( new Value("MODIFIED_DATE", Value.VALUE_TYPE_DATE) ); transMeta.getModifiedDate().sysdate(); transMeta.setModifiedUser( rep.getUserInfo().getLogin() ); TransSaveProgressDialog tspd = new TransSaveProgressDialog(log, props, shell, rep, transMeta); if (tspd.open()) { saved=true; if (!props.getSaveConfirmation()) { MessageDialogWithToggle md = new MessageDialogWithToggle(shell, Messages.getString("Spoon.Message.Warning.SaveOK"), //"Save OK!" null, Messages.getString("Spoon.Message.Warning.TransformationWasStored"),//"This transformation was stored in repository" MessageDialog.QUESTION, new String[] { Messages.getString("Spoon.Message.Warning.OK") },//"OK!" 0, Messages.getString("Spoon.Message.Warning.NotShowThisMessage"),//"Don't show this message again." props.getSaveConfirmation() ); md.open(); props.setSaveConfirmation(md.getToggleState()); } // Handle last opened files... props.addLastFile(Props.TYPE_PROPERTIES_SPOON, transMeta.getName(), transMeta.getDirectory().getPath(), true, getRepositoryName()); saveSettings(); addMenuLast(); setShellText(); } shell.setCursor(null); } return saved; } else { MessageBox mb = new MessageBox(shell, SWT.CLOSE | SWT.ICON_ERROR); mb.setMessage(Messages.getString("Spoon.Dialog.OnlyreadRepository.Message"));//"Sorry, the user you're logged on with, can only read from the repository" mb.setText(Messages.getString("Spoon.Dialog.OnlyreadRepository.Title"));//"Transformation not saved!" mb.open(); } } } else { MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR); mb.setMessage(Messages.getString("Spoon.Dialog.NoRepositoryConnection.Message"));//"There is no repository connection available." mb.setText(Messages.getString("Spoon.Dialog.NoRepositoryConnection.Title"));//"No repository available." mb.open(); } return false; } public boolean saveFileAs() { boolean saved=false; log.logBasic(toString(), Messages.getString("Spoon.Log.SaveAs"));//"Save as..." if (rep!=null) { transMeta.setID(-1L); saved=saveRepository(true); } else { saved=saveXMLFile(); } return saved; } private boolean saveXMLFile() { boolean saved=false; FileDialog dialog = new FileDialog(shell, SWT.SAVE); dialog.setFilterPath("C:\\Projects\\kettle\\source\\"); dialog.setFilterExtensions(Const.STRING_TRANS_FILTER_EXT); dialog.setFilterNames(Const.STRING_TRANS_FILTER_NAMES); String fname = dialog.open(); if (fname!=null) { // Is the filename ending on .ktr, .xml? boolean ending=false; for (int i=0;i<Const.STRING_TRANS_FILTER_EXT.length-1;i++) { if (fname.endsWith(Const.STRING_TRANS_FILTER_EXT[i].substring(1))) { ending=true; } } if (fname.endsWith(Const.STRING_TRANS_DEFAULT_EXT)) ending=true; if (!ending) { fname+=Const.STRING_TRANS_DEFAULT_EXT; } // See if the file already exists... File f = new File(fname); int id = SWT.YES; if (f.exists()) { MessageBox mb = new MessageBox(shell, SWT.NO | SWT.YES | SWT.ICON_WARNING); mb.setMessage(Messages.getString("Spoon.Dialog.PromptOverwriteFile.Message"));//"This file already exists. Do you want to overwrite it?" mb.setText(Messages.getString("Spoon.Dialog.PromptOverwriteFile.Title"));//"This file already exists!" id = mb.open(); } if (id==SWT.YES) { saved=save(fname); setFilename(fname); } } return saved; } private boolean save(String fname) { boolean saved = false; String xml = XMLHandler.getXMLHeader() + transMeta.getXML(); try { DataOutputStream dos = new DataOutputStream(new FileOutputStream(new File(fname))); dos.write(xml.getBytes(Const.XML_ENCODING)); dos.close(); saved=true; // Handle last opened files... props.addLastFile(Props.TYPE_PROPERTIES_SPOON, fname, Const.FILE_SEPARATOR, false, ""); saveSettings(); addMenuLast(); transMeta.clearChanged(); setShellText(); log.logDebug(toString(), Messages.getString("Spoon.Log.FileWritten")+" ["+fname+"]"); //"File written to } catch(Exception e) { log.logDebug(toString(), Messages.getString("Spoon.Log.ErrorOpeningFileForWriting")+e.toString());//"Error opening file for writing! --> " MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR); mb.setMessage(Messages.getString("Spoon.Dialog.ErrorSavingFile.Message")+Const.CR+e.toString());//"Error saving file:" mb.setText(Messages.getString("Spoon.Dialog.ErrorSavingFile.Title"));//"ERROR" mb.open(); } return saved; } public void helpAbout() { MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION | SWT.CENTER); String mess = Messages.getString("System.ProductInfo")+Const.VERSION+Const.CR+Const.CR+Const.CR;//Kettle - Spoon version mess+=Messages.getString("System.CompanyInfo")+Const.CR; mess+=" "+Messages.getString("System.ProductWebsiteUrl")+Const.CR; //(c) 2001-2004 i-Bridge bvba www.kettle.be mess+=" "+BuildVersion.getInstance().getVersion()+Const.CR; mb.setMessage(mess); mb.setText(APP_NAME); mb.open(); } public void editUnselectAll() { transMeta.unselectAll(); spoongraph.redraw(); } public void editSelectAll() { transMeta.selectAll(); spoongraph.redraw(); } public void editOptions() { EnterOptionsDialog eod = new EnterOptionsDialog(shell, props); if (eod.open()!=null) { props.saveProps(); loadSettings(); changeLooks(); MessageBox mb = new MessageBox(shell, SWT.ICON_INFORMATION); mb.setMessage(Messages.getString("Spoon.Dialog.PleaseRestartApplication.Message")); mb.setText(Messages.getString("Spoon.Dialog.PleaseRestartApplication.Title")); mb.open(); } } public int getTreePosition(TreeItem ti, String item) { if (ti!=null) { TreeItem items[] = ti.getItems(); for (int x=0;x<items.length;x++) { if (items[x].getText().equalsIgnoreCase(item)) { return x; } } } return -1; } public void refreshTree() { refreshTree(false); refreshPluginHistory(); } /** * Refresh the object selection tree (on the left of the screen) * @param complete true refreshes the complete tree, false tries to do a differential update to avoid flickering. */ public void refreshTree(boolean complete) { if (shell.isDisposed()) return; if (!transMeta.hasChanged() && !complete) return; // Nothing changed: nothing to do! int idx; TreeItem ti[]; // Refresh the connections... // if (transMeta.haveConnectionsChanged() || complete) { tiConn.setText(STRING_CONNECTIONS); // TreeItem tiConn= this.tiConn (TreeItem)widgets.getWidget(STRING_CONNECTIONS); ti = tiConn.getItems(); // In complete refresh: delete all items first if (complete) { for (int i=0;i<ti.length;i++) ti[i].dispose(); ti = tiConn.getItems(); } // First delete no longer used items... for (int i=0;i<ti.length;i++) { String str = ti[i].getText(); DatabaseMeta inf = transMeta.findDatabase(str); if (inf!=null) idx = transMeta.indexOfDatabase(inf); else idx=-1; if (idx<0 || idx>i) ti[i].dispose(); } ti = tiConn.getItems(); // Insert missing items in tree... int j=0; for (int i=0;i<transMeta.nrDatabases();i++) { DatabaseMeta inf = transMeta.getDatabase(i); String con_name = inf.getName(); String ti_name = ""; if (j<ti.length) ti_name = ti[j].getText(); if (!con_name.equalsIgnoreCase(ti_name)) { // insert at position j in tree TreeItem newitem = new TreeItem(tiConn, j); newitem.setText(inf.getName()); newitem.setForeground(GUIResource.getInstance().getColorBlack()); newitem.setImage(GUIResource.getInstance().getImageConnection()); j++; ti = tiConn.getItems(); } else { j++; } } // tiConn.setExpanded(true); } //ni.setImage(gv.hop_image); //ni.setImage(gv.step_images_small[steptype]); // Refresh the Steps... // if (transMeta.haveStepsChanged() || complete) { tiStep.setText(STRING_STEPS); ti = tiStep.getItems(); // In complete refresh: delete all items first if (complete) { for (int i=0;i<ti.length;i++) ti[i].dispose(); ti = tiStep.getItems(); } // First delete no longer used items... log.logDebug(toString(), Messages.getString("Spoon.Log.CheckSteps"));//"check steps" for (int i=0;i<ti.length;i++) { String str = ti[i].getText(); log.logDebug(toString(), " "+Messages.getString("Spoon.Log.CheckStepTreeItem")+i+" : ["+str+"]"); StepMeta inf = transMeta.findStep(str); if (inf!=null) idx = transMeta.indexOfStep(inf); else idx=-1; if (idx<0 || idx>i) { log.logDebug(toString(), " "+ Messages.getString("Spoon.Log.RemoveTreeItem")+ "["+str+"]");//remove tree item ti[i].dispose(); } } ti = tiStep.getItems(); // Insert missing items in tree... int j=0; for (int i=0;i<transMeta.nrSteps();i++) { StepMeta inf = transMeta.getStep(i); String step_name = inf.getName(); String step_id = inf.getStepID(); String ti_name = ""; if (j<ti.length) ti_name = ti[j].getText(); if (!step_name.equalsIgnoreCase(ti_name)) { // insert at position j in tree TreeItem newitem = new TreeItem(tiStep, j); newitem.setText(inf.getName()); // Set the small image... Image img = (Image)GUIResource.getInstance().getImagesStepsSmall().get(step_id); newitem.setImage(img); j++; ti = tiStep.getItems(); } else { j++; } } // See if the colors are still OK! for (int i=0;i<ti.length;i++) { StepMeta inf = transMeta.findStep(ti[i].getText()); Color col = ti[i].getForeground(); Color newcol; if (transMeta.isStepUsedInTransHops(inf)) newcol=GUIResource.getInstance().getColorBlack(); else newcol=GUIResource.getInstance().getColorGray(); if (!newcol.equals(col)) ti[i].setForeground(newcol); } //tiStep.setExpanded(true); } // Refresh the Hops... // if (transMeta.haveHopsChanged() || complete) { tiHops.setText(STRING_HOPS); ti = tiHops.getItems(); // In complete refresh: delete all items first if (complete) { for (int i=0;i<ti.length;i++) ti[i].dispose(); ti = tiHops.getItems(); } // First delete no longer used items... for (int i=0;i<ti.length;i++) { String str = ti[i].getText(); TransHopMeta inf = transMeta.findTransHop(str); if (inf!=null) idx = transMeta.indexOfTransHop(inf); else idx=-1; if (idx<0 || idx>i) ti[i].dispose(); } ti = tiHops.getItems(); // Insert missing items in tree... int j=0; for (int i=0;i<transMeta.nrTransHops();i++) { TransHopMeta inf = transMeta.getTransHop(i); String trans_name = inf.toString(); String ti_name = ""; if (j<ti.length) ti_name = ti[j].getText(); if (!trans_name.equalsIgnoreCase(ti_name)) { // insert at position j in tree TreeItem newitem = new TreeItem(tiHops, j); newitem.setText(inf.toString()); newitem.setForeground(GUIResource.getInstance().getColorBlack()); newitem.setImage(GUIResource.getInstance().getImageHop()); j++; ti = tiHops.getItems(); } else { j++; } } // tiTrns.setExpanded(false); } selectionTree.setFocus(); setShellText(); } public void refreshGraph() { if (shell.isDisposed()) return; spoongraph.redraw(); setShellText(); } public void refreshHistory() { spoonhist.refreshHistory(); } public StepMeta newStep() { return newStep(true, true); } public StepMeta newStep(boolean openit, boolean rename) { TreeItem ti[] = selectionTree.getSelection(); StepMeta inf = null; if (ti.length==1) { String steptype = ti[0].getText(); log.logDebug(toString(), Messages.getString("Spoon.Log.NewStep")+steptype);//"New step: " inf = newStep(steptype, steptype, openit, rename); } return inf; } /** * Allocate new step, optionally open and rename it. * * @param name Name of the new step * @param description Description of the type of step * @param openit Open the dialog for this step? * @param rename Rename this step? * * @return The newly created StepMeta object. * */ public StepMeta newStep(String name, String description, boolean openit, boolean rename) { StepMeta inf = null; // See if we need to rename the step to avoid doubles! if (rename && transMeta.findStep(name)!=null) { int i=2; String newname = name+" "+i; while (transMeta.findStep(newname)!=null) { i++; newname = name+" "+i; } name=newname; } StepLoader steploader = StepLoader.getInstance(); StepPlugin stepPlugin = null; try { stepPlugin = steploader.findStepPluginWithDescription(description); if (stepPlugin!=null) { StepMetaInterface info = BaseStep.getStepInfo(stepPlugin, steploader); info.setDefault(); if (openit) { StepDialogInterface dialog = info.getDialog(shell, info, transMeta, name); name = dialog.open(); } inf=new StepMeta(log, stepPlugin.getID()[0], name, info); if (name!=null) // OK pressed in the dialog: we have a step-name { String newname=name; StepMeta stepMeta = transMeta.findStep(newname); int nr=2; while (stepMeta!=null) { newname = name+" "+nr; stepMeta = transMeta.findStep(newname); nr++; } if (nr>2) { inf.setName(newname); MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION); mb.setMessage(Messages.getString("Spoon.Dialog.ChangeStepname.Message",newname));//"This stepname already exists. Spoon changed the stepname to ["+newname+"]" mb.setText(Messages.getString("Spoon.Dialog.ChangeStepname.Title"));//"Info!" mb.open(); } inf.setLocation(20, 20); // default location at (20,20) transMeta.addStep(inf); // Save for later: // if openit is false: we drag&drop it onto the canvas! if (openit) { addUndoNew(new StepMeta[] { inf }, new int[] { transMeta.indexOfStep(inf) }); } // Also store it in the pluginHistory list... props.addPluginHistory(stepPlugin.getID()[0]); refreshTree(); } else { return null; // Cancel pressed in dialog. } setShellText(); } } catch(KettleException e) { String filename = stepPlugin.getErrorHelpFile(); if (stepPlugin!=null && filename!=null) { // OK, in stead of a normal error message, we give back the content of the error help file... (HTML) try { StringBuffer content=new StringBuffer(); System.out.println("Filename = "+filename); FileInputStream fis = new FileInputStream(new File(filename)); int ch = fis.read(); while (ch>=0) { content.append( (char)ch); ch = fis.read(); } System.out.println("Content = "+content); ShowBrowserDialog sbd = new ShowBrowserDialog(shell, Messages.getString("Spoon.Dialog.ErrorHelpText.Title"), content.toString());//"Error help text" sbd.open(); } catch(Exception ex) { new ErrorDialog(shell, props, Messages.getString("Spoon.Dialog.ErrorShowingHelpText.Title"), Messages.getString("Spoon.Dialog.ErrorShowingHelpText.Message"), ex);//"Error showing help text" } } else { new ErrorDialog(shell, props, Messages.getString("Spoon.Dialog.UnableCreateNewStep.Title"),Messages.getString("Spoon.Dialog.UnableCreateNewStep.Message") , e);//"Error creating step" "I was unable to create a new step" } return null; } catch(Throwable e) { if (!shell.isDisposed()) new ErrorDialog(shell, props, Messages.getString("Spoon.Dialog.ErrorCreatingStep.Title"), Messages.getString("Spoon.Dialog.UnableCreateNewStep.Message"), new Exception(e));//"Error creating step" return null; } return inf; } private void setTreeImages() { tiConn.setImage(GUIResource.getInstance().getImageConnection()); tiHops.setImage(GUIResource.getInstance().getImageHop()); tiStep.setImage(GUIResource.getInstance().getImageBol()); tiBase.setImage(GUIResource.getInstance().getImageBol()); tiPlug.setImage(GUIResource.getInstance().getImageBol()); TreeItem tiBaseCat[]=tiBase.getItems(); for (int x=0;x<tiBaseCat.length;x++) { tiBaseCat[x].setImage(GUIResource.getInstance().getImageBol()); TreeItem ti[] = tiBaseCat[x].getItems(); for (int i=0;i<ti.length;i++) { TreeItem stepitem = ti[i]; String description = stepitem.getText(); StepLoader steploader = StepLoader.getInstance(); StepPlugin sp = steploader.findStepPluginWithDescription(description); if (sp!=null) { Image stepimg = (Image)GUIResource.getInstance().getImagesStepsSmall().get(sp.getID()[0]); if (stepimg!=null) { stepitem.setImage(stepimg); } } } } TreeItem tiPlugCat[]=tiPlug.getItems(); for (int x=0;x<tiPlugCat.length;x++) { tiPlugCat[x].setImage(GUIResource.getInstance().getImageBol()); TreeItem ti[] = tiPlugCat[x].getItems(); for (int i=0;i<ti.length;i++) { TreeItem stepitem = ti[i]; String description = stepitem.getText(); StepLoader steploader = StepLoader.getInstance(); StepPlugin sp = steploader.findStepPluginWithDescription(description); if (sp!=null) { Image stepimg = (Image)GUIResource.getInstance().getImagesStepsSmall().get(sp.getID()); if (stepimg!=null) { stepitem.setImage(stepimg); } } } } } public DatabaseMeta getConnection(String name) { int i; for (i=0;i<transMeta.nrDatabases();i++) { DatabaseMeta ci = transMeta.getDatabase(i); if (ci.getName().equalsIgnoreCase(name)) { return ci; } } return null; } public void setShellText() { String fname = transMeta.getFilename(); if (shell.isDisposed()) return; if (rep!=null) { String repository = "["+getRepositoryName()+"]"; String transname = transMeta.getName(); if (transname==null) transname=Messages.getString("Spoon.Various.NoName");//"[no name]" shell.setText(APPL_TITLE+" - "+repository+" "+transname+(transMeta.hasChanged()?(" "+Messages.getString("Spoon.Various.Changed")):""));//(changed) } else { String repository = Messages.getString("Spoon.Various.NoRepository");//"[no repository]" if (fname!=null) { shell.setText(APPL_TITLE+" - "+repository+" File: "+fname+(transMeta.hasChanged()?(" "+Messages.getString("Spoon.Various.Changed")):"")); } else { shell.setText(APPL_TITLE+" - "+repository+" "+(transMeta.hasChanged()?(" "+Messages.getString("Spoon.Various.Changed")):"")); } } } public void setFilename(String fname) { if (fname!=null) transMeta.setFilename(fname); setShellText(); } private void printFile() { PrintSpool ps = new PrintSpool(); Printer printer = ps.getPrinter(shell); // Create an image of the screen Point max = transMeta.getMaximum(); Image img = spoongraph.getTransformationImage(printer, max.x, max.y); ps.printImage(shell, props, img); img.dispose(); ps.dispose(); } private boolean setTrans() { TransDialog tid = new TransDialog(shell, SWT.NONE, transMeta, rep); TransMeta ti = tid.open(); setShellText(); return ti!=null; } public void saveSettings() { WindowProperty winprop = new WindowProperty(shell); winprop.setName(APPL_TITLE); props.setScreen(winprop); props.setLogLevel(log.getLogLevelDesc()); props.setLogFilter(log.getFilter()); props.setSashWeights(sashform.getWeights()); props.saveProps(); } public void loadSettings() { log.setLogLevel(props.getLogLevel()); log.setFilter(props.getLogFilter()); transMeta.setMaxUndo(props.getMaxUndo()); transMeta.getDbCache().setActive(props.useDBCache()); } public void changeLooks() { props.setLook(selectionTree); props.setLook(tabfolder, Props.WIDGET_STYLE_TAB); spoongraph.newProps(); refreshTree(); refreshGraph(); } public void undoAction() { spoongraph.forceFocus(); TransAction ta = transMeta.previousUndo(); if (ta==null) return; setUndoMenu(); // something changed: change the menu switch(ta.getType()) { // // NEW // // We created a new step : undo this... case TransAction.TYPE_ACTION_NEW_STEP: // Delete the step at correct location: for (int i=ta.getCurrent().length-1;i>=0;i--) { int idx = ta.getCurrentIndex()[i]; transMeta.removeStep(idx); } refreshTree(); refreshGraph(); break; // We created a new connection : undo this... case TransAction.TYPE_ACTION_NEW_CONNECTION: // Delete the connection at correct location: for (int i=ta.getCurrent().length-1;i>=0;i--) { int idx = ta.getCurrentIndex()[i]; transMeta.removeDatabase(idx); } refreshTree(); refreshGraph(); break; // We created a new note : undo this... case TransAction.TYPE_ACTION_NEW_NOTE: // Delete the note at correct location: for (int i=ta.getCurrent().length-1;i>=0;i--) { int idx = ta.getCurrentIndex()[i]; transMeta.removeNote(idx); } refreshTree(); refreshGraph(); break; // We created a new hop : undo this... case TransAction.TYPE_ACTION_NEW_HOP: // Delete the hop at correct location: for (int i=ta.getCurrent().length-1;i>=0;i--) { int idx = ta.getCurrentIndex()[i]; transMeta.removeTransHop(idx); } refreshTree(); refreshGraph(); break; // // DELETE // // We delete a step : undo this... case TransAction.TYPE_ACTION_DELETE_STEP: // un-Delete the step at correct location: re-insert for (int i=0;i<ta.getCurrent().length;i++) { StepMeta stepMeta = (StepMeta)ta.getCurrent()[i]; int idx = ta.getCurrentIndex()[i]; transMeta.addStep(idx, stepMeta); } refreshTree(); refreshGraph(); break; // We deleted a connection : undo this... case TransAction.TYPE_ACTION_DELETE_CONNECTION: // re-insert the connection at correct location: for (int i=0;i<ta.getCurrent().length;i++) { DatabaseMeta ci = (DatabaseMeta)ta.getCurrent()[i]; int idx = ta.getCurrentIndex()[i]; transMeta.addDatabase(idx, ci); } refreshTree(); refreshGraph(); break; // We delete new note : undo this... case TransAction.TYPE_ACTION_DELETE_NOTE: // re-insert the note at correct location: for (int i=0;i<ta.getCurrent().length;i++) { NotePadMeta ni = (NotePadMeta)ta.getCurrent()[i]; int idx = ta.getCurrentIndex()[i]; transMeta.addNote(idx, ni); } refreshTree(); refreshGraph(); break; // We deleted a hop : undo this... case TransAction.TYPE_ACTION_DELETE_HOP: // re-insert the hop at correct location: for (int i=0;i<ta.getCurrent().length;i++) { TransHopMeta hi = (TransHopMeta)ta.getCurrent()[i]; int idx = ta.getCurrentIndex()[i]; // Build a new hop: StepMeta from = transMeta.findStep(hi.getFromStep().getName()); StepMeta to = transMeta.findStep(hi.getToStep().getName()); TransHopMeta hinew = new TransHopMeta(from, to); transMeta.addTransHop(idx, hinew); } refreshTree(); refreshGraph(); break; // // CHANGE // // We changed a step : undo this... case TransAction.TYPE_ACTION_CHANGE_STEP: // Delete the current step, insert previous version. for (int i=0;i<ta.getCurrent().length;i++) { StepMeta prev = (StepMeta)ta.getPrevious()[i]; int idx = ta.getCurrentIndex()[i]; transMeta.removeStep(idx); transMeta.addStep(idx, prev); } refreshTree(); refreshGraph(); break; // We changed a connection : undo this... case TransAction.TYPE_ACTION_CHANGE_CONNECTION: // Delete & re-insert for (int i=0;i<ta.getCurrent().length;i++) { DatabaseMeta prev = (DatabaseMeta)ta.getPrevious()[i]; int idx = ta.getCurrentIndex()[i]; transMeta.removeDatabase(idx); transMeta.addDatabase(idx, prev); } refreshTree(); refreshGraph(); break; // We changed a note : undo this... case TransAction.TYPE_ACTION_CHANGE_NOTE: // Delete & re-insert for (int i=0;i<ta.getCurrent().length;i++) { int idx = ta.getCurrentIndex()[i]; transMeta.removeNote(idx); NotePadMeta prev = (NotePadMeta)ta.getPrevious()[i]; transMeta.addNote(idx, prev); } refreshTree(); refreshGraph(); break; // We changed a hop : undo this... case TransAction.TYPE_ACTION_CHANGE_HOP: // Delete & re-insert for (int i=0;i<ta.getCurrent().length;i++) { TransHopMeta prev = (TransHopMeta)ta.getPrevious()[i]; int idx = ta.getCurrentIndex()[i]; transMeta.removeTransHop(idx); transMeta.addTransHop(idx, prev); } refreshTree(); refreshGraph(); break; // // POSITION // // The position of a step has changed: undo this... case TransAction.TYPE_ACTION_POSITION_STEP: // Find the location of the step: for (int i = 0; i < ta.getCurrentIndex().length; i++) { StepMeta stepMeta = transMeta.getStep(ta.getCurrentIndex()[i]); stepMeta.setLocation(ta.getPreviousLocation()[i]); } refreshGraph(); break; // The position of a note has changed: undo this... case TransAction.TYPE_ACTION_POSITION_NOTE: for (int i=0;i<ta.getCurrentIndex().length;i++) { int idx = ta.getCurrentIndex()[i]; NotePadMeta npi = transMeta.getNote(idx); Point prev = ta.getPreviousLocation()[i]; npi.setLocation(prev); } refreshGraph(); break; default: break; } // OK, now check if we need to do this again... if (transMeta.viewNextUndo()!=null) { if (transMeta.viewNextUndo().getNextAlso()) undoAction(); } } public void redoAction() { spoongraph.forceFocus(); TransAction ta = transMeta.nextUndo(); if (ta==null) return; setUndoMenu(); // something changed: change the menu switch(ta.getType()) { // // NEW // case TransAction.TYPE_ACTION_NEW_STEP: // re-delete the step at correct location: for (int i=0;i<ta.getCurrent().length;i++) { StepMeta stepMeta = (StepMeta)ta.getCurrent()[i]; int idx = ta.getCurrentIndex()[i]; transMeta.addStep(idx, stepMeta); refreshTree(); refreshGraph(); } break; case TransAction.TYPE_ACTION_NEW_CONNECTION: // re-insert the connection at correct location: for (int i=0;i<ta.getCurrent().length;i++) { DatabaseMeta ci = (DatabaseMeta)ta.getCurrent()[i]; int idx = ta.getCurrentIndex()[i]; transMeta.addDatabase(idx, ci); refreshTree(); refreshGraph(); } break; case TransAction.TYPE_ACTION_NEW_NOTE: // re-insert the note at correct location: for (int i=0;i<ta.getCurrent().length;i++) { NotePadMeta ni = (NotePadMeta)ta.getCurrent()[i]; int idx = ta.getCurrentIndex()[i]; transMeta.addNote(idx, ni); refreshTree(); refreshGraph(); } break; case TransAction.TYPE_ACTION_NEW_HOP: // re-insert the hop at correct location: for (int i=0;i<ta.getCurrent().length;i++) { TransHopMeta hi = (TransHopMeta)ta.getCurrent()[i]; int idx = ta.getCurrentIndex()[i]; transMeta.addTransHop(idx, hi); refreshTree(); refreshGraph(); } break; // // DELETE // case TransAction.TYPE_ACTION_DELETE_STEP: // re-remove the step at correct location: for (int i=ta.getCurrent().length-1;i>=0;i--) { int idx = ta.getCurrentIndex()[i]; transMeta.removeStep(idx); } refreshTree(); refreshGraph(); break; case TransAction.TYPE_ACTION_DELETE_CONNECTION: // re-remove the connection at correct location: for (int i=ta.getCurrent().length-1;i>=0;i--) { int idx = ta.getCurrentIndex()[i]; transMeta.removeDatabase(idx); } refreshTree(); refreshGraph(); break; case TransAction.TYPE_ACTION_DELETE_NOTE: // re-remove the note at correct location: for (int i=ta.getCurrent().length-1;i>=0;i--) { int idx = ta.getCurrentIndex()[i]; transMeta.removeNote(idx); } refreshTree(); refreshGraph(); break; case TransAction.TYPE_ACTION_DELETE_HOP: // re-remove the hop at correct location: for (int i=ta.getCurrent().length-1;i>=0;i--) { int idx = ta.getCurrentIndex()[i]; transMeta.removeTransHop(idx); } refreshTree(); refreshGraph(); break; // // CHANGE // // We changed a step : undo this... case TransAction.TYPE_ACTION_CHANGE_STEP: // Delete the current step, insert previous version. for (int i=0;i<ta.getCurrent().length;i++) { StepMeta stepMeta = (StepMeta)ta.getCurrent()[i]; int idx = ta.getCurrentIndex()[i]; transMeta.removeStep(idx); transMeta.addStep(idx, stepMeta); } refreshTree(); refreshGraph(); break; // We changed a connection : undo this... case TransAction.TYPE_ACTION_CHANGE_CONNECTION: // Delete & re-insert for (int i=0;i<ta.getCurrent().length;i++) { DatabaseMeta ci = (DatabaseMeta)ta.getCurrent()[i]; int idx = ta.getCurrentIndex()[i]; transMeta.removeDatabase(idx); transMeta.addDatabase(idx, ci); } refreshTree(); refreshGraph(); break; // We changed a note : undo this... case TransAction.TYPE_ACTION_CHANGE_NOTE: // Delete & re-insert for (int i=0;i<ta.getCurrent().length;i++) { NotePadMeta ni = (NotePadMeta)ta.getCurrent()[i]; int idx = ta.getCurrentIndex()[i]; transMeta.removeNote(idx); transMeta.addNote(idx, ni); } refreshTree(); refreshGraph(); break; // We changed a hop : undo this... case TransAction.TYPE_ACTION_CHANGE_HOP: // Delete & re-insert for (int i=0;i<ta.getCurrent().length;i++) { TransHopMeta hi = (TransHopMeta)ta.getCurrent()[i]; int idx = ta.getCurrentIndex()[i]; transMeta.removeTransHop(idx); transMeta.addTransHop(idx, hi); } refreshTree(); refreshGraph(); break; // // CHANGE POSITION // case TransAction.TYPE_ACTION_POSITION_STEP: for (int i=0;i<ta.getCurrentIndex().length;i++) { // Find & change the location of the step: StepMeta stepMeta = transMeta.getStep(ta.getCurrentIndex()[i]); stepMeta.setLocation(ta.getCurrentLocation()[i]); } refreshGraph(); break; case TransAction.TYPE_ACTION_POSITION_NOTE: for (int i=0;i<ta.getCurrentIndex().length;i++) { int idx = ta.getCurrentIndex()[i]; NotePadMeta npi = transMeta.getNote(idx); Point curr = ta.getCurrentLocation()[i]; npi.setLocation(curr); } refreshGraph(); break; default: break; } // OK, now check if we need to do this again... if (transMeta.viewNextUndo()!=null) { if (transMeta.viewNextUndo().getNextAlso()) redoAction(); } } public void setUndoMenu() { if (shell.isDisposed()) return; TransAction prev = transMeta.viewThisUndo(); TransAction next = transMeta.viewNextUndo(); if (prev!=null) { miEditUndo.setEnabled(true); miEditUndo.setText(Messages.getString("Spoon.Menu.Undo.Available", prev.toString()));//"Undo : "+prev.toString()+" \tCTRL-Z" } else { miEditUndo.setEnabled(false); miEditUndo.setText(Messages.getString("Spoon.Menu.Undo.NotAvailable"));//"Undo : not available \tCTRL-Z" } if (next!=null) { miEditRedo.setEnabled(true); miEditRedo.setText(Messages.getString("Spoon.Menu.Redo.Available",next.toString()));//"Redo : "+next.toString()+" \tCTRL-Y" } else { miEditRedo.setEnabled(false); miEditRedo.setText(Messages.getString("Spoon.Menu.Redo.NotAvailable"));//"Redo : not available \tCTRL-Y" } } public void addUndoNew(Object obj[], int position[]) { addUndoNew(obj, position, false); } public void addUndoNew(Object obj[], int position[], boolean nextAlso) { // New object? transMeta.addUndo(obj, null, position, null, null, TransMeta.TYPE_UNDO_NEW, nextAlso); setUndoMenu(); } // Undo delete object public void addUndoDelete(Object obj[], int position[]) { addUndoDelete(obj, position, false); } // Undo delete object public void addUndoDelete(Object obj[], int position[], boolean nextAlso) { transMeta.addUndo(obj, null, position, null, null, TransMeta.TYPE_UNDO_DELETE, nextAlso); setUndoMenu(); } // Change of step, connection, hop or note... public void addUndoPosition(Object obj[], int pos[], Point prev[], Point curr[]) { addUndoPosition(obj, pos, prev, curr, false); } // Change of step, connection, hop or note... public void addUndoPosition(Object obj[], int pos[], Point prev[], Point curr[], boolean nextAlso) { // It's better to store the indexes of the objects, not the objects itself! transMeta.addUndo(obj, null, pos, prev, curr, TransMeta.TYPE_UNDO_POSITION, nextAlso); setUndoMenu(); } // Change of step, connection, hop or note... public void addUndoChange(Object from[], Object to[], int[] pos) { addUndoChange(from, to, pos, false); } // Change of step, connection, hop or note... public void addUndoChange(Object from[], Object to[], int[] pos, boolean nextAlso) { transMeta.addUndo(from, to, pos, null, null, TransMeta.TYPE_UNDO_CHANGE, nextAlso); setUndoMenu(); } /** * Checks *all* the steps in the transformation, puts the result in remarks list */ public void checkTrans() { checkTrans(false); } /** * Check the steps in a transformation * * @param only_selected True: Check only the selected steps... */ public void checkTrans(boolean only_selected) { CheckTransProgressDialog ctpd = new CheckTransProgressDialog(log, props, shell, transMeta, remarks, only_selected); ctpd.open(); // manages the remarks arraylist... showLastTransCheck(); } /** * Show the remarks of the last transformation check that was run. * @see #checkTrans() */ public void showLastTransCheck() { CheckResultDialog crd = new CheckResultDialog(shell, SWT.NONE, remarks); String stepname = crd.open(); if (stepname!=null) { // Go to the indicated step! StepMeta stepMeta = transMeta.findStep(stepname); if (stepMeta!=null) { editStepInfo(stepMeta); } } } public void clearDBCache() { // Determine what menu we selected from... TreeItem ti[] = selectionTree.getSelection(); // Then call editConnection or editStep or editTrans if (ti.length==1) { String name = ti[0].getText(); TreeItem parent = ti[0].getParentItem(); if (parent != null) { String type = parent.getText(); if (type.equalsIgnoreCase(STRING_CONNECTIONS)) { transMeta.getDbCache().clear(name); } } else { if (name.equalsIgnoreCase(STRING_CONNECTIONS)) transMeta.getDbCache().clear(null); } } } public void exploreDB() { // Determine what menu we selected from... TreeItem ti[] = selectionTree.getSelection(); // Then call editConnection or editStep or editTrans if (ti.length==1) { String name = ti[0].getText(); TreeItem parent = ti[0].getParentItem(); if (parent != null) { String type = parent.getText(); if (type.equalsIgnoreCase(STRING_CONNECTIONS)) { DatabaseMeta dbinfo = transMeta.findDatabase(name); if (dbinfo!=null) { DatabaseExplorerDialog std = new DatabaseExplorerDialog(shell, props, SWT.NONE, dbinfo, transMeta.getDatabases(), true ); std.open(); } else { MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR ); mb.setMessage(Messages.getString("Spoon.Dialog.CannotFindConnection.Message"));//"Couldn't find connection, please refresh the tree (F5)!" mb.setText(Messages.getString("Spoon.Dialog.CannotFindConnection.Title"));//"Error!" mb.open(); } } } else { if (name.equalsIgnoreCase(STRING_CONNECTIONS)) transMeta.getDbCache().clear(null); } } } public void analyseImpact() { AnalyseImpactProgressDialog aipd = new AnalyseImpactProgressDialog(log, props, shell, transMeta, impact); impactHasRun = aipd.open(); if (impactHasRun) showLastImpactAnalyses(); } public void showLastImpactAnalyses() { ArrayList rows = new ArrayList(); for (int i=0;i<impact.size();i++) { DatabaseImpact ii = (DatabaseImpact)impact.get(i); rows.add(ii.getRow()); } if (rows.size()>0) { // Display all the rows... PreviewRowsDialog prd = new PreviewRowsDialog(shell, SWT.NONE, "-", rows); prd.setTitleMessage(Messages.getString("Spoon.Dialog.ImpactAnalyses.Title"), Messages.getString("Spoon.Dialog.ImpactAnalyses.Message"));//"Impact analyses" "Result of analyses:" prd.open(); } else { MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION ); if (impactHasRun) { mb.setMessage(Messages.getString("Spoon.Dialog.TransformationNoImpactOnDatabase.Message"));//"As far as I can tell, this transformation has no impact on any database." } else { mb.setMessage(Messages.getString("Spoon.Dialog.RunImpactAnalysesFirst.Message"));//"Please run the impact analyses first on this transformation." } mb.setText(Messages.getString("Spoon.Dialog.ImpactAnalyses.Title"));//Impact mb.open(); } } /** * Get & show the SQL required to run the loaded transformation... * */ public void getSQL() { GetSQLProgressDialog pspd = new GetSQLProgressDialog(log, props, shell, transMeta); ArrayList stats = pspd.open(); if (stats!=null) // null means error, but we already displayed the error { if (stats.size()>0) { SQLStatementsDialog ssd = new SQLStatementsDialog(shell, SWT.NONE, stats); ssd.open(); } else { MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION ); mb.setMessage(Messages.getString("Spoon.Dialog.NoSQLNeedEexecuted.Message"));//As far as I can tell, no SQL statements need to be executed before this transformation can run. mb.setText(Messages.getString("Spoon.Dialog.NoSQLNeedEexecuted.Title"));//"SQL" mb.open(); } } } public void toClipboard(String cliptext) { props.toClipboard(cliptext); } public String fromClipboard() { return props.fromClipboard(); } /** * Paste transformation from the clipboard... * */ public void pasteTransformation() { log.logDetailed(toString(), Messages.getString("Spoon.Log.PasteTransformationFromClipboard"));//"Paste transformation from the clipboard!" if (showChangedWarning()) { String xml = fromClipboard(); try { Document doc = XMLHandler.loadXMLString(xml); transMeta = new TransMeta(XMLHandler.getSubNode(doc, "transformation")); refreshGraph(); refreshTree(true); } catch(KettleException e) { new ErrorDialog(shell, props, Messages.getString("Spoon.Dialog.ErrorPastingTransformation.Title"), Messages.getString("Spoon.Dialog.ErrorPastingTransformation.Message"), e);//Error pasting transformation "An error occurred pasting a transformation from the clipboard" } } } public void copyTransformation() { toClipboard(XMLHandler.getXMLHeader()+transMeta.getXML()); } public void copyTransformationImage() { Clipboard clipboard = props.getNewClipboard(); Point area = transMeta.getMaximum(); Image image = spoongraph.getTransformationImage(Display.getCurrent(), area.x, area.y); clipboard.setContents(new Object[] { image.getImageData() }, new Transfer[]{ImageDataTransfer.getInstance()}); /** System.out.println("image obtained: "+area.x+"x"+area.y); ShowImageDialog sid = new ShowImageDialog(shell, image); sid.open(); */ } /** * Shows a wizard that creates a new database connection... * */ private void createDatabaseWizard() { CreateDatabaseWizard cdw=new CreateDatabaseWizard(); DatabaseMeta newDBInfo=cdw.createAndRunDatabaseWizard(shell, props, transMeta.getDatabases()); if(newDBInfo!=null){ //finished transMeta.addDatabase(newDBInfo); refreshTree(true); refreshGraph(); } } /** * Create a transformation that extracts tables & data from a database.<p><p> * * 0) Select the database to rip<p> * 1) Select the table in the database to copy<p> * 2) Select the database to dump to<p> * 3) Select the repository directory in which it will end up<p> * 4) Select a name for the new transformation<p> * 6) Create 1 transformation for the selected table<p> */ private void copyTableWizard() { if (showChangedWarning()) { final CopyTableWizardPage1 page1 = new CopyTableWizardPage1("1", transMeta.getDatabases()); page1.createControl(shell); final CopyTableWizardPage2 page2 = new CopyTableWizardPage2("2"); page2.createControl(shell); final CopyTableWizardPage3 page3 = new CopyTableWizardPage3 ("3", rep); page3.createControl(shell); Wizard wizard = new Wizard() { public boolean performFinish() { return copyTable(page3.getTransformationName(), page3.getDirectory(), page1.getSourceDatabase(), page1.getTargetDatabase(), page2.getSelection() ); } /** * @see org.eclipse.jface.wizard.Wizard#canFinish() */ public boolean canFinish() { return page3.canFinish(); } }; wizard.addPage(page1); wizard.addPage(page2); wizard.addPage(page3); WizardDialog wd = new WizardDialog(shell, wizard); wd.setMinimumPageSize(700,400); wd.open(); } } public boolean copyTable( String transname, RepositoryDirectory repdir, DatabaseMeta sourceDBInfo, DatabaseMeta targetDBInfo, String tablename ) { try { // // Create a new transformation... // TransMeta ti = new TransMeta(); ti.setName(transname); ti.setDirectory(repdir); ti.setDatabases(transMeta.getDatabases()); // // Add a note // String note = Messages.getString("Spoon.Message.Note.ReadInformationFromTableOnDB",tablename,sourceDBInfo.getDatabaseName() )+Const.CR;//"Reads information from table ["+tablename+"] on database ["+sourceDBInfo+"]" note+=Messages.getString("Spoon.Message.Note.WriteInformationToTableOnDB",tablename,targetDBInfo.getDatabaseName() );//"After that, it writes the information to table ["+tablename+"] on database ["+targetDBInfo+"]" NotePadMeta ni = new NotePadMeta(note, 150, 10, -1, -1); ti.addNote(ni); // // create the source step... // String fromstepname = Messages.getString("Spoon.Message.Note.ReadFromTable",tablename); //"read from ["+tablename+"]"; TableInputMeta tii = new TableInputMeta(); tii.setDatabaseMeta(sourceDBInfo); tii.setSQL("SELECT * FROM "+tablename); StepLoader steploader = StepLoader.getInstance(); String fromstepid = steploader.getStepPluginID(tii); StepMeta fromstep = new StepMeta(log, fromstepid, fromstepname, (StepMetaInterface)tii ); fromstep.setLocation(150,100); fromstep.setDraw(true); fromstep.setDescription(Messages.getString("Spoon.Message.Note.ReadInformationFromTableOnDB",tablename,sourceDBInfo.getDatabaseName() )); ti.addStep(fromstep); // // add logic to rename fields in case any of the field names contain reserved words... // Use metadata logic in SelectValues, use SelectValueInfo... // Database sourceDB = new Database(sourceDBInfo); sourceDB.connect(); // Get the fields for the input table... Row fields = sourceDB.getTableFields(tablename); // See if we need to deal with reserved words... int nrReserved = targetDBInfo.getNrReservedWords(fields); if (nrReserved>0) { SelectValuesMeta svi = new SelectValuesMeta(); svi.allocate(0,0,nrReserved); int nr = 0; for (int i=0;i<fields.size();i++) { Value v = fields.getValue(i); if (targetDBInfo.isReservedWord( v.getName() ) ) { svi.getMetaName()[nr] = v.getName(); svi.getMetaRename()[nr] = targetDBInfo.quoteField( v.getName() ); nr++; } } String selstepname =Messages.getString("Spoon.Message.Note.HandleReservedWords"); //"Handle reserved words"; String selstepid = steploader.getStepPluginID(svi); StepMeta selstep = new StepMeta(log, selstepid, selstepname, (StepMetaInterface)svi ); selstep.setLocation(350,100); selstep.setDraw(true); selstep.setDescription(Messages.getString("Spoon.Message.Note.RenamesReservedWords",targetDBInfo.getDatabaseTypeDesc()) );//"Renames reserved words for "+targetDBInfo.getDatabaseTypeDesc() ti.addStep(selstep); TransHopMeta shi = new TransHopMeta(fromstep, selstep); ti.addTransHop(shi); fromstep = selstep; } // // Create the target step... // // // Add the TableOutputMeta step... // String tostepname = Messages.getString("Spoon.Message.Note.WriteToTable",tablename); // "write to ["+tablename+"]"; TableOutputMeta toi = new TableOutputMeta(); toi.setDatabase( targetDBInfo ); toi.setTablename( tablename ); toi.setCommitSize( 200 ); toi.setTruncateTable( true ); String tostepid = steploader.getStepPluginID(toi); StepMeta tostep = new StepMeta(log, tostepid, tostepname, (StepMetaInterface)toi ); tostep.setLocation(550,100); tostep.setDraw(true); tostep.setDescription(Messages.getString("Spoon.Message.Note.WriteInformationToTableOnDB2",tablename,targetDBInfo.getDatabaseName() ));//"Write information to table ["+tablename+"] on database ["+targetDBInfo+"]" ti.addStep(tostep); // // Add a hop between the two steps... // TransHopMeta hi = new TransHopMeta(fromstep, tostep); ti.addTransHop(hi); // OK, if we're still here: overwrite the current transformation... transMeta = ti; refreshGraph(); refreshTree(true); } catch(Exception e) { new ErrorDialog(shell, props, Messages.getString("Spoon.Dialog.UnexpectedError.Title"), Messages.getString("Spoon.Dialog.UnexpectedError.Message"), new KettleException(e.getMessage(), e));//"Unexpected error" "An unexpected error occurred creating the new transformation" return false; } return true; } public String toString() { return APP_NAME; } /** * This is the main procedure for Spoon. * * @param a Arguments are available in the "Get System Info" step. */ public static void main (String [] a) throws KettleException { EnvUtil.environmentInit(); ArrayList args = new ArrayList(); for (int i=0;i<a.length;i++) args.add(a[i]); Display display = new Display(); Splash splash = new Splash(display); StringBuffer optionRepname, optionUsername, optionPassword, optionTransname, optionFilename, optionDirname, optionLogfile, optionLoglevel; CommandLineOption options[] = new CommandLineOption[] { new CommandLineOption("rep", "Repository name", optionRepname=new StringBuffer()), new CommandLineOption("user", "Repository username", optionUsername=new StringBuffer()), new CommandLineOption("pass", "Repository password", optionPassword=new StringBuffer()), new CommandLineOption("trans", "The name of the transformation to launch", optionTransname=new StringBuffer()), new CommandLineOption("dir", "The directory (don't forget the leading /)", optionDirname=new StringBuffer()), new CommandLineOption("file", "The filename (Transformation in XML) to launch", optionFilename=new StringBuffer()), new CommandLineOption("level", "The logging level (Basic, Detailed, Debug, Rowlevel, Error, Nothing)", optionLoglevel=new StringBuffer()), new CommandLineOption("logfile", "The logging file to write to", optionLogfile=new StringBuffer()), new CommandLineOption("log", "The logging file to write to (deprecated)", optionLogfile=new StringBuffer(), false, true), }; // Parse the options... CommandLineOption.parseArguments(args, options); String kettleRepname = Const.getEnvironmentVariable("KETTLE_REPOSITORY", null); String kettleUsername = Const.getEnvironmentVariable("KETTLE_USER", null); String kettlePassword = Const.getEnvironmentVariable("KETTLE_PASSWORD", null); if (!Const.isEmpty(kettleRepname )) optionRepname = new StringBuffer(kettleRepname); if (!Const.isEmpty(kettleUsername)) optionUsername = new StringBuffer(kettleUsername); if (!Const.isEmpty(kettlePassword)) optionPassword = new StringBuffer(kettlePassword); // Before anything else, check the runtime version!!! String version = Const.JAVA_VERSION; if ("1.4".compareToIgnoreCase(version)>0) { System.out.println("The System is running on Java version "+version); System.out.println("Unfortunately, it needs version 1.4 or higher to run."); return; } // Set default Locale: Locale.setDefault(Const.DEFAULT_LOCALE); LogWriter log; if (Const.isEmpty(optionLogfile)) { log=LogWriter.getInstance(Const.SPOON_LOG_FILE, false, LogWriter.LOG_LEVEL_BASIC); } else { log=LogWriter.getInstance( optionLogfile.toString(), true, LogWriter.LOG_LEVEL_BASIC ); } if (log.getRealFilename()!=null) log.logBasic(APP_NAME, Messages.getString("Spoon.Log.LoggingToFile")+log.getRealFilename());//"Logging goes to " if (!Const.isEmpty(optionLoglevel)) { log.setLogLevel(optionLoglevel.toString()); log.logBasic(APP_NAME, Messages.getString("Spoon.Log.LoggingAtLevel")+log.getLogLevelDesc());//"Logging is at level : " } /* Load the plugins etc.*/ StepLoader stloader = StepLoader.getInstance(); if (!stloader.read()) { log.logError(APP_NAME, Messages.getString("Spoon.Log.ErrorLoadingAndHaltSystem"));//Error loading steps & plugins... halting Spoon! return; } /* Load the plugins etc. we need to load jobentry*/ JobEntryLoader jeloader = JobEntryLoader.getInstance(); if (!jeloader.read()) { log.logError("Spoon", "Error loading job entries & plugins... halting Kitchen!"); return; } final Spoon win = new Spoon(log, display, null); win.setDestroy(true); win.setArguments((String[])args.toArray(new String[args.size()])); log.logBasic(APP_NAME, Messages.getString("Spoon.Log.MainWindowCreated"));//Main window is created. RepositoryMeta repinfo = null; UserInfo userinfo = null; if (Const.isEmpty(optionRepname) && Const.isEmpty(optionFilename) && win.props.showRepositoriesDialogAtStartup()) { log.logBasic(APP_NAME, Messages.getString("Spoon.Log.AskingForRepository"));//"Asking for repository" int perms[] = new int[] { PermissionMeta.TYPE_PERMISSION_TRANSFORMATION }; splash.hide(); RepositoriesDialog rd = new RepositoriesDialog(win.disp, SWT.NONE, perms, Messages.getString("Spoon.Application.Name"));//"Spoon" if (rd.open()) { repinfo = rd.getRepository(); userinfo = rd.getUser(); if (!userinfo.useTransformations()) { MessageBox mb = new MessageBox(win.shell, SWT.OK | SWT.ICON_ERROR ); mb.setMessage(Messages.getString("Spoon.Dialog.RepositoryUserCannotWork.Message"));//"Sorry, this repository user can't work with transformations from the repository." mb.setText(Messages.getString("Spoon.Dialog.RepositoryUserCannotWork.Title"));//"Error!" mb.open(); userinfo = null; repinfo = null; } } else { // Exit point: user pressed CANCEL! if (rd.isCancelled()) { splash.dispose(); win.quitFile(); return; } } } try { // Read kettle transformation specified on command-line? if (!Const.isEmpty(optionRepname) || !Const.isEmpty(optionFilename)) { if (!Const.isEmpty(optionRepname)) { RepositoriesMeta repsinfo = new RepositoriesMeta(log); if (repsinfo.readData()) { repinfo = repsinfo.findRepository(optionRepname.toString()); if (repinfo!=null) { // Define and connect to the repository... win.rep = new Repository(log, repinfo, userinfo); if (win.rep.connect(Messages.getString("Spoon.Application.Name")))//"Spoon" { if (Const.isEmpty(optionDirname)) optionDirname=new StringBuffer(RepositoryDirectory.DIRECTORY_SEPARATOR); // Check username, password win.rep.userinfo = new UserInfo(win.rep, optionUsername.toString(), optionPassword.toString()); if (win.rep.userinfo.getID()>0) { // OK, if we have a specified transformation, try to load it... // If not, keep the repository logged in. if (!Const.isEmpty(optionTransname)) { RepositoryDirectory repdir = win.rep.getDirectoryTree().findDirectory(optionDirname.toString()); if (repdir!=null) { win.transMeta = new TransMeta(win.rep, optionTransname.toString(), repdir); win.setFilename(optionRepname.toString()); win.transMeta.clearChanged(); } else { log.logError(APP_NAME, Messages.getString("Spoon.Log.UnableFindDirectory",optionDirname.toString()));//"Can't find directory ["+dirname+"] in the repository." } } } else { log.logError(APP_NAME, Messages.getString("Spoon.Log.UnableVerifyUser"));//"Can't verify username and password." win.rep.disconnect(); win.rep=null; } } else { log.logError(APP_NAME, Messages.getString("Spoon.Log.UnableConnectToRepository"));//"Can't connect to the repository." } } else { log.logError(APP_NAME, Messages.getString("Spoon.Log.NoRepositoryRrovided"));//"No repository provided, can't load transformation." } } else { log.logError(APP_NAME, Messages.getString("Spoon.Log.NoRepositoriesDefined"));//"No repositories defined on this system." } } else if (!Const.isEmpty(optionFilename)) { win.transMeta = new TransMeta(optionFilename.toString()); win.setFilename(optionFilename.toString()); win.transMeta.clearChanged(); } } else // Normal operations, nothing on the commandline... { // Can we connect to the repository? if (repinfo!=null && userinfo!=null) { win.rep = new Repository(log, repinfo, userinfo); if (!win.rep.connect(Messages.getString("Spoon.Application.Name"))) //"Spoon" { win.rep = null; } } if (win.props.openLastFile()) { log.logDetailed(APP_NAME, Messages.getString("Spoon.Log.TryingOpenLastUsedFile"));//"Trying to open the last file used." String lastfiles[] = win.props.getLastFiles(); String lastdirs[] = win.props.getLastDirs(); boolean lasttypes[] = win.props.getLastTypes(); String lastrepos[] = win.props.getLastRepositories(); if (lastfiles.length>0) { boolean use_repository = repinfo!=null; // Perhaps we need to connect to the repository? if (lasttypes[0]) { if (lastrepos[0]!=null && lastrepos[0].length()>0) { if (use_repository && !lastrepos[0].equalsIgnoreCase(repinfo.getName())) { // We just asked... use_repository = false; } } } if (use_repository || !lasttypes[0]) { if (win.rep!=null) // load from repository... { if (win.rep.getName().equalsIgnoreCase(lastrepos[0])) { RepositoryDirectory repdir = win.rep.getDirectoryTree().findDirectory(lastdirs[0]); if (repdir!=null) { log.logDetailed(APP_NAME, Messages.getString("Spoon.Log.AutoLoadingTransformation",lastfiles[0],lastdirs[0]));//"Auto loading transformation ["+lastfiles[0]+"] from repository directory ["+lastdirs[0]+"]" TransLoadProgressDialog tlpd = new TransLoadProgressDialog(win.shell, win.rep, lastfiles[0], repdir); TransMeta transInfo = tlpd.open(); // = new TransInfo(log, win.rep, lastfiles[0], repdir); if (transInfo != null) { win.transMeta = transInfo; win.setFilename(lastfiles[0]); } } } } else // Load from XML? { win.transMeta = new TransMeta(lastfiles[0]); win.setFilename(lastfiles[0]); } } win.transMeta.clearChanged(); } } } } catch(KettleException ke) { log.logError(APP_NAME, Messages.getString("Spoon.Log.ErrorOccurred")+Const.CR+ke.getMessage());//"An error occurred: " win.rep=null; // ke.printStackTrace(); } win.open (); splash.dispose(); try { while (!win.isDisposed ()) { if (!win.readAndDispatch ()) win.sleep (); } } catch(Throwable e) { log.logError(APP_NAME, Messages.getString("Spoon.Log.UnexpectedErrorOccurred")+Const.CR+e.getMessage());//"An unexpected error occurred in Spoon: probable cause: please close all windows before stopping Spoon! " e.printStackTrace(); } win.dispose(); log.logBasic(APP_NAME, APP_NAME+" "+Messages.getString("Spoon.Log.AppHasEnded"));//" has ended." // Close the logfile log.close(); // Kill all remaining things in this VM! System.exit(0); } /** * @return Returns the transMeta. */ public TransMeta getTransMeta() { return transMeta; } /** * @param transMeta The transMeta to set. */ public void setTransMeta(TransMeta transMeta) { this.transMeta = transMeta; } /** * Create a new SelectValues step in between this step and the previous. * If the previous fields are not there, no mapping can be made, same with the required fields. * @param stepMeta The target step to map against. */ public void generateMapping(StepMeta stepMeta) { try { if (stepMeta!=null) { StepMetaInterface smi = stepMeta.getStepMetaInterface(); Row targetFields = smi.getRequiredFields(); Row sourceFields = transMeta.getPrevStepFields(stepMeta); // Build the mapping: let the user decide!! String[] source = sourceFields.getFieldNames(); for (int i=0;i<source.length;i++) { Value v = sourceFields.getValue(i); source[i]+=EnterMappingDialog.STRING_ORIGIN_SEPARATOR+v.getOrigin()+")"; } String[] target = targetFields.getFieldNames(); EnterMappingDialog dialog = new EnterMappingDialog(shell, source, target); ArrayList mappings = dialog.open(); if (mappings!=null) { // OK, so we now know which field maps where. // This allows us to generate the mapping using a SelectValues Step... SelectValuesMeta svm = new SelectValuesMeta(); svm.allocate(mappings.size(), 0, 0); for (int i=0;i<mappings.size();i++) { SourceToTargetMapping mapping = (SourceToTargetMapping) mappings.get(i); svm.getSelectName()[i] = sourceFields.getValue(mapping.getSourcePosition()).getName(); svm.getSelectRename()[i] = target[mapping.getTargetPosition()]; svm.getSelectLength()[i] = -1; svm.getSelectPrecision()[i] = -1; } // Now that we have the meta-data, create a new step info object String stepName = stepMeta.getName()+" Mapping"; stepName = transMeta.getAlternativeStepname(stepName); // if it's already there, rename it. StepMeta newStep = new StepMeta(log, "SelectValues", stepName, svm); newStep.setLocation(stepMeta.getLocation().x+20, stepMeta.getLocation().y+20); newStep.setDraw(true); transMeta.addStep(newStep); addUndoNew(new StepMeta[] { newStep }, new int[] { transMeta.indexOfStep(newStep) }); // Redraw stuff... refreshTree(); refreshGraph(); } } else { System.out.println("No target to do mapping against!"); } } catch(KettleException e) { new ErrorDialog(shell, Props.getInstance(), "Error creating mapping", "There was an error when Kettle tried to generate a mapping against the target step", e); } } }
diff --git a/soar-robotics/sps/src/org/msoar/sps/Odometry.java b/soar-robotics/sps/src/org/msoar/sps/Odometry.java index b13778293..ea6552f66 100644 --- a/soar-robotics/sps/src/org/msoar/sps/Odometry.java +++ b/soar-robotics/sps/src/org/msoar/sps/Odometry.java @@ -1,54 +1,54 @@ package org.msoar.sps; import jmat.LinAlg; import jmat.MathUtil; import lcmtypes.pose_t; import org.apache.log4j.Logger; import org.msoar.sps.lcmtypes.odom_t; public class Odometry { private static Logger logger = Logger.getLogger(Odometry.class); private final double tickMeters; private final double baselineMeters; private double[] deltaxyt = new double[3]; public Odometry(double tickMeters, double baselineMeters) { this.tickMeters = tickMeters; this.baselineMeters = baselineMeters; } public void propagate(odom_t newOdom, odom_t oldOdom, pose_t pose) { - System.out.println("delta left ticks: " + (newOdom.left - oldOdom.left)); - System.out.println("delta right ticks: " + (newOdom.right - oldOdom.right)); + //System.out.println("delta left ticks: " + (newOdom.left - oldOdom.left)); + //System.out.println("delta right ticks: " + (newOdom.right - oldOdom.right)); double dleft = (newOdom.left - oldOdom.left) * tickMeters; double dright = (newOdom.right - oldOdom.right) * tickMeters; // phi deltaxyt[2] = MathUtil.mod2pi((dright - dleft) / baselineMeters); double dCenter = (dleft + dright) / 2; // delta x, delta y - deltaxyt[0] += dCenter * Math.cos(deltaxyt[2]); - deltaxyt[1] += dCenter * Math.sin(deltaxyt[2]); + deltaxyt[0] = dCenter * Math.cos(deltaxyt[2]); + deltaxyt[1] = dCenter * Math.sin(deltaxyt[2]); // our current theta double theta = LinAlg.quatToRollPitchYaw(pose.orientation)[2]; // calculate and store new xyt pose.pos[0] += (deltaxyt[0] * Math.cos(theta)) - (deltaxyt[1] * Math.sin(theta)); pose.pos[1] += (deltaxyt[0] * Math.sin(theta)) + (deltaxyt[1] * Math.cos(theta)); theta += deltaxyt[2]; // convert theta to quat and store pose.orientation = LinAlg.rollPitchYawToQuat(new double[] {0, 0, theta}); if (logger.isTraceEnabled()) { theta = MathUtil.mod2pi(theta); theta = Math.toDegrees(theta); logger.trace(String.format("odom: n(%d,%d) o(%d,%d) p(%5.2f,%5.2f,%5.1f)", newOdom.left, newOdom.right, oldOdom.left, oldOdom.right, pose.pos[0], pose.pos[1], theta)); } } }
false
true
public void propagate(odom_t newOdom, odom_t oldOdom, pose_t pose) { System.out.println("delta left ticks: " + (newOdom.left - oldOdom.left)); System.out.println("delta right ticks: " + (newOdom.right - oldOdom.right)); double dleft = (newOdom.left - oldOdom.left) * tickMeters; double dright = (newOdom.right - oldOdom.right) * tickMeters; // phi deltaxyt[2] = MathUtil.mod2pi((dright - dleft) / baselineMeters); double dCenter = (dleft + dright) / 2; // delta x, delta y deltaxyt[0] += dCenter * Math.cos(deltaxyt[2]); deltaxyt[1] += dCenter * Math.sin(deltaxyt[2]); // our current theta double theta = LinAlg.quatToRollPitchYaw(pose.orientation)[2]; // calculate and store new xyt pose.pos[0] += (deltaxyt[0] * Math.cos(theta)) - (deltaxyt[1] * Math.sin(theta)); pose.pos[1] += (deltaxyt[0] * Math.sin(theta)) + (deltaxyt[1] * Math.cos(theta)); theta += deltaxyt[2]; // convert theta to quat and store pose.orientation = LinAlg.rollPitchYawToQuat(new double[] {0, 0, theta}); if (logger.isTraceEnabled()) { theta = MathUtil.mod2pi(theta); theta = Math.toDegrees(theta); logger.trace(String.format("odom: n(%d,%d) o(%d,%d) p(%5.2f,%5.2f,%5.1f)", newOdom.left, newOdom.right, oldOdom.left, oldOdom.right, pose.pos[0], pose.pos[1], theta)); } }
public void propagate(odom_t newOdom, odom_t oldOdom, pose_t pose) { //System.out.println("delta left ticks: " + (newOdom.left - oldOdom.left)); //System.out.println("delta right ticks: " + (newOdom.right - oldOdom.right)); double dleft = (newOdom.left - oldOdom.left) * tickMeters; double dright = (newOdom.right - oldOdom.right) * tickMeters; // phi deltaxyt[2] = MathUtil.mod2pi((dright - dleft) / baselineMeters); double dCenter = (dleft + dright) / 2; // delta x, delta y deltaxyt[0] = dCenter * Math.cos(deltaxyt[2]); deltaxyt[1] = dCenter * Math.sin(deltaxyt[2]); // our current theta double theta = LinAlg.quatToRollPitchYaw(pose.orientation)[2]; // calculate and store new xyt pose.pos[0] += (deltaxyt[0] * Math.cos(theta)) - (deltaxyt[1] * Math.sin(theta)); pose.pos[1] += (deltaxyt[0] * Math.sin(theta)) + (deltaxyt[1] * Math.cos(theta)); theta += deltaxyt[2]; // convert theta to quat and store pose.orientation = LinAlg.rollPitchYawToQuat(new double[] {0, 0, theta}); if (logger.isTraceEnabled()) { theta = MathUtil.mod2pi(theta); theta = Math.toDegrees(theta); logger.trace(String.format("odom: n(%d,%d) o(%d,%d) p(%5.2f,%5.2f,%5.1f)", newOdom.left, newOdom.right, oldOdom.left, oldOdom.right, pose.pos[0], pose.pos[1], theta)); } }
diff --git a/src/main/java/de/markiewb/netbeans/plugin/git/openinexternalviewer/OpenAction.java b/src/main/java/de/markiewb/netbeans/plugin/git/openinexternalviewer/OpenAction.java index c5b151c..1c0a80e 100644 --- a/src/main/java/de/markiewb/netbeans/plugin/git/openinexternalviewer/OpenAction.java +++ b/src/main/java/de/markiewb/netbeans/plugin/git/openinexternalviewer/OpenAction.java @@ -1,130 +1,137 @@ /** * Copyright 2013 markiewb * * 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 de.markiewb.netbeans.plugin.git.openinexternalviewer; import java.awt.event.ActionEvent; import java.net.MalformedURLException; import java.net.URL; import java.text.MessageFormat; import java.util.Collection; import javax.swing.AbstractAction; import javax.swing.Action; import static javax.swing.Action.NAME; import org.netbeans.api.project.Project; import org.netbeans.libs.git.GitBranch; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionReferences; import org.openide.awt.ActionRegistration; import org.openide.awt.DynamicMenuContent; import org.openide.awt.HtmlBrowser; import org.openide.filesystems.FileObject; import org.openide.util.ContextAwareAction; import org.openide.util.Exceptions; import org.openide.util.Lookup; @ActionID(category = "Git", id = "de.markiewb.netbeans.plugin.git.openinexternalviewer.OpenAction") @ActionRegistration(lazy = false, displayName = "openinexternalviewer.OpenAction") @ActionReferences({ @ActionReference(path = "Projects/Actions", position = 500) }) public final class OpenAction extends AbstractAction implements ContextAwareAction { @Override public void actionPerformed(ActionEvent e) { } @Override public Action createContextAwareInstance(Lookup lkp) { return new ContextAction(lkp); } static class ContextAction extends AbstractAction { private String url = null; private ContextAction(Lookup lkp) { putValue(NAME, null); putValue(DynamicMenuContent.HIDE_WHEN_DISABLED, true); init(lkp); } private RepoStrategy getStrategy(String remote) { Collection<? extends RepoStrategy> strategies = Lookup.getDefault().lookupAll(RepoStrategy.class); RepoStrategy usedStrategy = null; for (RepoStrategy strategy : strategies) { boolean supported = strategy.supports(remote); if (supported) { usedStrategy = strategy; break; } } return usedStrategy; } @Override public void actionPerformed(ActionEvent e) { if (null != url) { try { HtmlBrowser.URLDisplayer.getDefault().showURLExternal(new URL(url)); } catch (MalformedURLException ex) { Exceptions.printStackTrace(ex); } } } private void init(Lookup lkp) { setEnabled(false); //only support one project selected project Collection<? extends Project> lookupAll = lkp.lookupAll(Project.class); if (lookupAll != null && lookupAll.size() >= 2) { return; } Project project = lkp.lookup(Project.class); FileObject gitRepoDirectory = GitUtils.getGitRepoDirectory(project.getProjectDirectory()); if (gitRepoDirectory == null) { return; } GitBranch activeBranch = GitUtils.getActiveBranch(gitRepoDirectory); if (activeBranch == null) { return; } if (activeBranch.getTrackedBranch() == null) { //TODO support detached heads //TODO support tags return; } else { final String remoteBranchName = activeBranch.getTrackedBranch().getName(); //split "origin/master" to "origin" "master" - String[] split = remoteBranchName.split("/"); - if (2 == split.length) { - final String origin = split[0]; - final String remoteName = split[1]; + //split "orgin/feature/myfeature" to "origin" "feature/myfeature" + int indexOf = remoteBranchName.indexOf("/"); + if (indexOf<=0 || remoteBranchName.startsWith("/") || remoteBranchName.endsWith("/")){ + // no slash found OR + // slash is the first char? NOGO + //slash at the end? NOGO + return; + } + { + final String origin = remoteBranchName.substring(0, indexOf); + final String remoteName = remoteBranchName.substring(indexOf + 1); final String remote = GitUtils.getRemote(gitRepoDirectory, origin); final RepoStrategy strategy = getStrategy(remote); if (strategy != null) { putValue(NAME, MessageFormat.format("Open ''{0}'' at ''{1}''", remoteBranchName, strategy.getLabel())); url = strategy.getUrl(remote, remoteName, activeBranch.getId()); setEnabled(null != url); } } } } } }
true
true
private void init(Lookup lkp) { setEnabled(false); //only support one project selected project Collection<? extends Project> lookupAll = lkp.lookupAll(Project.class); if (lookupAll != null && lookupAll.size() >= 2) { return; } Project project = lkp.lookup(Project.class); FileObject gitRepoDirectory = GitUtils.getGitRepoDirectory(project.getProjectDirectory()); if (gitRepoDirectory == null) { return; } GitBranch activeBranch = GitUtils.getActiveBranch(gitRepoDirectory); if (activeBranch == null) { return; } if (activeBranch.getTrackedBranch() == null) { //TODO support detached heads //TODO support tags return; } else { final String remoteBranchName = activeBranch.getTrackedBranch().getName(); //split "origin/master" to "origin" "master" String[] split = remoteBranchName.split("/"); if (2 == split.length) { final String origin = split[0]; final String remoteName = split[1]; final String remote = GitUtils.getRemote(gitRepoDirectory, origin); final RepoStrategy strategy = getStrategy(remote); if (strategy != null) { putValue(NAME, MessageFormat.format("Open ''{0}'' at ''{1}''", remoteBranchName, strategy.getLabel())); url = strategy.getUrl(remote, remoteName, activeBranch.getId()); setEnabled(null != url); } } } }
private void init(Lookup lkp) { setEnabled(false); //only support one project selected project Collection<? extends Project> lookupAll = lkp.lookupAll(Project.class); if (lookupAll != null && lookupAll.size() >= 2) { return; } Project project = lkp.lookup(Project.class); FileObject gitRepoDirectory = GitUtils.getGitRepoDirectory(project.getProjectDirectory()); if (gitRepoDirectory == null) { return; } GitBranch activeBranch = GitUtils.getActiveBranch(gitRepoDirectory); if (activeBranch == null) { return; } if (activeBranch.getTrackedBranch() == null) { //TODO support detached heads //TODO support tags return; } else { final String remoteBranchName = activeBranch.getTrackedBranch().getName(); //split "origin/master" to "origin" "master" //split "orgin/feature/myfeature" to "origin" "feature/myfeature" int indexOf = remoteBranchName.indexOf("/"); if (indexOf<=0 || remoteBranchName.startsWith("/") || remoteBranchName.endsWith("/")){ // no slash found OR // slash is the first char? NOGO //slash at the end? NOGO return; } { final String origin = remoteBranchName.substring(0, indexOf); final String remoteName = remoteBranchName.substring(indexOf + 1); final String remote = GitUtils.getRemote(gitRepoDirectory, origin); final RepoStrategy strategy = getStrategy(remote); if (strategy != null) { putValue(NAME, MessageFormat.format("Open ''{0}'' at ''{1}''", remoteBranchName, strategy.getLabel())); url = strategy.getUrl(remote, remoteName, activeBranch.getId()); setEnabled(null != url); } } } }
diff --git a/src/org/eclipse/imp/pdb/facts/type/TypeDescriptorFactory.java b/src/org/eclipse/imp/pdb/facts/type/TypeDescriptorFactory.java index bd45a013..2d8a50b5 100644 --- a/src/org/eclipse/imp/pdb/facts/type/TypeDescriptorFactory.java +++ b/src/org/eclipse/imp/pdb/facts/type/TypeDescriptorFactory.java @@ -1,287 +1,287 @@ /******************************************************************************* * Copyright (c) 2008 CWI * 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: * Jurgen Vinju ([email protected]) *******************************************************************************/ package org.eclipse.imp.pdb.facts.type; import java.util.LinkedList; import java.util.List; import org.eclipse.imp.pdb.facts.IConstructor; import org.eclipse.imp.pdb.facts.IList; import org.eclipse.imp.pdb.facts.IListWriter; import org.eclipse.imp.pdb.facts.INode; import org.eclipse.imp.pdb.facts.IString; import org.eclipse.imp.pdb.facts.IValue; import org.eclipse.imp.pdb.facts.IValueFactory; import org.eclipse.imp.pdb.facts.exceptions.FactTypeDeclarationException; import org.eclipse.imp.pdb.facts.io.IValueReader; import org.eclipse.imp.pdb.facts.io.IValueWriter; import org.eclipse.imp.pdb.facts.visitors.NullVisitor; import org.eclipse.imp.pdb.facts.visitors.VisitorException; /** * This class converts types to representations of types as values and back. * It can be used for (de)serialization of types via {@link IValueReader} and {@link IValueWriter} * */ public class TypeDescriptorFactory { private TypeFactory tf = TypeFactory.getInstance(); private TypeStore ts = new TypeStore(); private Type typeSort = tf.abstractDataType(ts, "Type"); private Type boolType = tf.constructor(ts, typeSort, "bool"); private Type doubleType = tf.constructor(ts, typeSort, "double"); private Type integerType = tf.constructor(ts, typeSort, "int"); private Type nodeType = tf.constructor(ts, typeSort, "node"); private Type listType = tf.constructor(ts, typeSort, "list", typeSort, "element"); private Type mapType = tf.constructor(ts, typeSort, "map", typeSort, "key", typeSort, "value"); private Type aliasType = tf.constructor(ts, typeSort, "alias", tf.stringType(), "name", typeSort, "aliased"); private Type relationType = tf.constructor(ts, typeSort, "relation", tf.listType(typeSort), "fields"); private Type setType = tf.constructor(ts, typeSort, "set", typeSort, "element"); private Type sourceLocationType = tf.constructor(ts, typeSort, "sourceLocation"); private Type sourceRangeType = tf.constructor(ts, typeSort, "sourceRange"); private Type stringType = tf.constructor(ts, typeSort, "string"); private Type constructorType = tf.constructor(ts, typeSort, "constructor", typeSort, "abstract-data-type", tf.stringType(), "name", tf.listType(typeSort), "children"); private Type abstractDataType = tf.constructor(ts, typeSort, "abstract-data-type", tf.stringType(), "name"); private Type parameterType = tf.constructor(ts, typeSort, "parameter", tf.stringType(), "name", typeSort, "bound"); private Type tupleType = tf.constructor(ts, typeSort, "tuple", tf.listType(typeSort), "fields"); private Type valueType = tf.constructor(ts, typeSort, "value"); private Type voidType = tf.constructor(ts, typeSort, "void"); private TypeStore store; private static class InstanceHolder { public static TypeDescriptorFactory sInstance = new TypeDescriptorFactory(); } private TypeDescriptorFactory() {} public static TypeDescriptorFactory getInstance() { return InstanceHolder.sInstance; } public TypeStore getStore() { return ts; } /** * Create a representation of a type for use in (de)serialization or other * computations on types. * * @param factory the factory to use to construct the values * @param type the type to convert to a value * @return a value that represents this type and can be convert back to * the original type via {@link TypeDescriptorFactory#fromTypeDescriptor(INode)} */ public IValue toTypeDescriptor(IValueFactory factory, Type type) { return type.accept(new ToTypeVisitor(factory)); } /** * Construct a type that is represented by this value. Will only work for values * that have been constructed using {@link TypeDescriptorFactory#toTypeDescriptor(IValueFactory, Type)}, * or something that exactly mimicked it. * * @param store to store found declarations in * @param descriptor a value that represents a type * @return a type that was represented by the descriptor * @throws FactTypeDeclarationException if the descriptor is not a valid type descriptor */ public Type fromTypeDescriptor(TypeStore store, IValue descriptor) throws FactTypeDeclarationException { try { this.store = store; return descriptor.accept(new FromTypeVisitor()); } catch (VisitorException e) { // this does not happen since nobody throws a VisitorException return null; } } private class FromTypeVisitor extends NullVisitor<Type> { @Override public Type visitConstructor(IConstructor o) throws VisitorException { Type node = o.getConstructorType(); if (node == boolType) { return tf.boolType(); } else if (node == doubleType) { return tf.doubleType(); } else if (node == integerType) { return tf.integerType(); } else if (node == nodeType) { return tf.nodeType(); } else if (node == listType) { return tf.listType(o.get("element").accept(this)); } else if (node == mapType) { return tf.mapType(o.get("key").accept(this), o.get("value").accept(this)); } else if (node == aliasType) { return tf.aliasType(store, ((IString) o.get("name")).getValue(), o.get("aliased").accept(this)); } else if (node == relationType) { IList fieldValues = (IList) o.get("fields"); List<Type> fieldTypes = new LinkedList<Type>(); for (IValue field : fieldValues) { fieldTypes.add(field.accept(this)); } - return tf.relTypeFromTuple(tf.tupleType(fieldTypes)); + return tf.relTypeFromTuple(tf.tupleType(fieldTypes.toArray())); } else if (node == setType) { return tf.setType(o.get("element").accept(this)); } else if (node == sourceLocationType) { return tf.sourceLocationType(); } else if (node == sourceRangeType) { return tf.sourceRangeType(); } else if (node == stringType) { return tf.stringType(); } else if (node == constructorType) { AbstractDataType sort = (AbstractDataType) o.get("abstract-data-type").accept(this); String name = ((IString) o.get("name")).getValue(); IList childrenValues = (IList) o.get("children"); List<Type> childrenTypes = new LinkedList<Type>(); for (IValue child : childrenValues) { childrenTypes.add(child.accept(this)); } - return tf.constructor(store, sort, name, tf.tupleType(childrenTypes)); + return tf.constructor(store, sort, name, tf.tupleType(childrenTypes.toArray())); } else if (node == abstractDataType) { return tf.abstractDataType(store, ((IString) o.get("name")).getValue()); } else if (node == parameterType) { return tf.parameterType(((IString) o.get("name")).getValue(), o.get("bound").accept(this)); } else if (node == tupleType) { IList fieldValues = (IList) o.get("fields"); List<Type> fieldTypes = new LinkedList<Type>(); for (IValue field : fieldValues) { fieldTypes.add(field.accept(this)); } return tf.tupleType(fieldTypes); } else { return tf.valueType(); } } } private class ToTypeVisitor implements ITypeVisitor<INode> { private IValueFactory vf; public ToTypeVisitor(IValueFactory factory) { this.vf = factory; } public INode visitDouble(Type type) { return vf.constructor(doubleType); } public INode visitInteger(Type type) { return vf.constructor(integerType); } public INode visitList(Type type) { return vf.constructor(listType, type.getElementType().accept(this)); } public INode visitMap(Type type) { return vf.constructor(mapType, type.getKeyType().accept(this), type.getValueType().accept(this)); } public INode visitAlias(Type type) { return vf.constructor(aliasType, vf.string(type.getName()), type.getAliased().accept(this)); } public INode visitRelationType(Type type) { IListWriter w = vf.listWriter(typeSort); for (Type field : type.getFieldTypes()) { w.append(field.accept(this)); } return vf.constructor(relationType, w.done()); } public INode visitSet(Type type) { return vf.constructor(setType, type.getElementType().accept(this)); } public INode visitSourceLocation(Type type) { return vf.constructor(sourceLocationType); } public INode visitSourceRange(Type type) { return vf.constructor(sourceRangeType); } public INode visitString(Type type) { return vf.constructor(stringType); } public INode visitConstructor(Type type) { IListWriter w = vf.listWriter(typeSort); for (Type field : type.getFieldTypes()) { w.append(field.accept(this)); } return vf.constructor(constructorType, type.getAbstractDataType().accept(this), vf.string(type.getName()), w.done()); } public INode visitAbstractData(Type type) { return vf.constructor(abstractDataType, vf.string(type.getName())); } public INode visitTuple(Type type) { IListWriter w = vf.listWriter(typeSort); for (Type field : type) { w.append(field.accept(this)); } return vf.constructor(tupleType, w.done()); } public INode visitValue(Type type) { return vf.constructor(valueType); } public INode visitVoid(Type type) { return vf.constructor(voidType); } public INode visitNode(Type type) { return vf.constructor(nodeType); } public INode visitBool(Type type) { return vf.constructor(boolType); } public INode visitParameter(Type type) { return vf.constructor(parameterType, vf.string(type.getName()), type.getBound().accept(this)); } } }
false
true
public Type visitConstructor(IConstructor o) throws VisitorException { Type node = o.getConstructorType(); if (node == boolType) { return tf.boolType(); } else if (node == doubleType) { return tf.doubleType(); } else if (node == integerType) { return tf.integerType(); } else if (node == nodeType) { return tf.nodeType(); } else if (node == listType) { return tf.listType(o.get("element").accept(this)); } else if (node == mapType) { return tf.mapType(o.get("key").accept(this), o.get("value").accept(this)); } else if (node == aliasType) { return tf.aliasType(store, ((IString) o.get("name")).getValue(), o.get("aliased").accept(this)); } else if (node == relationType) { IList fieldValues = (IList) o.get("fields"); List<Type> fieldTypes = new LinkedList<Type>(); for (IValue field : fieldValues) { fieldTypes.add(field.accept(this)); } return tf.relTypeFromTuple(tf.tupleType(fieldTypes)); } else if (node == setType) { return tf.setType(o.get("element").accept(this)); } else if (node == sourceLocationType) { return tf.sourceLocationType(); } else if (node == sourceRangeType) { return tf.sourceRangeType(); } else if (node == stringType) { return tf.stringType(); } else if (node == constructorType) { AbstractDataType sort = (AbstractDataType) o.get("abstract-data-type").accept(this); String name = ((IString) o.get("name")).getValue(); IList childrenValues = (IList) o.get("children"); List<Type> childrenTypes = new LinkedList<Type>(); for (IValue child : childrenValues) { childrenTypes.add(child.accept(this)); } return tf.constructor(store, sort, name, tf.tupleType(childrenTypes)); } else if (node == abstractDataType) { return tf.abstractDataType(store, ((IString) o.get("name")).getValue()); } else if (node == parameterType) { return tf.parameterType(((IString) o.get("name")).getValue(), o.get("bound").accept(this)); } else if (node == tupleType) { IList fieldValues = (IList) o.get("fields"); List<Type> fieldTypes = new LinkedList<Type>(); for (IValue field : fieldValues) { fieldTypes.add(field.accept(this)); } return tf.tupleType(fieldTypes); } else { return tf.valueType(); } }
public Type visitConstructor(IConstructor o) throws VisitorException { Type node = o.getConstructorType(); if (node == boolType) { return tf.boolType(); } else if (node == doubleType) { return tf.doubleType(); } else if (node == integerType) { return tf.integerType(); } else if (node == nodeType) { return tf.nodeType(); } else if (node == listType) { return tf.listType(o.get("element").accept(this)); } else if (node == mapType) { return tf.mapType(o.get("key").accept(this), o.get("value").accept(this)); } else if (node == aliasType) { return tf.aliasType(store, ((IString) o.get("name")).getValue(), o.get("aliased").accept(this)); } else if (node == relationType) { IList fieldValues = (IList) o.get("fields"); List<Type> fieldTypes = new LinkedList<Type>(); for (IValue field : fieldValues) { fieldTypes.add(field.accept(this)); } return tf.relTypeFromTuple(tf.tupleType(fieldTypes.toArray())); } else if (node == setType) { return tf.setType(o.get("element").accept(this)); } else if (node == sourceLocationType) { return tf.sourceLocationType(); } else if (node == sourceRangeType) { return tf.sourceRangeType(); } else if (node == stringType) { return tf.stringType(); } else if (node == constructorType) { AbstractDataType sort = (AbstractDataType) o.get("abstract-data-type").accept(this); String name = ((IString) o.get("name")).getValue(); IList childrenValues = (IList) o.get("children"); List<Type> childrenTypes = new LinkedList<Type>(); for (IValue child : childrenValues) { childrenTypes.add(child.accept(this)); } return tf.constructor(store, sort, name, tf.tupleType(childrenTypes.toArray())); } else if (node == abstractDataType) { return tf.abstractDataType(store, ((IString) o.get("name")).getValue()); } else if (node == parameterType) { return tf.parameterType(((IString) o.get("name")).getValue(), o.get("bound").accept(this)); } else if (node == tupleType) { IList fieldValues = (IList) o.get("fields"); List<Type> fieldTypes = new LinkedList<Type>(); for (IValue field : fieldValues) { fieldTypes.add(field.accept(this)); } return tf.tupleType(fieldTypes); } else { return tf.valueType(); } }
diff --git a/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/RefreshLocalVisitor.java b/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/RefreshLocalVisitor.java index f85cfad9c..9b78c9a27 100644 --- a/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/RefreshLocalVisitor.java +++ b/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/RefreshLocalVisitor.java @@ -1,301 +1,301 @@ /******************************************************************************* * 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.core.internal.localstore; import org.eclipse.core.resources.*; import org.eclipse.core.runtime.*; import org.eclipse.core.internal.resources.*; import org.eclipse.core.internal.utils.Policy; // /** * Visits a unified tree, and synchronizes the file system with the * resource tree. After the visit is complete, the file system will * be synchronized with the workspace tree with respect to * resource existence, gender, and timestamp. */ public class RefreshLocalVisitor implements IUnifiedTreeVisitor, ILocalStoreConstants { protected IProgressMonitor monitor; protected Workspace workspace; protected boolean resourceChanged; protected MultiStatus errors; /* * Fields for progress monitoring algorithm. * Initially, give progress for every 4 resources, double * this value at halfway point, then reset halfway point * to be half of remaining work. (this gives an infinite * series that converges at total work after an infinite * number of resources). */ public static final int TOTAL_WORK = 250; private int halfWay = TOTAL_WORK / 2; private int currentIncrement = 4; private int nextProgress = currentIncrement; private int worked = 0; /** control constants */ protected static final int RL_UNKNOWN = 0; protected static final int RL_IN_SYNC = 1; protected static final int RL_NOT_IN_SYNC = 2; public RefreshLocalVisitor(IProgressMonitor monitor) { this.monitor = monitor; workspace = (Workspace) ResourcesPlugin.getWorkspace(); resourceChanged = false; String msg = Policy.bind("resources.errorMultiRefresh"); //$NON-NLS-1$ errors = new MultiStatus(ResourcesPlugin.PI_RESOURCES, IResourceStatus.FAILED_READ_LOCAL, msg, null); } /** * This method has the same implementation as resourceChanged but as they are different * cases, we prefer to use different methods. */ protected void contentAdded(UnifiedTreeNode node, Resource target) throws CoreException { resourceChanged(node, target); } protected void createResource(UnifiedTreeNode node, Resource target) throws CoreException { ResourceInfo info = target.getResourceInfo(false, false); int flags = target.getFlags(info); if (target.exists(flags, false)) return; /* make sure target's parent exists */ if (node.getLevel() == 0) { IContainer parent = target.getParent(); if (parent.getType() == IResource.FOLDER) ((Folder) target.getParent()).ensureExists(monitor); } /* Use the basic file creation protocol since we don't want to create any content on disk. */ info = workspace.createResource(target, false); target.getLocalManager().updateLocalSync(info, node.getLastModified()); } protected void deleteResource(UnifiedTreeNode node, Resource target) throws CoreException { ResourceInfo info = target.getResourceInfo(false, false); int flags = target.getFlags(info); //don't delete linked resources if (ResourceInfo.isSet(flags, ICoreConstants.M_LINK)) return; if (target.exists(flags, false)) target.deleteResource(true, null); node.setExistsWorkspace(false); } protected void fileToFolder(UnifiedTreeNode node, Resource target) throws CoreException { ResourceInfo info = target.getResourceInfo(false, false); int flags = target.getFlags(info); if (target.exists(flags, true)) { target = (Folder) ((File) target).changeToFolder(); } else { if (!target.exists(flags, false)) { target = (Resource) workspace.getRoot().getFolder(target.getFullPath()); // Use the basic file creation protocol since we don't want to create any content on disk. workspace.createResource(target, false); } } node.setResource(target); info = target.getResourceInfo(false, true); target.getLocalManager().updateLocalSync(info, node.getLastModified()); } protected void folderToFile(UnifiedTreeNode node, Resource target) throws CoreException { ResourceInfo info = target.getResourceInfo(false, false); int flags = target.getFlags(info); if (target.exists(flags, true)) target = (File) ((Folder) target).changeToFile(); else { if (!target.exists(flags, false)) { target = (Resource) workspace.getRoot().getFile(target.getFullPath()); // Use the basic file creation protocol since we don't want to // create any content on disk. workspace.createResource(target, false); } } node.setResource(target); info = target.getResourceInfo(false, true); target.getLocalManager().updateLocalSync(info, node.getLastModified()); } /** * Returns the status of the nodes visited so far. This will be a multi-status * that describes all problems that have occurred, or an OK status if everything * went smoothly. */ public IStatus getErrorStatus() { return errors; } /** * Refreshes the parent of a resource currently being synchronized. */ protected void refresh(Container parent) throws CoreException { parent.getLocalManager().refresh(parent, IResource.DEPTH_ZERO, false, null); } protected void resourceChanged(UnifiedTreeNode node, Resource target) throws CoreException { ResourceInfo info = target.getResourceInfo(false, true); if (info == null) return; target.getLocalManager().updateLocalSync(info, node.getLastModified()); info.incrementContentId(); workspace.updateModificationStamp(info); } public boolean resourcesChanged() { return resourceChanged; } /** * deletion or creation -- Returns: * - RL_IN_SYNC - the resource is in-sync with the file system * - RL_NOT_IN_SYNC - the resource is not in-sync with file system * - RL_UNKNOWN - couldn't determine the sync status for this resource */ protected int synchronizeExistence(UnifiedTreeNode node, Resource target, int level) throws CoreException { boolean existsInWorkspace = node.existsInWorkspace(); if (!existsInWorkspace) { if (!CoreFileSystemLibrary.isCaseSensitive() && level == 0) { // do we have any alphabetic variants on the workspace? IResource variant = target.findExistingResourceVariant(target.getFullPath()); if (variant != null) return RL_UNKNOWN; } // do we have a gender variant in the workspace? IResource genderVariant = workspace.getRoot().findMember(target.getFullPath()); if (genderVariant != null) return RL_UNKNOWN; } if (existsInWorkspace) { if (!node.existsInFileSystem()) { //non-local files are always in sync if (target.isLocal(IResource.DEPTH_ZERO)) { deleteResource(node, target); resourceChanged = true; return RL_NOT_IN_SYNC; } else return RL_IN_SYNC; } } else { if (node.existsInFileSystem()) { if (!CoreFileSystemLibrary.isCaseSensitive()) { Container parent = (Container) target.getParent(); if (!parent.exists()) { refresh(parent); if (!parent.exists()) return RL_NOT_IN_SYNC; } if (!target.getName().equals(node.getLocalName())) return RL_IN_SYNC; } createResource(node, target); resourceChanged = true; return RL_NOT_IN_SYNC; } } return RL_UNKNOWN; } /** * gender change -- Returns true if gender was in sync. */ protected boolean synchronizeGender(UnifiedTreeNode node, Resource target) throws CoreException { if (!node.existsInWorkspace()) { //may be an existing resource in the workspace of different gender IResource genderVariant = workspace.getRoot().findMember(target.getFullPath()); if (genderVariant != null) target = (Resource)genderVariant; } if (target.getType() == IResource.FILE) { if (!node.isFile()) { fileToFolder(node, target); resourceChanged = true; return false; } } else { if (!node.isFolder()) { folderToFile(node, target); resourceChanged = true; return false; } } return true; } /** * lastModified */ protected void synchronizeLastModified(UnifiedTreeNode node, Resource target) throws CoreException { if (target.isLocal(IResource.DEPTH_ZERO)) resourceChanged(node, target); else contentAdded(node, target); resourceChanged = true; } public boolean visit(UnifiedTreeNode node) throws CoreException { Policy.checkCanceled(monitor); try { Resource target = (Resource) node.getResource(); int targetType = target.getType(); if (targetType == IResource.PROJECT) return true; if (node.existsInWorkspace() && node.existsInFileSystem()) { /* for folders we only care about updating local status */ if (targetType == IResource.FOLDER && node.isFolder()) { // if not local, mark as local if (!target.isLocal(IResource.DEPTH_ZERO)) { ResourceInfo info = target.getResourceInfo(false, true); if (info == null) return true; target.getLocalManager().updateLocalSync(info, node.getLastModified()); } return true; } /* compare file last modified */ if (targetType == IResource.FILE && node.isFile()) { - long lastModifed = target.getResourceInfo(false, false).getLocalSyncInfo(); - if (lastModifed == node.getLastModified()) + ResourceInfo info = target.getResourceInfo(false, false); + if (info != null && info.getLocalSyncInfo() == node.getLastModified()) return true; } } else { if (node.existsInFileSystem() && !Path.EMPTY.isValidSegment(node.getLocalName())) { String message = Policy.bind("resources.invalidResourceName", node.getLocalName()); //$NON-NLS-1$ errors.merge(new ResourceStatus(IResourceStatus.INVALID_RESOURCE_NAME, message)); return false; } int state = synchronizeExistence(node, target, node.getLevel()); if (state == RL_IN_SYNC || state == RL_NOT_IN_SYNC) { if (targetType == IResource.FILE) { try { ((File)target).updateProjectDescription(); } catch (CoreException e) { errors.merge(e.getStatus()); } } return true; } } if (synchronizeGender(node, target)) synchronizeLastModified(node, target); if (targetType == IResource.FILE) { try { ((File)target).updateProjectDescription(); } catch (CoreException e) { errors.merge(e.getStatus()); } } return true; } finally { if (--nextProgress <= 0) { //we have exhausted the current increment, so report progress monitor.worked(1); worked++; if (worked >= halfWay) { //we have passed the current halfway point, so double the //increment and reset the halfway point. currentIncrement *= 2; halfWay += (TOTAL_WORK - halfWay) / 2; } //reset the progress counter to another full increment nextProgress = currentIncrement; } } } }
true
true
public boolean visit(UnifiedTreeNode node) throws CoreException { Policy.checkCanceled(monitor); try { Resource target = (Resource) node.getResource(); int targetType = target.getType(); if (targetType == IResource.PROJECT) return true; if (node.existsInWorkspace() && node.existsInFileSystem()) { /* for folders we only care about updating local status */ if (targetType == IResource.FOLDER && node.isFolder()) { // if not local, mark as local if (!target.isLocal(IResource.DEPTH_ZERO)) { ResourceInfo info = target.getResourceInfo(false, true); if (info == null) return true; target.getLocalManager().updateLocalSync(info, node.getLastModified()); } return true; } /* compare file last modified */ if (targetType == IResource.FILE && node.isFile()) { long lastModifed = target.getResourceInfo(false, false).getLocalSyncInfo(); if (lastModifed == node.getLastModified()) return true; } } else { if (node.existsInFileSystem() && !Path.EMPTY.isValidSegment(node.getLocalName())) { String message = Policy.bind("resources.invalidResourceName", node.getLocalName()); //$NON-NLS-1$ errors.merge(new ResourceStatus(IResourceStatus.INVALID_RESOURCE_NAME, message)); return false; } int state = synchronizeExistence(node, target, node.getLevel()); if (state == RL_IN_SYNC || state == RL_NOT_IN_SYNC) { if (targetType == IResource.FILE) { try { ((File)target).updateProjectDescription(); } catch (CoreException e) { errors.merge(e.getStatus()); } } return true; } } if (synchronizeGender(node, target)) synchronizeLastModified(node, target); if (targetType == IResource.FILE) { try { ((File)target).updateProjectDescription(); } catch (CoreException e) { errors.merge(e.getStatus()); } } return true; } finally { if (--nextProgress <= 0) { //we have exhausted the current increment, so report progress monitor.worked(1); worked++; if (worked >= halfWay) { //we have passed the current halfway point, so double the //increment and reset the halfway point. currentIncrement *= 2; halfWay += (TOTAL_WORK - halfWay) / 2; } //reset the progress counter to another full increment nextProgress = currentIncrement; } } }
public boolean visit(UnifiedTreeNode node) throws CoreException { Policy.checkCanceled(monitor); try { Resource target = (Resource) node.getResource(); int targetType = target.getType(); if (targetType == IResource.PROJECT) return true; if (node.existsInWorkspace() && node.existsInFileSystem()) { /* for folders we only care about updating local status */ if (targetType == IResource.FOLDER && node.isFolder()) { // if not local, mark as local if (!target.isLocal(IResource.DEPTH_ZERO)) { ResourceInfo info = target.getResourceInfo(false, true); if (info == null) return true; target.getLocalManager().updateLocalSync(info, node.getLastModified()); } return true; } /* compare file last modified */ if (targetType == IResource.FILE && node.isFile()) { ResourceInfo info = target.getResourceInfo(false, false); if (info != null && info.getLocalSyncInfo() == node.getLastModified()) return true; } } else { if (node.existsInFileSystem() && !Path.EMPTY.isValidSegment(node.getLocalName())) { String message = Policy.bind("resources.invalidResourceName", node.getLocalName()); //$NON-NLS-1$ errors.merge(new ResourceStatus(IResourceStatus.INVALID_RESOURCE_NAME, message)); return false; } int state = synchronizeExistence(node, target, node.getLevel()); if (state == RL_IN_SYNC || state == RL_NOT_IN_SYNC) { if (targetType == IResource.FILE) { try { ((File)target).updateProjectDescription(); } catch (CoreException e) { errors.merge(e.getStatus()); } } return true; } } if (synchronizeGender(node, target)) synchronizeLastModified(node, target); if (targetType == IResource.FILE) { try { ((File)target).updateProjectDescription(); } catch (CoreException e) { errors.merge(e.getStatus()); } } return true; } finally { if (--nextProgress <= 0) { //we have exhausted the current increment, so report progress monitor.worked(1); worked++; if (worked >= halfWay) { //we have passed the current halfway point, so double the //increment and reset the halfway point. currentIncrement *= 2; halfWay += (TOTAL_WORK - halfWay) / 2; } //reset the progress counter to another full increment nextProgress = currentIncrement; } } }
diff --git a/src/annahack/nethackparser/NetHackParser.java b/src/annahack/nethackparser/NetHackParser.java index e5cfca0..9bab334 100644 --- a/src/annahack/nethackparser/NetHackParser.java +++ b/src/annahack/nethackparser/NetHackParser.java @@ -1,255 +1,255 @@ package annahack.nethackparser; import java.util.Queue; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; import annahack.nethackinformation.nethackplayer.PlayerWriter; import annahack.nethackinformation.nethackplayer.Player; import annahack.telnetconnection.TelnetInterface; public class NetHackParser { private TelnetInterface com; private Queue<String> messageBuf; private Queue<String> itemsBuf; private PlayerWriter pw; private int score; private int turn; private int dlvl; public NetHackParser(TelnetInterface com) { this.com=com; messageBuf=new java.util.LinkedList<String>(); pw=new PlayerWriter(); //TODO: Implement ability to choose race, gender, etc. } /** * @return * 0 if there were no messages, * 1 if there were messages * 2 if there were messages and space needs to be sent (--More--) * 3 if the last message is a prompt */ public byte checkMessages() throws IOException { String line; line=new String(com.peekLine(0)); if (line.equals(" ")) { //Nothing return 0; }else{ //Something int search=line.indexOf("--More--"); if (search!=-1) { //Messages and --More-- String[] msgs=line.substring(0, search).split(" "); for (int i=0; i<msgs.length; i++) { messageBuf.add(msgs[i].trim()); } return 2; }else{ //No --More-- on first line if (thingsThatAreHere(0)) return 2; if (line.matches("There is an? ([a-z ]+) here.")) { messageBuf.add(line); if (thingsThatAreHere(2)) return 2; System.err.println("Unable to figure out line:\n"+line); throw new UnparseableBullshitException(line); }else{ StringBuffer messageBlob=new StringBuffer(line); for (int i=1; i<23; i++) messageBlob.append(new String(com.peekLine(0))); return 0; } } } } /** * Checks for a "things that are here" starting on the given line. * Line should be 0 or 2. * Returns true if things are here. **/ private boolean thingsThatAreHere(int linenum) throws IOException { String line=new String(com.peekLine(linenum)); int search=line.indexOf("Things that are here"); if (search==-1) return false; //Clearly, things are not here //Item list for (int i=1; (line=new String(com.peekLine(i), search, 80-search).trim()). indexOf("--More--")==-1; i++) { itemsBuf.add(line); } return true; } private static final Pattern r_hp = Pattern.compile("HP:([\\d]+)\\(([\\d]+)\\)"); private static final Pattern r_mp = Pattern.compile("Pw:([\\d]+)\\(([\\d]+)\\)"); private static final Pattern r_dlvl = Pattern.compile("Dlvl:([\\d]+)"); private static final Pattern r_gold = Pattern.compile("\\$:([\\d]+)"); private static final Pattern r_ac = Pattern.compile("AC:([\\d]+)"); private static final Pattern r_turn = Pattern.compile("T:([\\d]+)"); private static final Pattern r_xp = Pattern.compile("Xp:([\\d]+)/([\\d]+)"); private static final Pattern r_st = Pattern.compile("St:([\\d]+)"); private static final Pattern r_dx = Pattern.compile("Dx:([\\d]+)"); private static final Pattern r_co = Pattern.compile("Co:([\\d]+)"); private static final Pattern r_in = Pattern.compile("In:([\\d]+)"); private static final Pattern r_wi = Pattern.compile("Wi:([\\d]+)"); private static final Pattern r_ch = Pattern.compile("Ch:([\\d]+)"); private static final Pattern r_align = Pattern.compile("(Lawful|Chaotic|Neutral)"); private static final Pattern r_score = Pattern.compile("S:([\\d]+)"); /** * Parses the status line, updates if all is found * @returns false if all of objects on status line are not found */ private boolean parseStatusLine() throws IOException { String topline = new String(com.peekLine(22)); String bottomline = new String(com.peekLine(23)); Matcher m_st=r_st.matcher(topline); if(!m_st.find()) return false; Matcher m_dx=r_dx.matcher(topline); if(!m_dx.find()) return false; Matcher m_co=r_co.matcher(topline); if(!m_co.find()) return false; Matcher m_in=r_in.matcher(topline); if(!m_in.find()) return false; Matcher m_wi=r_wi.matcher(topline); if(!m_wi.find()) return false; Matcher m_ch=r_ch.matcher(topline); if(!m_ch.find()) return false; Matcher m_align=r_align.matcher(topline); if(!m_align.find()) return false; Matcher m_score=r_score.matcher(topline); if(!m_score.find()) return false; Matcher m_hp=r_hp.matcher(bottomline); if(!m_hp.find()) return false; Matcher m_mp=r_mp.matcher(bottomline); if(!m_mp.find()) return false; Matcher m_gold=r_gold.matcher(bottomline); if(!m_gold.find()) return false; Matcher m_xp=r_xp.matcher(bottomline); if(!m_xp.find()) return false; Matcher m_dlvl=r_dlvl.matcher(bottomline); if(!m_dlvl.find()) return false; Matcher m_ac=r_ac.matcher(bottomline); if(!m_ac.find()) return false; Matcher m_turn=r_turn.matcher(bottomline); if(!m_turn.find()) return false; try { //Begin top line pw.setSt(Integer.parseInt(m_st.group(1))); pw.setCo(Integer.parseInt(m_co.group(1))); pw.setDx(Integer.parseInt(m_dx.group(1))); pw.setIn(Integer.parseInt(m_in.group(1))); pw.setWi(Integer.parseInt(m_wi.group(1))); pw.setCh(Integer.parseInt(m_ch.group(1))); pw.setAlignment(m_align.group()); score=Integer.parseInt(m_score.group(1)); //End top line //Begin bottom line //TODO: Add gold to inventory dlvl= Integer.parseInt(m_dlvl.group(1)); turn= Integer.parseInt(m_turn.group(1)); pw.setHp(Integer.parseInt(m_hp.group(1))); pw.setMaxHp(Integer.parseInt(m_hp.group(2))); pw.setMp(Integer.parseInt(m_mp.group(1))); pw.setMaxMp(Integer.parseInt(m_mp.group(2))); - pw.setAC(Integer.parseInt(m_mp.group(1))); + pw.setAC(Integer.parseInt(m_ac.group(1))); pw.setXp(Integer.parseInt(m_xp.group(1))); pw.setLevel(Integer.parseInt(m_xp.group(2))); //End bottom line } catch (NumberFormatException e) { return false; } return true; } public Player getPlayer() { return pw.getPlayer(); } public int getScore() { return score; } public int getDLvl() { return dlvl; } public int getTurn() { return turn; } public boolean debug_parseStatusLine() { try{return parseStatusLine();}catch(Exception e){return false;} } }
true
true
private boolean parseStatusLine() throws IOException { String topline = new String(com.peekLine(22)); String bottomline = new String(com.peekLine(23)); Matcher m_st=r_st.matcher(topline); if(!m_st.find()) return false; Matcher m_dx=r_dx.matcher(topline); if(!m_dx.find()) return false; Matcher m_co=r_co.matcher(topline); if(!m_co.find()) return false; Matcher m_in=r_in.matcher(topline); if(!m_in.find()) return false; Matcher m_wi=r_wi.matcher(topline); if(!m_wi.find()) return false; Matcher m_ch=r_ch.matcher(topline); if(!m_ch.find()) return false; Matcher m_align=r_align.matcher(topline); if(!m_align.find()) return false; Matcher m_score=r_score.matcher(topline); if(!m_score.find()) return false; Matcher m_hp=r_hp.matcher(bottomline); if(!m_hp.find()) return false; Matcher m_mp=r_mp.matcher(bottomline); if(!m_mp.find()) return false; Matcher m_gold=r_gold.matcher(bottomline); if(!m_gold.find()) return false; Matcher m_xp=r_xp.matcher(bottomline); if(!m_xp.find()) return false; Matcher m_dlvl=r_dlvl.matcher(bottomline); if(!m_dlvl.find()) return false; Matcher m_ac=r_ac.matcher(bottomline); if(!m_ac.find()) return false; Matcher m_turn=r_turn.matcher(bottomline); if(!m_turn.find()) return false; try { //Begin top line pw.setSt(Integer.parseInt(m_st.group(1))); pw.setCo(Integer.parseInt(m_co.group(1))); pw.setDx(Integer.parseInt(m_dx.group(1))); pw.setIn(Integer.parseInt(m_in.group(1))); pw.setWi(Integer.parseInt(m_wi.group(1))); pw.setCh(Integer.parseInt(m_ch.group(1))); pw.setAlignment(m_align.group()); score=Integer.parseInt(m_score.group(1)); //End top line //Begin bottom line //TODO: Add gold to inventory dlvl= Integer.parseInt(m_dlvl.group(1)); turn= Integer.parseInt(m_turn.group(1)); pw.setHp(Integer.parseInt(m_hp.group(1))); pw.setMaxHp(Integer.parseInt(m_hp.group(2))); pw.setMp(Integer.parseInt(m_mp.group(1))); pw.setMaxMp(Integer.parseInt(m_mp.group(2))); pw.setAC(Integer.parseInt(m_mp.group(1))); pw.setXp(Integer.parseInt(m_xp.group(1))); pw.setLevel(Integer.parseInt(m_xp.group(2))); //End bottom line } catch (NumberFormatException e) { return false; } return true; }
private boolean parseStatusLine() throws IOException { String topline = new String(com.peekLine(22)); String bottomline = new String(com.peekLine(23)); Matcher m_st=r_st.matcher(topline); if(!m_st.find()) return false; Matcher m_dx=r_dx.matcher(topline); if(!m_dx.find()) return false; Matcher m_co=r_co.matcher(topline); if(!m_co.find()) return false; Matcher m_in=r_in.matcher(topline); if(!m_in.find()) return false; Matcher m_wi=r_wi.matcher(topline); if(!m_wi.find()) return false; Matcher m_ch=r_ch.matcher(topline); if(!m_ch.find()) return false; Matcher m_align=r_align.matcher(topline); if(!m_align.find()) return false; Matcher m_score=r_score.matcher(topline); if(!m_score.find()) return false; Matcher m_hp=r_hp.matcher(bottomline); if(!m_hp.find()) return false; Matcher m_mp=r_mp.matcher(bottomline); if(!m_mp.find()) return false; Matcher m_gold=r_gold.matcher(bottomline); if(!m_gold.find()) return false; Matcher m_xp=r_xp.matcher(bottomline); if(!m_xp.find()) return false; Matcher m_dlvl=r_dlvl.matcher(bottomline); if(!m_dlvl.find()) return false; Matcher m_ac=r_ac.matcher(bottomline); if(!m_ac.find()) return false; Matcher m_turn=r_turn.matcher(bottomline); if(!m_turn.find()) return false; try { //Begin top line pw.setSt(Integer.parseInt(m_st.group(1))); pw.setCo(Integer.parseInt(m_co.group(1))); pw.setDx(Integer.parseInt(m_dx.group(1))); pw.setIn(Integer.parseInt(m_in.group(1))); pw.setWi(Integer.parseInt(m_wi.group(1))); pw.setCh(Integer.parseInt(m_ch.group(1))); pw.setAlignment(m_align.group()); score=Integer.parseInt(m_score.group(1)); //End top line //Begin bottom line //TODO: Add gold to inventory dlvl= Integer.parseInt(m_dlvl.group(1)); turn= Integer.parseInt(m_turn.group(1)); pw.setHp(Integer.parseInt(m_hp.group(1))); pw.setMaxHp(Integer.parseInt(m_hp.group(2))); pw.setMp(Integer.parseInt(m_mp.group(1))); pw.setMaxMp(Integer.parseInt(m_mp.group(2))); pw.setAC(Integer.parseInt(m_ac.group(1))); pw.setXp(Integer.parseInt(m_xp.group(1))); pw.setLevel(Integer.parseInt(m_xp.group(2))); //End bottom line } catch (NumberFormatException e) { return false; } return true; }
diff --git a/src/annahack/telnetconnection/ApacheBasedTelnetInterface.java b/src/annahack/telnetconnection/ApacheBasedTelnetInterface.java index ef7364c..a61ecdf 100644 --- a/src/annahack/telnetconnection/ApacheBasedTelnetInterface.java +++ b/src/annahack/telnetconnection/ApacheBasedTelnetInterface.java @@ -1,101 +1,101 @@ package annahack.telnetconnection; import org.apache.commons.net.telnet.TelnetClient; import java.net.SocketException; import org.apache.commons.net.telnet.InvalidTelnetOptionException; import java.io.IOException; import java.io.OutputStream; public class ApacheBasedTelnetInterface extends EmulatorVT100 implements TelnetInterface { private TelnetClient tc; private OutputStream outstr; Thread updater; public ApacheBasedTelnetInterface(TelnetClient tc) throws SocketException, InvalidTelnetOptionException, IOException { super(new TerminalSymbol[24][80], tc.getInputStream()); for (int i=0; i<24; i++) for (int j=0; j<80; j++) screen[i][j]=new TerminalSymbol(); this.tc=tc; outstr=this.tc.getOutputStream(); updater=new Thread(this); - updater.run(); + updater.start(); } //@Override public int getdimx() { return 24; } //@Override public int getdimy() { return 80; } //@Override public int getcursorx() { return x; } //@Override public int getcursory() { return y; } //@Override public TerminalSymbol peek(int x, int y) throws IOException { return screen[x][y]; } //@Override public byte[] peekLine(int x) throws IOException { byte[] peek=new byte[80]; for (int y=0; y<80; y++) { peek[y]=screen[x][y].getChar(); } return peek; } //@Override public void send(byte[] s) throws IOException { outstr.write(s); outstr.flush(); } public void send(char c) throws IOException { outstr.write(c); outstr.flush(); } public boolean waiting() throws InterruptedException, IOException { return tc.sendAYT(1000); } public void startUpdating() { updater.notify(); } public void stopUpdating() { updater.interrupt(); } public long timeSinceUpdate() { return System.currentTimeMillis()-lastUpdate; } }
true
true
public ApacheBasedTelnetInterface(TelnetClient tc) throws SocketException, InvalidTelnetOptionException, IOException { super(new TerminalSymbol[24][80], tc.getInputStream()); for (int i=0; i<24; i++) for (int j=0; j<80; j++) screen[i][j]=new TerminalSymbol(); this.tc=tc; outstr=this.tc.getOutputStream(); updater=new Thread(this); updater.run(); }
public ApacheBasedTelnetInterface(TelnetClient tc) throws SocketException, InvalidTelnetOptionException, IOException { super(new TerminalSymbol[24][80], tc.getInputStream()); for (int i=0; i<24; i++) for (int j=0; j<80; j++) screen[i][j]=new TerminalSymbol(); this.tc=tc; outstr=this.tc.getOutputStream(); updater=new Thread(this); updater.start(); }
diff --git a/src/org/concord/data/Unit.java b/src/org/concord/data/Unit.java index 5880ec3..60b6f69 100644 --- a/src/org/concord/data/Unit.java +++ b/src/org/concord/data/Unit.java @@ -1,792 +1,792 @@ /* * Copyright (C) 2004 The Concord Consortium, Inc., * 10 Concord Crossing, Concord, MA 01742 * * Web Site: http://www.concord.org * Email: [email protected] * * 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 * * END LICENSE */ /* * Created on May 4, 2004 * */ package org.concord.data; /** * @author dima * */ import java.util.Vector; import org.concord.framework.data.DataDimension; public final class Unit implements DataDimension{ public int unitCategory = UNIT_CAT_UNKNOWN; public int code = UNIT_CODE_UNKNOWN; public int baseUnit = UNIT_CODE_UNKNOWN; public boolean derived = false; public String name; public String abbreviation; // Powers of the standard units public byte meter = 0; public byte kg = 0; public byte sec = 0; public byte amper = 0; public byte kelvin = 0; public byte candela = 0; public byte mole = 0; public byte radian = 0; public byte steradian = 0; public float koeffA = 1.0f; public float koeffB = 0.0f; public boolean dimLess = false; public boolean doMetricPrefix = false; private static final byte NON_ORDER = 0; final static int METER_INDEX = 0; final static int KG_INDEX = 1; final static int SEC_INDEX = 2; final static int AMPER_INDEX = 3; final static int KELVIN_INDEX = 4; final static int CANDELA_INDEX = 5; final static int MOLE_INDEX = 6; final static int RADIAN_INDEX = 7; final static int STERADIAN_INDEX = 8; public final static int UNIT_CODE_UNKNOWN = 0; public final static int UNIT_CODE_KG = 1; public final static int UNIT_CODE_G = 2; public final static int UNIT_CODE_MT = 3; public final static int UNIT_CODE_LB = 4; public final static int UNIT_CODE_OZ = 5; public final static int UNIT_CODE_AMU = 6; public final static int UNIT_CODE_METER = 7; public final static int UNIT_CODE_INCH = 8; public final static int UNIT_CODE_YARD = 9; public final static int UNIT_CODE_FEET = 10; public final static int UNIT_CODE_MILE_ST = 11; public final static int UNIT_CODE_MICRON = 12; public final static int UNIT_CODE_S = 13; public final static int UNIT_CODE_MIN = 14; public final static int UNIT_CODE_HOUR = 15; public final static int UNIT_CODE_DAY = 16; public final static int UNIT_CODE_CELSIUS = 17; public final static int UNIT_CODE_KELVIN = 18; public final static int UNIT_CODE_FAHRENHEIT = 19; public final static int UNIT_CODE_M2 = 20; public final static int UNIT_CODE_ACRE = 21; public final static int UNIT_CODE_ARE = 22; public final static int UNIT_CODE_HECTARE = 23; public final static int UNIT_CODE_M3 = 24; public final static int UNIT_CODE_LITER = 25; public final static int UNIT_CODE_CC = 26; public final static int UNIT_CODE_BBL_D = 27; public final static int UNIT_CODE_BBL_L = 28; public final static int UNIT_CODE_BU = 29; public final static int UNIT_CODE_GAL_D = 30; public final static int UNIT_CODE_GAL_L = 31; public final static int UNIT_CODE_PT_D = 32; public final static int UNIT_CODE_PT_L = 33; public final static int UNIT_CODE_QT_D = 34; public final static int UNIT_CODE_QT_L = 35; public final static int UNIT_CODE_JOULE = 36; public final static int UNIT_CODE_CALORIE = 37; public final static int UNIT_CODE_EV = 38; public final static int UNIT_CODE_ERG = 39; public final static int UNIT_CODE_WHR = 40; public final static int UNIT_CODE_NEWTON = 41; public final static int UNIT_CODE_DYNE = 42; public final static int UNIT_CODE_KGF = 43; public final static int UNIT_CODE_LBF = 44; public final static int UNIT_CODE_WATT = 45; public final static int UNIT_CODE_HP_MECH = 46; public final static int UNIT_CODE_HP_EL = 47; public final static int UNIT_CODE_HP_METR = 48; public final static int UNIT_CODE_PASCAL = 49; public final static int UNIT_CODE_BAR = 50; public final static int UNIT_CODE_ATM = 51; public final static int UNIT_CODE_MMHG = 52; public final static int UNIT_CODE_CMH2O = 53; public final static int UNIT_CODE_TORR = 54; public final static int UNIT_CODE_ANG_VEL = 55; public final static int UNIT_CODE_LINEAR_VEL = 56; public final static int UNIT_CODE_AMPERE = 57; public final static int UNIT_CODE_VOLT = 58; public final static int UNIT_CODE_COULOMB = 59; public final static int UNIT_CODE_MILLIVOLT = 60; public final static int UNIT_CODE_LUMEN = 61; public final static int UNIT_CODE_LUX = 62; public final static int UNIT_CODE_CENTIMETER = 63; public final static int UNIT_CODE_MILLISECOND = 64; public final static int UNIT_CODE_LINEAR_VEL_MILLISECOND = 65; public final static int UNIT_CODE_KILOMETER = 66; public final static int UNIT_CODE_LINEAR_VEL_KMH = 67; public final static int UNIT_TABLE_LENGTH = 68; public final static int UNIT_CAT_UNKNOWN = 0; public final static int UNIT_CAT_LENGTH = 1; public final static int UNIT_CAT_MASS = 2; public final static int UNIT_CAT_TIME = 3; public final static int UNIT_CAT_TEMPERATURE = 4; public final static int UNIT_CAT_AREA = 5; public final static int UNIT_CAT_VOL_CAP = 6; public final static int UNIT_CAT_ENERGY = 7; public final static int UNIT_CAT_FORCE = 8; public final static int UNIT_CAT_POWER = 9; public final static int UNIT_CAT_PRESSURE = 10; public final static int UNIT_CAT_ELECTRICITY = 11; public final static int UNIT_CAT_LIGHT = 12; public final static int UNIT_CAT_MISC = 13; public final static int UNIT_CAT_VELOCITY = 14; public final static int UNIT_CAT_ACCELERATION = 15; public final static int UNIT_CAT_TABLE_LENGTH = 16; public static String[] catNames = {"Unknown", "Length", "Mass", "Time", "Temperature", "Area", "Volumes/Capacity", "Energy", "Force", "Power", "Pressure", "Electricity", "Light", "Miscellaneous", "Velocity", "Acceleration"}; static byte [][]catNumbers = new byte[UNIT_CAT_TABLE_LENGTH][9]; static{ boolean []flags = new boolean[UNIT_CAT_TABLE_LENGTH]; for(int u = 1; u < UNIT_TABLE_LENGTH; u++){ Unit unit = getUnit(u); if(!flags[unit.unitCategory]){ flags[unit.unitCategory] = true; catNumbers[unit.unitCategory][METER_INDEX] = unit.meter; catNumbers[unit.unitCategory][KG_INDEX] = unit.kg; catNumbers[unit.unitCategory][SEC_INDEX] = unit.sec; catNumbers[unit.unitCategory][AMPER_INDEX] = unit.amper; catNumbers[unit.unitCategory][KELVIN_INDEX] = unit.kelvin; catNumbers[unit.unitCategory][CANDELA_INDEX] = unit.candela; catNumbers[unit.unitCategory][MOLE_INDEX] = unit.mole; catNumbers[unit.unitCategory][RADIAN_INDEX] = unit.radian; catNumbers[unit.unitCategory][STERADIAN_INDEX] = unit.steradian; } } } public static byte[] getCategoryNumber(int category){ if(category < 0 || category >= UNIT_CAT_TABLE_LENGTH) return null; return catNumbers[category]; } public Unit(String name,String abbreviation,boolean derived,int unitCategory,int code,int baseUnit, byte meter,byte kg,byte sec,byte amper,byte kelvin,byte candela,byte mole,byte radian,byte steradian, float koeffA,float koeffB,boolean dimLess,boolean doMetricPrefix){ this.name = name; this.abbreviation = abbreviation; this.derived = derived; this.unitCategory = unitCategory; this.code = code; this.baseUnit = baseUnit; this.meter = meter; this.kg = kg; this.sec = sec; this.amper = amper; this.kelvin = kelvin; this.candela = candela; this.mole = mole; this.radian = radian; this.steradian = steradian; this.koeffA = koeffA; this.koeffB = koeffB; this.dimLess = dimLess; this.doMetricPrefix = doMetricPrefix; } public String getDimension(){return abbreviation;} public void setDimension(String dimension){abbreviation = dimension;} public static Vector getCatUnitAbbrev(int index) { Vector abbrevs = new Vector(); for(int i = 1; i < UNIT_TABLE_LENGTH; i++){ Unit u = getUnit(i); if(u.unitCategory == index){ abbrevs.addElement(u.abbreviation); } } return abbrevs; } public static Unit getUnit(int code){ if(code < 0) return null; switch(code){ case UNIT_CODE_KG : return new Unit("kilogram","kg",false,UNIT_CAT_MASS,UNIT_CODE_KG,UNIT_CODE_KG, (byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1.0f,0.0f,false,false); case UNIT_CODE_G : return new Unit("gram","g",true,UNIT_CAT_MASS,UNIT_CODE_G,UNIT_CODE_KG, (byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 0.001f,0.0f,false,true); case UNIT_CODE_MT : return new Unit("metric ton","tn",true,UNIT_CAT_MASS,UNIT_CODE_MT,UNIT_CODE_KG, (byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1000f,0.0f,false,true); case UNIT_CODE_LB : return new Unit("pound","lb",true,UNIT_CAT_MASS,UNIT_CODE_LB,UNIT_CODE_KG, (byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 0.45359237f,0.0f,false,false); case UNIT_CODE_OZ : return new Unit("ounce","oz",true,UNIT_CAT_MASS,UNIT_CODE_OZ,UNIT_CODE_G, (byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 0.028349523f,0.0f,false,false); case UNIT_CODE_AMU : return new Unit("atomic mass unit","amu",true,UNIT_CAT_MASS,UNIT_CODE_AMU,UNIT_CODE_KG, (byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1.66054e-27f,0.0f,false,false); case UNIT_CODE_KILOMETER : return new Unit("kilometer","m",false,UNIT_CAT_LENGTH,UNIT_CODE_METER,UNIT_CODE_METER, (byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1000f,0.0f,false,true); case UNIT_CODE_METER : return new Unit("meter","m",false,UNIT_CAT_LENGTH,UNIT_CODE_METER,UNIT_CODE_METER, (byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1f,0.0f,false,true); case UNIT_CODE_CENTIMETER : return new Unit("centimeter","cm",false,UNIT_CAT_LENGTH,code,UNIT_CODE_METER, (byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 0.01f,0.0f,false,false); case UNIT_CODE_INCH : return new Unit("inch","in",false,UNIT_CAT_LENGTH,UNIT_CODE_INCH,UNIT_CODE_METER, (byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 0.0254f,0.0f,false,false); case UNIT_CODE_YARD : return new Unit("yard","yd",false,UNIT_CAT_LENGTH,UNIT_CODE_YARD,UNIT_CODE_METER, (byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 0.9144f,0.0f,false,false); case UNIT_CODE_FEET : return new Unit("feet","ft",false,UNIT_CAT_LENGTH,UNIT_CODE_FEET,UNIT_CODE_METER, (byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 0.3048f,0.0f,false,false); case UNIT_CODE_MILE_ST : return new Unit("mile (statute)","mi",false,UNIT_CAT_LENGTH,UNIT_CODE_MILE_ST,UNIT_CODE_METER, (byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1609.344f,0.0f,false,false); case UNIT_CODE_MICRON : return new Unit("micron","?",false,UNIT_CAT_LENGTH,UNIT_CODE_MICRON,UNIT_CODE_METER, (byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1e-6f,0.0f,false,false); case UNIT_CODE_MILLISECOND : return new Unit("millisecond","ms",false,UNIT_CAT_TIME,UNIT_CODE_MILLISECOND,UNIT_CODE_S, (byte)0,(byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 0.001f,0.0f,false,true); case UNIT_CODE_S : return new Unit("second","s",false,UNIT_CAT_TIME,UNIT_CODE_S,UNIT_CODE_S, (byte)0,(byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1f,0.0f,false,true); case UNIT_CODE_MIN : return new Unit("minute","min",false,UNIT_CAT_TIME,UNIT_CODE_MIN,UNIT_CODE_S, (byte)0,(byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 60f,0.0f,false,false); case UNIT_CODE_HOUR : return new Unit("hour","hr",false,UNIT_CAT_TIME,UNIT_CODE_HOUR,UNIT_CODE_S, (byte)0,(byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 3600f,0.0f,false,false); case UNIT_CODE_DAY : return new Unit("day","d",false,UNIT_CAT_TIME,UNIT_CODE_DAY,UNIT_CODE_S, (byte)0,(byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 86400f,0.0f,false,false); case UNIT_CODE_CELSIUS : return new Unit("Celsius","degC",false,UNIT_CAT_TEMPERATURE,UNIT_CODE_CELSIUS,UNIT_CODE_CELSIUS, (byte)0,(byte)0,(byte)0,(byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0, 1f,0.0f,false,false); case UNIT_CODE_KELVIN : return new Unit("Kelvin","K",false,UNIT_CAT_TEMPERATURE,UNIT_CODE_KELVIN,UNIT_CODE_CELSIUS, (byte)0,(byte)0,(byte)0,(byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0, 1f,-273.15f,false,true); case UNIT_CODE_FAHRENHEIT : return new Unit("Fahrenheit","degF",false,UNIT_CAT_TEMPERATURE,UNIT_CODE_FAHRENHEIT,UNIT_CODE_CELSIUS, (byte)0,(byte)0,(byte)0,(byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0, .55555555556f,-17.777777778f,false,false); case UNIT_CODE_M2 : return new Unit("m2","m2",false,UNIT_CAT_AREA,UNIT_CODE_M2,UNIT_CODE_M2, (byte)2,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1f,0.0f,false,false); case UNIT_CODE_ACRE : return new Unit("acre","acre",false,UNIT_CAT_AREA,UNIT_CODE_ACRE,UNIT_CODE_M2, (byte)2,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 4046.8564f,0.0f,false,false); case UNIT_CODE_ARE : return new Unit("are","a",false,UNIT_CAT_AREA,UNIT_CODE_ARE,UNIT_CODE_M2, (byte)2,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 100f,0.0f,false,false); case UNIT_CODE_HECTARE : return new Unit("hectare","ha",true,UNIT_CAT_AREA,UNIT_CODE_HECTARE,UNIT_CODE_M2, (byte)2,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 10000f,0.0f,false,false); case UNIT_CODE_M3 : return new Unit("m3","m3",true,UNIT_CAT_VOL_CAP,UNIT_CODE_M3,UNIT_CODE_M3, (byte)3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1f,0.0f,false,false); case UNIT_CODE_LITER : return new Unit("liter","L",true,UNIT_CAT_VOL_CAP,UNIT_CODE_LITER,UNIT_CODE_M3, (byte)3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 0.001f,0.0f,false,true); case UNIT_CODE_CC : return new Unit("cc","cc",true,UNIT_CAT_VOL_CAP,UNIT_CODE_CC,UNIT_CODE_M3, (byte)3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 0.000001f,0.0f,false,false); case UNIT_CODE_BBL_D : return new Unit("barrel","bbl",true,UNIT_CAT_VOL_CAP,UNIT_CODE_BBL_D,UNIT_CODE_M3, (byte)3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 0.11562712f,0.0f,false,false); case UNIT_CODE_BBL_L : return new Unit("barrel (l)","bbl",true,UNIT_CAT_VOL_CAP,UNIT_CODE_BBL_L,UNIT_CODE_M3, (byte)3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 0.11924047f,0.0f,false,false); case UNIT_CODE_BU : return new Unit("bushel","bu",true,UNIT_CAT_VOL_CAP,UNIT_CODE_BU,UNIT_CODE_M3, (byte)3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 0.03523907f,0.0f,false,false); case UNIT_CODE_GAL_D : return new Unit("gallon","gal",true,UNIT_CAT_VOL_CAP,UNIT_CODE_GAL_D,UNIT_CODE_M3, (byte)3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 0.00440476f,0.0f,false,false); case UNIT_CODE_GAL_L : return new Unit("gallon (liq)","gal",true,UNIT_CAT_VOL_CAP,UNIT_CODE_GAL_L,UNIT_CODE_M3, (byte)3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 0.0037854118f,0.0f,false,false); case UNIT_CODE_PT_D : return new Unit("pint","pt",true,UNIT_CAT_VOL_CAP,UNIT_CODE_PT_D,UNIT_CODE_M3, (byte)3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 5.505951e-4f,0.0f,false,false); case UNIT_CODE_PT_L : return new Unit("pint (liq)","pt",true,UNIT_CAT_VOL_CAP,UNIT_CODE_PT_L,UNIT_CODE_M3, (byte)3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 4.731632e-4f,0.0f,false,false); case UNIT_CODE_QT_D : return new Unit("quart","qt",true,UNIT_CAT_VOL_CAP,UNIT_CODE_QT_D,UNIT_CODE_M3, (byte)3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1.1011901e-3f,0.0f,false,false); case UNIT_CODE_QT_L : return new Unit("quart (liq)","qt",true,UNIT_CAT_VOL_CAP,UNIT_CODE_QT_L,UNIT_CODE_M3, (byte)3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 9.463264e-4f,0.0f,false,false); case UNIT_CODE_JOULE : return new Unit("Joule","J",true,UNIT_CAT_ENERGY,UNIT_CODE_JOULE,UNIT_CODE_JOULE, (byte)2,(byte)1,(byte)-2,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1f,0.0f,false,true); case UNIT_CODE_CALORIE : return new Unit("calorie","cal",true,UNIT_CAT_ENERGY,UNIT_CODE_CALORIE,UNIT_CODE_JOULE, (byte)2,(byte)1,(byte)-2,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 4.184f,0.0f,false,true); case UNIT_CODE_EV : return new Unit("eV","eV",true,UNIT_CAT_ENERGY,UNIT_CODE_EV,UNIT_CODE_JOULE, (byte)2,(byte)1,(byte)-2,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1.60219e-19f,0.0f,false,true); case UNIT_CODE_ERG : return new Unit("erg","erg",true,UNIT_CAT_ENERGY,UNIT_CODE_ERG,UNIT_CODE_JOULE, (byte)2,(byte)1,(byte)-2,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1e-7f,0.0f,false,true); case UNIT_CODE_WHR : return new Unit("Watt-hours","Whr",true,UNIT_CAT_ENERGY,UNIT_CODE_WHR,UNIT_CODE_JOULE, (byte)2,(byte)1,(byte)-2,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 3600f,0.0f,false,true); case UNIT_CODE_NEWTON : return new Unit("Newton","N",true,UNIT_CAT_FORCE,UNIT_CODE_NEWTON,UNIT_CODE_NEWTON, (byte)1,(byte)1,(byte)-2,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1f,0.0f,false,true); case UNIT_CODE_DYNE : return new Unit("dyne","dyn",true,UNIT_CAT_FORCE,UNIT_CODE_DYNE,UNIT_CODE_NEWTON, (byte)1,(byte)1,(byte)-2,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1e-5f,0.0f,false,true); case UNIT_CODE_KGF : return new Unit("kilogram-force","kgf",true,UNIT_CAT_FORCE,UNIT_CODE_KGF,UNIT_CODE_NEWTON, (byte)1,(byte)1,(byte)-2,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 9.80665f,0.0f,false,false); case UNIT_CODE_LBF : return new Unit("pound-force","lbf",true,UNIT_CAT_FORCE,UNIT_CODE_LBF,UNIT_CODE_NEWTON, (byte)1,(byte)1,(byte)-2,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 4.448222f,0.0f,false,false); case UNIT_CODE_WATT : return new Unit("watt","W",true,UNIT_CAT_POWER,UNIT_CODE_WATT,UNIT_CODE_WATT, (byte)2,(byte)1,(byte)-3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1f,0.0f,false,true); case UNIT_CODE_HP_MECH : return new Unit("horsepower","hp",true,UNIT_CAT_POWER,UNIT_CODE_HP_MECH,UNIT_CODE_WATT, (byte)2,(byte)1,(byte)-3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 745.7f,0.0f,false,false); case UNIT_CODE_HP_EL : return new Unit("horsepower (el)","hp(el)",true,UNIT_CAT_POWER,UNIT_CODE_HP_EL,UNIT_CODE_WATT, (byte)2,(byte)1,(byte)-3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 746f,0.0f,false,false); case UNIT_CODE_HP_METR : return new Unit("horsepower (metric)","hp(metric)",true,UNIT_CAT_POWER,UNIT_CODE_HP_METR,UNIT_CODE_WATT, (byte)2,(byte)1,(byte)-3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 735.499f,0.0f,false,false); case UNIT_CODE_PASCAL : return new Unit("Pascal","Pa",true,UNIT_CAT_PRESSURE,UNIT_CODE_PASCAL,UNIT_CODE_PASCAL, (byte)-1,(byte)1,(byte)-1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1f,0.0f,false,true); case UNIT_CODE_BAR : return new Unit("bar","bar",true,UNIT_CAT_PRESSURE,UNIT_CODE_BAR,UNIT_CODE_PASCAL, (byte)-1,(byte)1,(byte)-1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1e5f,0.0f,false,true); case UNIT_CODE_ATM : return new Unit("atmosphere","atm",true,UNIT_CAT_PRESSURE,UNIT_CODE_ATM,UNIT_CODE_PASCAL, (byte)-1,(byte)1,(byte)-1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1.01325e5f,0.0f,false,false); case UNIT_CODE_MMHG : return new Unit("mm Hg","mmHg",true,UNIT_CAT_PRESSURE,UNIT_CODE_MMHG,UNIT_CODE_PASCAL, (byte)-1,(byte)1,(byte)-1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 133.3224f,0.0f,false,false); case UNIT_CODE_CMH2O : return new Unit("cm H2O","cmH2O",true,UNIT_CAT_PRESSURE,UNIT_CODE_CMH2O,UNIT_CODE_PASCAL, (byte)-1,(byte)1,(byte)-1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 98.0638f,0.0f,false,false); case UNIT_CODE_TORR : return new Unit("torr","torr",true,UNIT_CAT_PRESSURE,UNIT_CODE_TORR,UNIT_CODE_PASCAL, (byte)-1,(byte)1,(byte)-1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 133.3224f,0.0f,false,true); case UNIT_CODE_ANG_VEL : return new Unit("rad/s","rad/s",true,UNIT_CAT_MISC,UNIT_CODE_ANG_VEL,UNIT_CODE_ANG_VEL, (byte)0,(byte)0,(byte)-1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)1,(byte)0, 1f,0.0f,false,false); case UNIT_CODE_LINEAR_VEL : return new Unit("m/s","m/s",true,UNIT_CAT_VELOCITY,UNIT_CODE_LINEAR_VEL,UNIT_CODE_LINEAR_VEL, (byte)1,(byte)0,(byte)-1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1f,0.0f,false,true); case UNIT_CODE_LINEAR_VEL_MILLISECOND : return new Unit("m/ms","m/ms",true,UNIT_CAT_VELOCITY,UNIT_CODE_LINEAR_VEL_MILLISECOND,UNIT_CODE_LINEAR_VEL, (byte)1,(byte)0,(byte)-1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1000f,0.0f,false,true); case UNIT_CODE_LINEAR_VEL_KMH : return new Unit("km/h","km/h",true,UNIT_CAT_VELOCITY,UNIT_CODE_LINEAR_VEL_KMH,UNIT_CODE_LINEAR_VEL, (byte)1,(byte)0,(byte)-1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, - 1f/3600f,0.0f,false,true); + 1f/3.6f,0.0f,false,true); case UNIT_CODE_AMPERE : return new Unit("ampere","A",false,UNIT_CAT_ELECTRICITY,UNIT_CODE_AMPERE,UNIT_CODE_AMPERE, (byte)0,(byte)0,(byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1f,0.0f,false,true); case UNIT_CODE_VOLT : return new Unit("volt","V",true,UNIT_CAT_ELECTRICITY,UNIT_CODE_VOLT,UNIT_CODE_VOLT, (byte)2,(byte)1,(byte)-3,(byte)-1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1f,0.0f,false,true); case UNIT_CODE_COULOMB : return new Unit("coulomb","Q",true,UNIT_CAT_ELECTRICITY,UNIT_CODE_COULOMB,UNIT_CODE_COULOMB, (byte)0,(byte)0,(byte)1,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1f,0.0f,false,true); case UNIT_CODE_MILLIVOLT : return new Unit("millivolt","mV",true,UNIT_CAT_ELECTRICITY,UNIT_CODE_MILLIVOLT,UNIT_CODE_VOLT, (byte)2,(byte)1,(byte)-3,(byte)-1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 0.001f,0.0f,false,false); case UNIT_CODE_LUMEN : return new Unit("lumen","lm",true,UNIT_CAT_POWER,UNIT_CODE_LUMEN,UNIT_CODE_WATT, (byte)2,(byte)1,(byte)-3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 0.0014641288f,0.0f,false,true); case UNIT_CODE_LUX : return new Unit("lux","lx",true,UNIT_CAT_LIGHT,UNIT_CODE_LUX,UNIT_CODE_LUX, (byte)0,(byte)1,(byte)-3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 0.0014641288f,0.0f,false,true); } return null; } public static Unit findUnit(String unitAbbreviation) { for(int i = 1; i < UNIT_TABLE_LENGTH; i++){ Unit u = getUnit(i); if(u.abbreviation.equals(unitAbbreviation)) { return u; } } return null; } public static int errorConvertStatus = 0; public static Unit sourceGlobalUnit = null; public static Unit destGlobalUnit = null; public static float unitConvert(Unit unitSrc, float srcValue,Unit unitDest){ float retValue = srcValue; errorConvertStatus = 0; if(!isUnitCompatible(unitSrc,unitDest)){ errorConvertStatus = 1; return retValue; } /* Unit unitSrcBase = Unit.getUnit(unitSrc.baseUnit); Unit unitDestBase = Unit.getUnit(unitDest.baseUnit); if(unitSrcBase == null || unitDestBase == null || unitSrcBase != unitDestBase){ errorConvertStatus = 3; return retValue; } */ retValue = ((srcValue*unitSrc.koeffA + unitSrc.koeffB) - unitDest.koeffB)/ unitDest.koeffA; return retValue; } public static float unitConvert(float srcValue){ return unitConvert(sourceGlobalUnit,srcValue,destGlobalUnit); } public boolean setGlobalUnits(int unitIDSrc,int unitIDDest){ sourceGlobalUnit = destGlobalUnit = null; sourceGlobalUnit = Unit.getUnit(unitIDSrc); if(sourceGlobalUnit == null) return false; destGlobalUnit = Unit.getUnit(unitIDDest); if(destGlobalUnit == null) return false; return true; } public static boolean isUnitCompatible(Unit unitSrc,Unit unitDest){ if(unitSrc == null || unitDest == null) return false; return ((unitSrc.meter == unitDest.meter) && (unitSrc.kg == unitDest.kg) && (unitSrc.sec == unitDest.sec) && (unitSrc.amper == unitDest.amper) && (unitSrc.kelvin == unitDest.kelvin) && (unitSrc.candela == unitDest.candela) && (unitSrc.mole == unitDest.mole) && (unitSrc.radian == unitDest.radian) && (unitSrc.steradian == unitDest.steradian)); } public static boolean isUnitCompatible(int unitIDSrc,int unitIDDest){ return isUnitCompatible(Unit.getUnit(unitIDSrc),Unit.getUnit(unitIDDest)); } public static float unitConvert(int unitIDSrc, float srcValue,int unitIDDest){ return unitConvert(Unit.getUnit(unitIDSrc),srcValue,Unit.getUnit(unitIDDest)); } public static String getPrefixStringForUnit(Unit p,int order){ String retValue = null; if(p == null || !p.doMetricPrefix) return retValue; switch(order){ case -12: retValue = "p"; break; case -9: retValue = "n"; break; case -6: retValue = "?"; break; case -3: retValue = "m"; break; case -2: retValue = "c"; break; case -1: retValue = "d"; break; case 3: retValue = "k"; break; case 6: retValue = "M"; break; case 9: retValue = "G"; break; } return retValue; } public static float getPrefixKoeffForUnit(Unit p,int order){ float retValue = -1f; if(p == null || !p.doMetricPrefix) return retValue; switch(order){ case -12: retValue = 1e-12f; break; case -9: retValue = 1e-9f; break; case -6: retValue = 1e-6f; break; case -3: retValue = 1e-3f; break; case -2: retValue = 0.01f; break; case -1: retValue = 0.1f; break; case 3: retValue = 1000f; break; case 6: retValue = 1e6f; break; case 9: retValue = 1e9f; break; } return retValue; } protected static float calcKoeff0(byte order,float kpart){ float k = 1; if(order == 0) return k; int n = Math.abs(order); for(int i = 0; i < n; i++) k = (order < 0)?(k/kpart):k*kpart; return k; } public static Unit createMechanicUnit(byte meter,byte kg,byte sec,float k){ return new Unit("Custom","",true,UNIT_CAT_UNKNOWN,UNIT_CODE_UNKNOWN,UNIT_CODE_UNKNOWN,meter,kg,sec,NON_ORDER,NON_ORDER,NON_ORDER,NON_ORDER,NON_ORDER,NON_ORDER,k,0,false,false); } public static Unit createMechanicUnit(byte meter,byte kg,byte sec,float kmeter,float kkg, float ksec){ float k = calcKoeff0(meter,kmeter)*calcKoeff0(kg,kkg)*calcKoeff0(sec,ksec); return createMechanicUnit(meter,kg,sec,k); } public static Unit findKnownMechanicUnit(int meter,int kg,int sec,float kmeter,float kkg, float ksec){ Unit needUnit = createMechanicUnit((byte)meter,(byte)kg,(byte)sec,kmeter,kkg,ksec); Unit cat = null; for(int i = 1; i < UNIT_TABLE_LENGTH; i++){ Unit tunit = getUnit(i); if(!isUnitCompatible(tunit,needUnit)) continue; if(needUnit.equals(tunit)){ cat = tunit; break; } } if(cat == null) return needUnit; return cat; } public static Unit findKnownMechanicUnit(int unitMeter,int nmeter,int unitKg,int nkg,int unitSec,int nsec){ Unit u = getUnit(unitMeter); if(u == null) return null; if(u.unitCategory != UNIT_CAT_LENGTH) return null; int umeter = u.meter*nmeter; float kmeter = u.koeffA; u = getUnit(unitKg); if(u == null) return null; if(u.unitCategory != UNIT_CAT_MASS) return null; int ukg = u.kg*nkg; float kkg = u.koeffA; u = getUnit(unitSec); if(u == null) return null; if(u.unitCategory != UNIT_CAT_TIME) return null; int usec = u.sec*nsec; float ksec = u.koeffA; return findKnownMechanicUnit(umeter,ukg,usec,kmeter,kkg,ksec); } public static Unit findKnownMechanicUnit(int category,int unitMeter,int unitKg,int unitSec){ byte []catn = getCategoryNumber(category); if(catn == null) return null; return findKnownMechanicUnit(unitMeter,catn[METER_INDEX],unitKg,catn[KG_INDEX],unitSec,catn[SEC_INDEX]); } public static Unit getUnitFromBasics(int unitCategory, int unitMeter, int unitKg, int unitSec, int unitAmper, int unitKelvin, int unitCandela, int unitMole, int unitRadian, int unitSteradian) { float koeffA=1f; float koeffB=0f; Unit cat=null, u; int i; for(i = 1; i < UNIT_TABLE_LENGTH; i++){ cat = getUnit(i); if(cat.unitCategory == unitCategory){ break; } } if (i == UNIT_TABLE_LENGTH) return null; u = getUnit(unitMeter); if (u!=null){ //System.out.println(u.name + " has koeffA: "+u.koeffA+" "+koeffA + "*" +u.koeffA+"^"+cat.meter); koeffA=koeffA*(float)Math.pow(u.koeffA,cat.meter); } u = getUnit(unitKg); if (u!=null){ //System.out.println(u.name + " has koeffA: "+u.koeffA+" "+koeffA + "*" +u.koeffA+"^"+cat.kg); koeffA=koeffA*(float)Math.pow(u.koeffA,cat.kg); } u = getUnit(unitSec); if (u!=null){ //System.out.println(u.name + " has koeffA: "+u.koeffA+" "+koeffA + "*" +u.koeffA+"^"+cat.sec); koeffA=koeffA*(float)Math.pow(u.koeffA,cat.sec); } u = getUnit(unitAmper); if (u!=null){ koeffA=koeffA*(float)Math.pow(u.koeffA,cat.amper); } u = getUnit(unitKelvin); if (u!=null){ koeffA=koeffA*(float)Math.pow(u.koeffA,cat.kelvin); } u = getUnit(unitCandela); if (u!=null){ koeffA=koeffA*(float)Math.pow(u.koeffA,cat.candela); } u = getUnit(unitMole); if (u!=null){ koeffA=koeffA*(float)Math.pow(u.koeffA,cat.mole); } u = getUnit(unitRadian); if (u!=null){ koeffA=koeffA*(float)Math.pow(u.koeffA,cat.radian); } u = getUnit(unitSteradian); if (u!=null){ koeffA=koeffA*(float)Math.pow(u.koeffA,cat.steradian); } System.out.println("koeffA: "+koeffA); for(i = 1; i < UNIT_TABLE_LENGTH; i++){ u = getUnit(i); if(u.unitCategory == unitCategory){ if (u.koeffA==koeffA){ return u; } } } return new Unit("Unknown","?",true,unitCategory,-1,-1, cat.meter,cat.kg,cat.sec,cat.amper,cat.kelvin, cat.candela,cat.mole,cat.radian,cat.steradian, koeffA,koeffB,false,false); } public String toString(){ String ret = "Unit: "; ret += name+":"+abbreviation+": "+meter+":"; ret += kg+":"; ret += sec+":"; ret += amper+":"; ret += kelvin+":"; ret += candela+":"; ret += mole+":"; ret += radian+":"; ret += steradian+": "; ret += koeffA+":"; ret += koeffB; return ret; } public synchronized boolean equals(Object obj) { if(!(obj instanceof Unit)) return false; if(obj == this) return true; Unit unit = (Unit)obj; if(unit.meter != meter) return false; if(unit.kg != kg) return false; if(unit.sec != sec) return false; if(unit.amper != amper) return false; if(unit.kelvin != kelvin) return false; if(unit.candela != candela) return false; if(unit.mole != mole) return false; if(unit.radian != steradian) return false; if(!MathUtil.equalWithTolerance(unit.koeffA,koeffA,1e-4f)) return false; if(!MathUtil.equalWithTolerance(unit.koeffB,koeffB,1e-4f)) return false; return true; } }
true
true
public static Unit getUnit(int code){ if(code < 0) return null; switch(code){ case UNIT_CODE_KG : return new Unit("kilogram","kg",false,UNIT_CAT_MASS,UNIT_CODE_KG,UNIT_CODE_KG, (byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1.0f,0.0f,false,false); case UNIT_CODE_G : return new Unit("gram","g",true,UNIT_CAT_MASS,UNIT_CODE_G,UNIT_CODE_KG, (byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 0.001f,0.0f,false,true); case UNIT_CODE_MT : return new Unit("metric ton","tn",true,UNIT_CAT_MASS,UNIT_CODE_MT,UNIT_CODE_KG, (byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1000f,0.0f,false,true); case UNIT_CODE_LB : return new Unit("pound","lb",true,UNIT_CAT_MASS,UNIT_CODE_LB,UNIT_CODE_KG, (byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 0.45359237f,0.0f,false,false); case UNIT_CODE_OZ : return new Unit("ounce","oz",true,UNIT_CAT_MASS,UNIT_CODE_OZ,UNIT_CODE_G, (byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 0.028349523f,0.0f,false,false); case UNIT_CODE_AMU : return new Unit("atomic mass unit","amu",true,UNIT_CAT_MASS,UNIT_CODE_AMU,UNIT_CODE_KG, (byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1.66054e-27f,0.0f,false,false); case UNIT_CODE_KILOMETER : return new Unit("kilometer","m",false,UNIT_CAT_LENGTH,UNIT_CODE_METER,UNIT_CODE_METER, (byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1000f,0.0f,false,true); case UNIT_CODE_METER : return new Unit("meter","m",false,UNIT_CAT_LENGTH,UNIT_CODE_METER,UNIT_CODE_METER, (byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1f,0.0f,false,true); case UNIT_CODE_CENTIMETER : return new Unit("centimeter","cm",false,UNIT_CAT_LENGTH,code,UNIT_CODE_METER, (byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 0.01f,0.0f,false,false); case UNIT_CODE_INCH : return new Unit("inch","in",false,UNIT_CAT_LENGTH,UNIT_CODE_INCH,UNIT_CODE_METER, (byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 0.0254f,0.0f,false,false); case UNIT_CODE_YARD : return new Unit("yard","yd",false,UNIT_CAT_LENGTH,UNIT_CODE_YARD,UNIT_CODE_METER, (byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 0.9144f,0.0f,false,false); case UNIT_CODE_FEET : return new Unit("feet","ft",false,UNIT_CAT_LENGTH,UNIT_CODE_FEET,UNIT_CODE_METER, (byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 0.3048f,0.0f,false,false); case UNIT_CODE_MILE_ST : return new Unit("mile (statute)","mi",false,UNIT_CAT_LENGTH,UNIT_CODE_MILE_ST,UNIT_CODE_METER, (byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1609.344f,0.0f,false,false); case UNIT_CODE_MICRON : return new Unit("micron","?",false,UNIT_CAT_LENGTH,UNIT_CODE_MICRON,UNIT_CODE_METER, (byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1e-6f,0.0f,false,false); case UNIT_CODE_MILLISECOND : return new Unit("millisecond","ms",false,UNIT_CAT_TIME,UNIT_CODE_MILLISECOND,UNIT_CODE_S, (byte)0,(byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 0.001f,0.0f,false,true); case UNIT_CODE_S : return new Unit("second","s",false,UNIT_CAT_TIME,UNIT_CODE_S,UNIT_CODE_S, (byte)0,(byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1f,0.0f,false,true); case UNIT_CODE_MIN : return new Unit("minute","min",false,UNIT_CAT_TIME,UNIT_CODE_MIN,UNIT_CODE_S, (byte)0,(byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 60f,0.0f,false,false); case UNIT_CODE_HOUR : return new Unit("hour","hr",false,UNIT_CAT_TIME,UNIT_CODE_HOUR,UNIT_CODE_S, (byte)0,(byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 3600f,0.0f,false,false); case UNIT_CODE_DAY : return new Unit("day","d",false,UNIT_CAT_TIME,UNIT_CODE_DAY,UNIT_CODE_S, (byte)0,(byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 86400f,0.0f,false,false); case UNIT_CODE_CELSIUS : return new Unit("Celsius","degC",false,UNIT_CAT_TEMPERATURE,UNIT_CODE_CELSIUS,UNIT_CODE_CELSIUS, (byte)0,(byte)0,(byte)0,(byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0, 1f,0.0f,false,false); case UNIT_CODE_KELVIN : return new Unit("Kelvin","K",false,UNIT_CAT_TEMPERATURE,UNIT_CODE_KELVIN,UNIT_CODE_CELSIUS, (byte)0,(byte)0,(byte)0,(byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0, 1f,-273.15f,false,true); case UNIT_CODE_FAHRENHEIT : return new Unit("Fahrenheit","degF",false,UNIT_CAT_TEMPERATURE,UNIT_CODE_FAHRENHEIT,UNIT_CODE_CELSIUS, (byte)0,(byte)0,(byte)0,(byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0, .55555555556f,-17.777777778f,false,false); case UNIT_CODE_M2 : return new Unit("m2","m2",false,UNIT_CAT_AREA,UNIT_CODE_M2,UNIT_CODE_M2, (byte)2,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1f,0.0f,false,false); case UNIT_CODE_ACRE : return new Unit("acre","acre",false,UNIT_CAT_AREA,UNIT_CODE_ACRE,UNIT_CODE_M2, (byte)2,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 4046.8564f,0.0f,false,false); case UNIT_CODE_ARE : return new Unit("are","a",false,UNIT_CAT_AREA,UNIT_CODE_ARE,UNIT_CODE_M2, (byte)2,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 100f,0.0f,false,false); case UNIT_CODE_HECTARE : return new Unit("hectare","ha",true,UNIT_CAT_AREA,UNIT_CODE_HECTARE,UNIT_CODE_M2, (byte)2,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 10000f,0.0f,false,false); case UNIT_CODE_M3 : return new Unit("m3","m3",true,UNIT_CAT_VOL_CAP,UNIT_CODE_M3,UNIT_CODE_M3, (byte)3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1f,0.0f,false,false); case UNIT_CODE_LITER : return new Unit("liter","L",true,UNIT_CAT_VOL_CAP,UNIT_CODE_LITER,UNIT_CODE_M3, (byte)3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 0.001f,0.0f,false,true); case UNIT_CODE_CC : return new Unit("cc","cc",true,UNIT_CAT_VOL_CAP,UNIT_CODE_CC,UNIT_CODE_M3, (byte)3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 0.000001f,0.0f,false,false); case UNIT_CODE_BBL_D : return new Unit("barrel","bbl",true,UNIT_CAT_VOL_CAP,UNIT_CODE_BBL_D,UNIT_CODE_M3, (byte)3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 0.11562712f,0.0f,false,false); case UNIT_CODE_BBL_L : return new Unit("barrel (l)","bbl",true,UNIT_CAT_VOL_CAP,UNIT_CODE_BBL_L,UNIT_CODE_M3, (byte)3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 0.11924047f,0.0f,false,false); case UNIT_CODE_BU : return new Unit("bushel","bu",true,UNIT_CAT_VOL_CAP,UNIT_CODE_BU,UNIT_CODE_M3, (byte)3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 0.03523907f,0.0f,false,false); case UNIT_CODE_GAL_D : return new Unit("gallon","gal",true,UNIT_CAT_VOL_CAP,UNIT_CODE_GAL_D,UNIT_CODE_M3, (byte)3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 0.00440476f,0.0f,false,false); case UNIT_CODE_GAL_L : return new Unit("gallon (liq)","gal",true,UNIT_CAT_VOL_CAP,UNIT_CODE_GAL_L,UNIT_CODE_M3, (byte)3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 0.0037854118f,0.0f,false,false); case UNIT_CODE_PT_D : return new Unit("pint","pt",true,UNIT_CAT_VOL_CAP,UNIT_CODE_PT_D,UNIT_CODE_M3, (byte)3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 5.505951e-4f,0.0f,false,false); case UNIT_CODE_PT_L : return new Unit("pint (liq)","pt",true,UNIT_CAT_VOL_CAP,UNIT_CODE_PT_L,UNIT_CODE_M3, (byte)3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 4.731632e-4f,0.0f,false,false); case UNIT_CODE_QT_D : return new Unit("quart","qt",true,UNIT_CAT_VOL_CAP,UNIT_CODE_QT_D,UNIT_CODE_M3, (byte)3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1.1011901e-3f,0.0f,false,false); case UNIT_CODE_QT_L : return new Unit("quart (liq)","qt",true,UNIT_CAT_VOL_CAP,UNIT_CODE_QT_L,UNIT_CODE_M3, (byte)3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 9.463264e-4f,0.0f,false,false); case UNIT_CODE_JOULE : return new Unit("Joule","J",true,UNIT_CAT_ENERGY,UNIT_CODE_JOULE,UNIT_CODE_JOULE, (byte)2,(byte)1,(byte)-2,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1f,0.0f,false,true); case UNIT_CODE_CALORIE : return new Unit("calorie","cal",true,UNIT_CAT_ENERGY,UNIT_CODE_CALORIE,UNIT_CODE_JOULE, (byte)2,(byte)1,(byte)-2,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 4.184f,0.0f,false,true); case UNIT_CODE_EV : return new Unit("eV","eV",true,UNIT_CAT_ENERGY,UNIT_CODE_EV,UNIT_CODE_JOULE, (byte)2,(byte)1,(byte)-2,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1.60219e-19f,0.0f,false,true); case UNIT_CODE_ERG : return new Unit("erg","erg",true,UNIT_CAT_ENERGY,UNIT_CODE_ERG,UNIT_CODE_JOULE, (byte)2,(byte)1,(byte)-2,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1e-7f,0.0f,false,true); case UNIT_CODE_WHR : return new Unit("Watt-hours","Whr",true,UNIT_CAT_ENERGY,UNIT_CODE_WHR,UNIT_CODE_JOULE, (byte)2,(byte)1,(byte)-2,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 3600f,0.0f,false,true); case UNIT_CODE_NEWTON : return new Unit("Newton","N",true,UNIT_CAT_FORCE,UNIT_CODE_NEWTON,UNIT_CODE_NEWTON, (byte)1,(byte)1,(byte)-2,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1f,0.0f,false,true); case UNIT_CODE_DYNE : return new Unit("dyne","dyn",true,UNIT_CAT_FORCE,UNIT_CODE_DYNE,UNIT_CODE_NEWTON, (byte)1,(byte)1,(byte)-2,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1e-5f,0.0f,false,true); case UNIT_CODE_KGF : return new Unit("kilogram-force","kgf",true,UNIT_CAT_FORCE,UNIT_CODE_KGF,UNIT_CODE_NEWTON, (byte)1,(byte)1,(byte)-2,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 9.80665f,0.0f,false,false); case UNIT_CODE_LBF : return new Unit("pound-force","lbf",true,UNIT_CAT_FORCE,UNIT_CODE_LBF,UNIT_CODE_NEWTON, (byte)1,(byte)1,(byte)-2,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 4.448222f,0.0f,false,false); case UNIT_CODE_WATT : return new Unit("watt","W",true,UNIT_CAT_POWER,UNIT_CODE_WATT,UNIT_CODE_WATT, (byte)2,(byte)1,(byte)-3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1f,0.0f,false,true); case UNIT_CODE_HP_MECH : return new Unit("horsepower","hp",true,UNIT_CAT_POWER,UNIT_CODE_HP_MECH,UNIT_CODE_WATT, (byte)2,(byte)1,(byte)-3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 745.7f,0.0f,false,false); case UNIT_CODE_HP_EL : return new Unit("horsepower (el)","hp(el)",true,UNIT_CAT_POWER,UNIT_CODE_HP_EL,UNIT_CODE_WATT, (byte)2,(byte)1,(byte)-3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 746f,0.0f,false,false); case UNIT_CODE_HP_METR : return new Unit("horsepower (metric)","hp(metric)",true,UNIT_CAT_POWER,UNIT_CODE_HP_METR,UNIT_CODE_WATT, (byte)2,(byte)1,(byte)-3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 735.499f,0.0f,false,false); case UNIT_CODE_PASCAL : return new Unit("Pascal","Pa",true,UNIT_CAT_PRESSURE,UNIT_CODE_PASCAL,UNIT_CODE_PASCAL, (byte)-1,(byte)1,(byte)-1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1f,0.0f,false,true); case UNIT_CODE_BAR : return new Unit("bar","bar",true,UNIT_CAT_PRESSURE,UNIT_CODE_BAR,UNIT_CODE_PASCAL, (byte)-1,(byte)1,(byte)-1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1e5f,0.0f,false,true); case UNIT_CODE_ATM : return new Unit("atmosphere","atm",true,UNIT_CAT_PRESSURE,UNIT_CODE_ATM,UNIT_CODE_PASCAL, (byte)-1,(byte)1,(byte)-1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1.01325e5f,0.0f,false,false); case UNIT_CODE_MMHG : return new Unit("mm Hg","mmHg",true,UNIT_CAT_PRESSURE,UNIT_CODE_MMHG,UNIT_CODE_PASCAL, (byte)-1,(byte)1,(byte)-1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 133.3224f,0.0f,false,false); case UNIT_CODE_CMH2O : return new Unit("cm H2O","cmH2O",true,UNIT_CAT_PRESSURE,UNIT_CODE_CMH2O,UNIT_CODE_PASCAL, (byte)-1,(byte)1,(byte)-1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 98.0638f,0.0f,false,false); case UNIT_CODE_TORR : return new Unit("torr","torr",true,UNIT_CAT_PRESSURE,UNIT_CODE_TORR,UNIT_CODE_PASCAL, (byte)-1,(byte)1,(byte)-1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 133.3224f,0.0f,false,true); case UNIT_CODE_ANG_VEL : return new Unit("rad/s","rad/s",true,UNIT_CAT_MISC,UNIT_CODE_ANG_VEL,UNIT_CODE_ANG_VEL, (byte)0,(byte)0,(byte)-1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)1,(byte)0, 1f,0.0f,false,false); case UNIT_CODE_LINEAR_VEL : return new Unit("m/s","m/s",true,UNIT_CAT_VELOCITY,UNIT_CODE_LINEAR_VEL,UNIT_CODE_LINEAR_VEL, (byte)1,(byte)0,(byte)-1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1f,0.0f,false,true); case UNIT_CODE_LINEAR_VEL_MILLISECOND : return new Unit("m/ms","m/ms",true,UNIT_CAT_VELOCITY,UNIT_CODE_LINEAR_VEL_MILLISECOND,UNIT_CODE_LINEAR_VEL, (byte)1,(byte)0,(byte)-1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1000f,0.0f,false,true); case UNIT_CODE_LINEAR_VEL_KMH : return new Unit("km/h","km/h",true,UNIT_CAT_VELOCITY,UNIT_CODE_LINEAR_VEL_KMH,UNIT_CODE_LINEAR_VEL, (byte)1,(byte)0,(byte)-1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1f/3600f,0.0f,false,true); case UNIT_CODE_AMPERE : return new Unit("ampere","A",false,UNIT_CAT_ELECTRICITY,UNIT_CODE_AMPERE,UNIT_CODE_AMPERE, (byte)0,(byte)0,(byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1f,0.0f,false,true); case UNIT_CODE_VOLT : return new Unit("volt","V",true,UNIT_CAT_ELECTRICITY,UNIT_CODE_VOLT,UNIT_CODE_VOLT, (byte)2,(byte)1,(byte)-3,(byte)-1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1f,0.0f,false,true); case UNIT_CODE_COULOMB : return new Unit("coulomb","Q",true,UNIT_CAT_ELECTRICITY,UNIT_CODE_COULOMB,UNIT_CODE_COULOMB, (byte)0,(byte)0,(byte)1,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1f,0.0f,false,true); case UNIT_CODE_MILLIVOLT : return new Unit("millivolt","mV",true,UNIT_CAT_ELECTRICITY,UNIT_CODE_MILLIVOLT,UNIT_CODE_VOLT, (byte)2,(byte)1,(byte)-3,(byte)-1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 0.001f,0.0f,false,false); case UNIT_CODE_LUMEN : return new Unit("lumen","lm",true,UNIT_CAT_POWER,UNIT_CODE_LUMEN,UNIT_CODE_WATT, (byte)2,(byte)1,(byte)-3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 0.0014641288f,0.0f,false,true); case UNIT_CODE_LUX : return new Unit("lux","lx",true,UNIT_CAT_LIGHT,UNIT_CODE_LUX,UNIT_CODE_LUX, (byte)0,(byte)1,(byte)-3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 0.0014641288f,0.0f,false,true); } return null; }
public static Unit getUnit(int code){ if(code < 0) return null; switch(code){ case UNIT_CODE_KG : return new Unit("kilogram","kg",false,UNIT_CAT_MASS,UNIT_CODE_KG,UNIT_CODE_KG, (byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1.0f,0.0f,false,false); case UNIT_CODE_G : return new Unit("gram","g",true,UNIT_CAT_MASS,UNIT_CODE_G,UNIT_CODE_KG, (byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 0.001f,0.0f,false,true); case UNIT_CODE_MT : return new Unit("metric ton","tn",true,UNIT_CAT_MASS,UNIT_CODE_MT,UNIT_CODE_KG, (byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1000f,0.0f,false,true); case UNIT_CODE_LB : return new Unit("pound","lb",true,UNIT_CAT_MASS,UNIT_CODE_LB,UNIT_CODE_KG, (byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 0.45359237f,0.0f,false,false); case UNIT_CODE_OZ : return new Unit("ounce","oz",true,UNIT_CAT_MASS,UNIT_CODE_OZ,UNIT_CODE_G, (byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 0.028349523f,0.0f,false,false); case UNIT_CODE_AMU : return new Unit("atomic mass unit","amu",true,UNIT_CAT_MASS,UNIT_CODE_AMU,UNIT_CODE_KG, (byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1.66054e-27f,0.0f,false,false); case UNIT_CODE_KILOMETER : return new Unit("kilometer","m",false,UNIT_CAT_LENGTH,UNIT_CODE_METER,UNIT_CODE_METER, (byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1000f,0.0f,false,true); case UNIT_CODE_METER : return new Unit("meter","m",false,UNIT_CAT_LENGTH,UNIT_CODE_METER,UNIT_CODE_METER, (byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1f,0.0f,false,true); case UNIT_CODE_CENTIMETER : return new Unit("centimeter","cm",false,UNIT_CAT_LENGTH,code,UNIT_CODE_METER, (byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 0.01f,0.0f,false,false); case UNIT_CODE_INCH : return new Unit("inch","in",false,UNIT_CAT_LENGTH,UNIT_CODE_INCH,UNIT_CODE_METER, (byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 0.0254f,0.0f,false,false); case UNIT_CODE_YARD : return new Unit("yard","yd",false,UNIT_CAT_LENGTH,UNIT_CODE_YARD,UNIT_CODE_METER, (byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 0.9144f,0.0f,false,false); case UNIT_CODE_FEET : return new Unit("feet","ft",false,UNIT_CAT_LENGTH,UNIT_CODE_FEET,UNIT_CODE_METER, (byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 0.3048f,0.0f,false,false); case UNIT_CODE_MILE_ST : return new Unit("mile (statute)","mi",false,UNIT_CAT_LENGTH,UNIT_CODE_MILE_ST,UNIT_CODE_METER, (byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1609.344f,0.0f,false,false); case UNIT_CODE_MICRON : return new Unit("micron","?",false,UNIT_CAT_LENGTH,UNIT_CODE_MICRON,UNIT_CODE_METER, (byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1e-6f,0.0f,false,false); case UNIT_CODE_MILLISECOND : return new Unit("millisecond","ms",false,UNIT_CAT_TIME,UNIT_CODE_MILLISECOND,UNIT_CODE_S, (byte)0,(byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 0.001f,0.0f,false,true); case UNIT_CODE_S : return new Unit("second","s",false,UNIT_CAT_TIME,UNIT_CODE_S,UNIT_CODE_S, (byte)0,(byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1f,0.0f,false,true); case UNIT_CODE_MIN : return new Unit("minute","min",false,UNIT_CAT_TIME,UNIT_CODE_MIN,UNIT_CODE_S, (byte)0,(byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 60f,0.0f,false,false); case UNIT_CODE_HOUR : return new Unit("hour","hr",false,UNIT_CAT_TIME,UNIT_CODE_HOUR,UNIT_CODE_S, (byte)0,(byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 3600f,0.0f,false,false); case UNIT_CODE_DAY : return new Unit("day","d",false,UNIT_CAT_TIME,UNIT_CODE_DAY,UNIT_CODE_S, (byte)0,(byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 86400f,0.0f,false,false); case UNIT_CODE_CELSIUS : return new Unit("Celsius","degC",false,UNIT_CAT_TEMPERATURE,UNIT_CODE_CELSIUS,UNIT_CODE_CELSIUS, (byte)0,(byte)0,(byte)0,(byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0, 1f,0.0f,false,false); case UNIT_CODE_KELVIN : return new Unit("Kelvin","K",false,UNIT_CAT_TEMPERATURE,UNIT_CODE_KELVIN,UNIT_CODE_CELSIUS, (byte)0,(byte)0,(byte)0,(byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0, 1f,-273.15f,false,true); case UNIT_CODE_FAHRENHEIT : return new Unit("Fahrenheit","degF",false,UNIT_CAT_TEMPERATURE,UNIT_CODE_FAHRENHEIT,UNIT_CODE_CELSIUS, (byte)0,(byte)0,(byte)0,(byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0, .55555555556f,-17.777777778f,false,false); case UNIT_CODE_M2 : return new Unit("m2","m2",false,UNIT_CAT_AREA,UNIT_CODE_M2,UNIT_CODE_M2, (byte)2,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1f,0.0f,false,false); case UNIT_CODE_ACRE : return new Unit("acre","acre",false,UNIT_CAT_AREA,UNIT_CODE_ACRE,UNIT_CODE_M2, (byte)2,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 4046.8564f,0.0f,false,false); case UNIT_CODE_ARE : return new Unit("are","a",false,UNIT_CAT_AREA,UNIT_CODE_ARE,UNIT_CODE_M2, (byte)2,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 100f,0.0f,false,false); case UNIT_CODE_HECTARE : return new Unit("hectare","ha",true,UNIT_CAT_AREA,UNIT_CODE_HECTARE,UNIT_CODE_M2, (byte)2,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 10000f,0.0f,false,false); case UNIT_CODE_M3 : return new Unit("m3","m3",true,UNIT_CAT_VOL_CAP,UNIT_CODE_M3,UNIT_CODE_M3, (byte)3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1f,0.0f,false,false); case UNIT_CODE_LITER : return new Unit("liter","L",true,UNIT_CAT_VOL_CAP,UNIT_CODE_LITER,UNIT_CODE_M3, (byte)3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 0.001f,0.0f,false,true); case UNIT_CODE_CC : return new Unit("cc","cc",true,UNIT_CAT_VOL_CAP,UNIT_CODE_CC,UNIT_CODE_M3, (byte)3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 0.000001f,0.0f,false,false); case UNIT_CODE_BBL_D : return new Unit("barrel","bbl",true,UNIT_CAT_VOL_CAP,UNIT_CODE_BBL_D,UNIT_CODE_M3, (byte)3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 0.11562712f,0.0f,false,false); case UNIT_CODE_BBL_L : return new Unit("barrel (l)","bbl",true,UNIT_CAT_VOL_CAP,UNIT_CODE_BBL_L,UNIT_CODE_M3, (byte)3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 0.11924047f,0.0f,false,false); case UNIT_CODE_BU : return new Unit("bushel","bu",true,UNIT_CAT_VOL_CAP,UNIT_CODE_BU,UNIT_CODE_M3, (byte)3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 0.03523907f,0.0f,false,false); case UNIT_CODE_GAL_D : return new Unit("gallon","gal",true,UNIT_CAT_VOL_CAP,UNIT_CODE_GAL_D,UNIT_CODE_M3, (byte)3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 0.00440476f,0.0f,false,false); case UNIT_CODE_GAL_L : return new Unit("gallon (liq)","gal",true,UNIT_CAT_VOL_CAP,UNIT_CODE_GAL_L,UNIT_CODE_M3, (byte)3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 0.0037854118f,0.0f,false,false); case UNIT_CODE_PT_D : return new Unit("pint","pt",true,UNIT_CAT_VOL_CAP,UNIT_CODE_PT_D,UNIT_CODE_M3, (byte)3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 5.505951e-4f,0.0f,false,false); case UNIT_CODE_PT_L : return new Unit("pint (liq)","pt",true,UNIT_CAT_VOL_CAP,UNIT_CODE_PT_L,UNIT_CODE_M3, (byte)3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 4.731632e-4f,0.0f,false,false); case UNIT_CODE_QT_D : return new Unit("quart","qt",true,UNIT_CAT_VOL_CAP,UNIT_CODE_QT_D,UNIT_CODE_M3, (byte)3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1.1011901e-3f,0.0f,false,false); case UNIT_CODE_QT_L : return new Unit("quart (liq)","qt",true,UNIT_CAT_VOL_CAP,UNIT_CODE_QT_L,UNIT_CODE_M3, (byte)3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 9.463264e-4f,0.0f,false,false); case UNIT_CODE_JOULE : return new Unit("Joule","J",true,UNIT_CAT_ENERGY,UNIT_CODE_JOULE,UNIT_CODE_JOULE, (byte)2,(byte)1,(byte)-2,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1f,0.0f,false,true); case UNIT_CODE_CALORIE : return new Unit("calorie","cal",true,UNIT_CAT_ENERGY,UNIT_CODE_CALORIE,UNIT_CODE_JOULE, (byte)2,(byte)1,(byte)-2,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 4.184f,0.0f,false,true); case UNIT_CODE_EV : return new Unit("eV","eV",true,UNIT_CAT_ENERGY,UNIT_CODE_EV,UNIT_CODE_JOULE, (byte)2,(byte)1,(byte)-2,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1.60219e-19f,0.0f,false,true); case UNIT_CODE_ERG : return new Unit("erg","erg",true,UNIT_CAT_ENERGY,UNIT_CODE_ERG,UNIT_CODE_JOULE, (byte)2,(byte)1,(byte)-2,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1e-7f,0.0f,false,true); case UNIT_CODE_WHR : return new Unit("Watt-hours","Whr",true,UNIT_CAT_ENERGY,UNIT_CODE_WHR,UNIT_CODE_JOULE, (byte)2,(byte)1,(byte)-2,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 3600f,0.0f,false,true); case UNIT_CODE_NEWTON : return new Unit("Newton","N",true,UNIT_CAT_FORCE,UNIT_CODE_NEWTON,UNIT_CODE_NEWTON, (byte)1,(byte)1,(byte)-2,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1f,0.0f,false,true); case UNIT_CODE_DYNE : return new Unit("dyne","dyn",true,UNIT_CAT_FORCE,UNIT_CODE_DYNE,UNIT_CODE_NEWTON, (byte)1,(byte)1,(byte)-2,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1e-5f,0.0f,false,true); case UNIT_CODE_KGF : return new Unit("kilogram-force","kgf",true,UNIT_CAT_FORCE,UNIT_CODE_KGF,UNIT_CODE_NEWTON, (byte)1,(byte)1,(byte)-2,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 9.80665f,0.0f,false,false); case UNIT_CODE_LBF : return new Unit("pound-force","lbf",true,UNIT_CAT_FORCE,UNIT_CODE_LBF,UNIT_CODE_NEWTON, (byte)1,(byte)1,(byte)-2,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 4.448222f,0.0f,false,false); case UNIT_CODE_WATT : return new Unit("watt","W",true,UNIT_CAT_POWER,UNIT_CODE_WATT,UNIT_CODE_WATT, (byte)2,(byte)1,(byte)-3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1f,0.0f,false,true); case UNIT_CODE_HP_MECH : return new Unit("horsepower","hp",true,UNIT_CAT_POWER,UNIT_CODE_HP_MECH,UNIT_CODE_WATT, (byte)2,(byte)1,(byte)-3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 745.7f,0.0f,false,false); case UNIT_CODE_HP_EL : return new Unit("horsepower (el)","hp(el)",true,UNIT_CAT_POWER,UNIT_CODE_HP_EL,UNIT_CODE_WATT, (byte)2,(byte)1,(byte)-3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 746f,0.0f,false,false); case UNIT_CODE_HP_METR : return new Unit("horsepower (metric)","hp(metric)",true,UNIT_CAT_POWER,UNIT_CODE_HP_METR,UNIT_CODE_WATT, (byte)2,(byte)1,(byte)-3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 735.499f,0.0f,false,false); case UNIT_CODE_PASCAL : return new Unit("Pascal","Pa",true,UNIT_CAT_PRESSURE,UNIT_CODE_PASCAL,UNIT_CODE_PASCAL, (byte)-1,(byte)1,(byte)-1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1f,0.0f,false,true); case UNIT_CODE_BAR : return new Unit("bar","bar",true,UNIT_CAT_PRESSURE,UNIT_CODE_BAR,UNIT_CODE_PASCAL, (byte)-1,(byte)1,(byte)-1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1e5f,0.0f,false,true); case UNIT_CODE_ATM : return new Unit("atmosphere","atm",true,UNIT_CAT_PRESSURE,UNIT_CODE_ATM,UNIT_CODE_PASCAL, (byte)-1,(byte)1,(byte)-1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1.01325e5f,0.0f,false,false); case UNIT_CODE_MMHG : return new Unit("mm Hg","mmHg",true,UNIT_CAT_PRESSURE,UNIT_CODE_MMHG,UNIT_CODE_PASCAL, (byte)-1,(byte)1,(byte)-1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 133.3224f,0.0f,false,false); case UNIT_CODE_CMH2O : return new Unit("cm H2O","cmH2O",true,UNIT_CAT_PRESSURE,UNIT_CODE_CMH2O,UNIT_CODE_PASCAL, (byte)-1,(byte)1,(byte)-1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 98.0638f,0.0f,false,false); case UNIT_CODE_TORR : return new Unit("torr","torr",true,UNIT_CAT_PRESSURE,UNIT_CODE_TORR,UNIT_CODE_PASCAL, (byte)-1,(byte)1,(byte)-1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 133.3224f,0.0f,false,true); case UNIT_CODE_ANG_VEL : return new Unit("rad/s","rad/s",true,UNIT_CAT_MISC,UNIT_CODE_ANG_VEL,UNIT_CODE_ANG_VEL, (byte)0,(byte)0,(byte)-1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)1,(byte)0, 1f,0.0f,false,false); case UNIT_CODE_LINEAR_VEL : return new Unit("m/s","m/s",true,UNIT_CAT_VELOCITY,UNIT_CODE_LINEAR_VEL,UNIT_CODE_LINEAR_VEL, (byte)1,(byte)0,(byte)-1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1f,0.0f,false,true); case UNIT_CODE_LINEAR_VEL_MILLISECOND : return new Unit("m/ms","m/ms",true,UNIT_CAT_VELOCITY,UNIT_CODE_LINEAR_VEL_MILLISECOND,UNIT_CODE_LINEAR_VEL, (byte)1,(byte)0,(byte)-1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1000f,0.0f,false,true); case UNIT_CODE_LINEAR_VEL_KMH : return new Unit("km/h","km/h",true,UNIT_CAT_VELOCITY,UNIT_CODE_LINEAR_VEL_KMH,UNIT_CODE_LINEAR_VEL, (byte)1,(byte)0,(byte)-1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1f/3.6f,0.0f,false,true); case UNIT_CODE_AMPERE : return new Unit("ampere","A",false,UNIT_CAT_ELECTRICITY,UNIT_CODE_AMPERE,UNIT_CODE_AMPERE, (byte)0,(byte)0,(byte)0,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1f,0.0f,false,true); case UNIT_CODE_VOLT : return new Unit("volt","V",true,UNIT_CAT_ELECTRICITY,UNIT_CODE_VOLT,UNIT_CODE_VOLT, (byte)2,(byte)1,(byte)-3,(byte)-1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1f,0.0f,false,true); case UNIT_CODE_COULOMB : return new Unit("coulomb","Q",true,UNIT_CAT_ELECTRICITY,UNIT_CODE_COULOMB,UNIT_CODE_COULOMB, (byte)0,(byte)0,(byte)1,(byte)1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 1f,0.0f,false,true); case UNIT_CODE_MILLIVOLT : return new Unit("millivolt","mV",true,UNIT_CAT_ELECTRICITY,UNIT_CODE_MILLIVOLT,UNIT_CODE_VOLT, (byte)2,(byte)1,(byte)-3,(byte)-1,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 0.001f,0.0f,false,false); case UNIT_CODE_LUMEN : return new Unit("lumen","lm",true,UNIT_CAT_POWER,UNIT_CODE_LUMEN,UNIT_CODE_WATT, (byte)2,(byte)1,(byte)-3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 0.0014641288f,0.0f,false,true); case UNIT_CODE_LUX : return new Unit("lux","lx",true,UNIT_CAT_LIGHT,UNIT_CODE_LUX,UNIT_CODE_LUX, (byte)0,(byte)1,(byte)-3,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0,(byte)0, 0.0014641288f,0.0f,false,true); } return null; }
diff --git a/src/main/java/org/github/kolorobot/config/PersistenceConfig.java b/src/main/java/org/github/kolorobot/config/PersistenceConfig.java index b760b0d..0d59c23 100644 --- a/src/main/java/org/github/kolorobot/config/PersistenceConfig.java +++ b/src/main/java/org/github/kolorobot/config/PersistenceConfig.java @@ -1,68 +1,68 @@ package org.github.kolorobot.config; import java.util.Properties; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.transaction.annotation.TransactionManagementConfigurer; @Configuration @EnableTransactionManagement @EnableJpaRepositories(basePackages = "org.github.kolorobot.repository", entityManagerFactoryRef = "entityManagerFactory") public class PersistenceConfig implements TransactionManagementConfigurer { @Value("${dataSource.driverClassName}") private String driver; @Value("${dataSource.url}") private String url; @Value("${dataSource.username}") private String username; @Value("${dataSource.password}") private String password; @Value("${hibernate.dialect}") private String dialect; @Value("${hibernate.hbm2ddl.auto}") private String hbm2ddlAuto; @Bean public DataSource dataSource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(driver); dataSource.setUrl(url); dataSource.setUsername(username); dataSource.setPassword(password); return dataSource; } @Bean(name = "entityManagerFactory") public LocalContainerEntityManagerFactoryBean entityManagerFactory() { LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean(); entityManagerFactoryBean.setDataSource(dataSource()); - entityManagerFactoryBean.setPackagesToScan("org.github.kolorobot.user"); + entityManagerFactoryBean.setPackagesToScan("org.github.kolorobot.domain"); entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); Properties jpaProperties = new Properties(); jpaProperties.put(org.hibernate.cfg.Environment.DIALECT, dialect); jpaProperties.put(org.hibernate.cfg.Environment.HBM2DDL_AUTO, hbm2ddlAuto); jpaProperties.put(org.hibernate.cfg.Environment.SHOW_SQL, "true"); entityManagerFactoryBean.setJpaProperties(jpaProperties); return entityManagerFactoryBean; } @Bean(name = "transactionManager") public PlatformTransactionManager annotationDrivenTransactionManager() { return new JpaTransactionManager(); } }
true
true
public LocalContainerEntityManagerFactoryBean entityManagerFactory() { LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean(); entityManagerFactoryBean.setDataSource(dataSource()); entityManagerFactoryBean.setPackagesToScan("org.github.kolorobot.user"); entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); Properties jpaProperties = new Properties(); jpaProperties.put(org.hibernate.cfg.Environment.DIALECT, dialect); jpaProperties.put(org.hibernate.cfg.Environment.HBM2DDL_AUTO, hbm2ddlAuto); jpaProperties.put(org.hibernate.cfg.Environment.SHOW_SQL, "true"); entityManagerFactoryBean.setJpaProperties(jpaProperties); return entityManagerFactoryBean; }
public LocalContainerEntityManagerFactoryBean entityManagerFactory() { LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean(); entityManagerFactoryBean.setDataSource(dataSource()); entityManagerFactoryBean.setPackagesToScan("org.github.kolorobot.domain"); entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); Properties jpaProperties = new Properties(); jpaProperties.put(org.hibernate.cfg.Environment.DIALECT, dialect); jpaProperties.put(org.hibernate.cfg.Environment.HBM2DDL_AUTO, hbm2ddlAuto); jpaProperties.put(org.hibernate.cfg.Environment.SHOW_SQL, "true"); entityManagerFactoryBean.setJpaProperties(jpaProperties); return entityManagerFactoryBean; }
diff --git a/tool/src/main/java/uk/ac/ox/oucs/oauth/servlet/AuthorisationServlet.java b/tool/src/main/java/uk/ac/ox/oucs/oauth/servlet/AuthorisationServlet.java index 897989b..811b69b 100644 --- a/tool/src/main/java/uk/ac/ox/oucs/oauth/servlet/AuthorisationServlet.java +++ b/tool/src/main/java/uk/ac/ox/oucs/oauth/servlet/AuthorisationServlet.java @@ -1,172 +1,172 @@ package uk.ac.ox.oucs.oauth.servlet; import org.sakaiproject.component.api.ServerConfigurationService; import org.sakaiproject.component.cover.ComponentManager; import org.sakaiproject.tool.api.*; import org.sakaiproject.user.api.User; import org.sakaiproject.user.api.UserDirectoryService; import uk.ac.ox.oucs.oauth.domain.Accessor; import uk.ac.ox.oucs.oauth.domain.Consumer; import uk.ac.ox.oucs.oauth.service.OAuthHttpService; import uk.ac.ox.oucs.oauth.service.OAuthService; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * @author Colin Hebert */ public class AuthorisationServlet extends HttpServlet { /** * Name of the "authorise" button in the authorisation page */ public static final String AUTHORISE_BUTTON = "authorise"; /** * Name of the "deny" button in the authorisation page */ public static final String DENY_BUTTON = "deny"; /** * */ private static final String LOGIN_PATH = "/login"; //Services and settings private OAuthService oAuthService; private OAuthHttpService oAuthHttpService; private UserDirectoryService userDirectoryService; private SessionManager sessionManager; private ActiveToolManager activeToolManager; private ServerConfigurationService serverConfigurationService; private String authorisePath; private static final String SAKAI_LOGIN_TOOL = "sakai.login"; @Override public void init(ServletConfig config) throws ServletException { super.init(config); oAuthService = (OAuthService) ComponentManager.getInstance().get(OAuthService.class.getCanonicalName()); oAuthHttpService = (OAuthHttpService) ComponentManager.getInstance().get(OAuthHttpService.class.getCanonicalName()); sessionManager = (SessionManager) ComponentManager.getInstance().get(SessionManager.class.getCanonicalName()); activeToolManager = (ActiveToolManager) ComponentManager.getInstance().get(ActiveToolManager.class.getCanonicalName()); userDirectoryService = (UserDirectoryService) ComponentManager.getInstance().get(UserDirectoryService.class.getCanonicalName()); serverConfigurationService = (ServerConfigurationService) ComponentManager.getInstance().get(ServerConfigurationService.class.getCanonicalName()); //TODO: get this path from the configuration (injection?) authorisePath = "/authorise.jsp"; } @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { handleRequest(request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { handleRequest(request, response); } /** * Filter users trying to obtain an OAuth authorisation token. * <p/> * Three outcomes are possible: * <ul> * <li>The user isn't logged in the application: He's sent toward the login tool</li> * <li>The user is logged in but hasn't filled the authorisation form: He's sent toward the form</li> * <li>The user has filled the form: The OAuth system attenpts to grant a token</li> * </ul> * * @param request current servlet request * @param response current servlet response * @throws IOException * @throws ServletException */ private void handleRequest(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String pathInfo = request.getPathInfo(); String currentUserId = sessionManager.getCurrentSessionUserId(); if (currentUserId == null || (pathInfo != null && pathInfo.startsWith(LOGIN_PATH))) //Redirect non logged-in users and currently logging-in users requests sendToLoginPage(request, response); else if (request.getParameter(AUTHORISE_BUTTON) == null && request.getParameter(DENY_BUTTON) == null) //If logged-in but haven't yet authorised (or denied) sendToAuthorisePage(request, response); else //Even if the authorisation has been denied, send the client to the consumer's callback handleRequestAuth(request, response); } private void sendToLoginPage(HttpServletRequest request, HttpServletResponse response) throws ToolException { //If not logging-in, set the return path and proceed to the login steps String pathInfo = request.getPathInfo(); if (pathInfo == null || !pathInfo.startsWith(LOGIN_PATH)) { Session session = sessionManager.getCurrentSession(); //Set the return path for after login if needed (Note: in session, not tool session, special for Login helper) StringBuffer returnUrl = request.getRequestURL(); if (request.getQueryString() != null) returnUrl.append('?').append(request.getQueryString()); session.setAttribute(Tool.HELPER_DONE_URL, returnUrl.toString()); } //Redirect to the login tool ActiveTool loginTool = activeToolManager.getActiveTool(SAKAI_LOGIN_TOOL); String context = request.getContextPath() + request.getServletPath() + LOGIN_PATH; loginTool.help(request, response, context, LOGIN_PATH); } /** * Pre-set request attributes to provide additional information on the authorisation form. * * @param request current servlet request * @param response current servlet response * @throws IOException * @throws ServletException */ private void sendToAuthorisePage(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { - Accessor accessor = oAuthService.getAccessor(request.getParameter("oauthToken"), Accessor.Type.REQUEST); + Accessor accessor = oAuthService.getAccessor(request.getParameter("oauth_token"), Accessor.Type.REQUEST); Consumer consumer = oAuthService.getConsumer(accessor.getConsumerId()); accessor = oAuthService.startAuthorisation(accessor.getToken()); User user = userDirectoryService.getCurrentUser(); request.setAttribute("userName", user.getDisplayName()); request.setAttribute("userId", user.getDisplayId()); request.setAttribute("uiName", serverConfigurationService.getString("ui.service", "Sakai")); request.setAttribute("skinPath", serverConfigurationService.getString("skin.repo", "/library/skin")); request.setAttribute("defaultSkin", serverConfigurationService.getString("skin.default", "default")); request.setAttribute("authorise", AUTHORISE_BUTTON); request.setAttribute("deny", DENY_BUTTON); request.setAttribute("oauthVerifier", accessor.getVerifier()); request.setAttribute("appName", consumer.getName()); request.setAttribute("appDesc", consumer.getDescription()); request.setAttribute("token", accessor.getToken()); request.getRequestDispatcher(authorisePath).forward(request, response); } /** * Pre-set request attributes to provide additional information to the token creation process. * * @param request current servlet request * @param response current servlet response * @throws IOException * @throws ServletException */ private void handleRequestAuth(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { boolean authorised = request.getParameter(AUTHORISE_BUTTON) != null && request.getParameter(DENY_BUTTON) == null; String token = request.getParameter("oauthToken"); String verifier = request.getParameter("oauthVerifier"); String userId = sessionManager.getCurrentSessionUserId(); oAuthHttpService.handleRequestAuthorisation(request, response, authorised, token, verifier, userId); } }
true
true
private void sendToAuthorisePage(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { Accessor accessor = oAuthService.getAccessor(request.getParameter("oauthToken"), Accessor.Type.REQUEST); Consumer consumer = oAuthService.getConsumer(accessor.getConsumerId()); accessor = oAuthService.startAuthorisation(accessor.getToken()); User user = userDirectoryService.getCurrentUser(); request.setAttribute("userName", user.getDisplayName()); request.setAttribute("userId", user.getDisplayId()); request.setAttribute("uiName", serverConfigurationService.getString("ui.service", "Sakai")); request.setAttribute("skinPath", serverConfigurationService.getString("skin.repo", "/library/skin")); request.setAttribute("defaultSkin", serverConfigurationService.getString("skin.default", "default")); request.setAttribute("authorise", AUTHORISE_BUTTON); request.setAttribute("deny", DENY_BUTTON); request.setAttribute("oauthVerifier", accessor.getVerifier()); request.setAttribute("appName", consumer.getName()); request.setAttribute("appDesc", consumer.getDescription()); request.setAttribute("token", accessor.getToken()); request.getRequestDispatcher(authorisePath).forward(request, response); }
private void sendToAuthorisePage(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { Accessor accessor = oAuthService.getAccessor(request.getParameter("oauth_token"), Accessor.Type.REQUEST); Consumer consumer = oAuthService.getConsumer(accessor.getConsumerId()); accessor = oAuthService.startAuthorisation(accessor.getToken()); User user = userDirectoryService.getCurrentUser(); request.setAttribute("userName", user.getDisplayName()); request.setAttribute("userId", user.getDisplayId()); request.setAttribute("uiName", serverConfigurationService.getString("ui.service", "Sakai")); request.setAttribute("skinPath", serverConfigurationService.getString("skin.repo", "/library/skin")); request.setAttribute("defaultSkin", serverConfigurationService.getString("skin.default", "default")); request.setAttribute("authorise", AUTHORISE_BUTTON); request.setAttribute("deny", DENY_BUTTON); request.setAttribute("oauthVerifier", accessor.getVerifier()); request.setAttribute("appName", consumer.getName()); request.setAttribute("appDesc", consumer.getDescription()); request.setAttribute("token", accessor.getToken()); request.getRequestDispatcher(authorisePath).forward(request, response); }
diff --git a/src/bbarm/viewtest/view/ArcView.java b/src/bbarm/viewtest/view/ArcView.java index 5f5bfa1..94aa31c 100644 --- a/src/bbarm/viewtest/view/ArcView.java +++ b/src/bbarm/viewtest/view/ArcView.java @@ -1,180 +1,181 @@ package bbarm.viewtest.view; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Path; import android.graphics.RectF; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.View; public class ArcView extends View { public interface OnAngleChangedListener { public void onChanging(float angle); public void onChanged(float angle); } private OnAngleChangedListener listener; private Paint paint; private Canvas arcCanvas; private RectF arcOval = new RectF(); private int color; private float width; private float startAngle, endAngle; private boolean flipping; private int flipUnit; public ArcView(Context context) { this(context, null); } public ArcView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public ArcView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } private void init() { paint = new Paint(); paint.setAntiAlias(true); paint.setStyle(Paint.Style.STROKE); } public void setColor(int color) { this.color = color; paint.setColor(color); } public void setStrokeWidth(float width) { this.width = width; paint.setStrokeWidth(width); } public float getStrokeWidth() { return this.width; } public void setOvalSize(float left, float top, float right, float bottom) { arcOval.set(left, top, right, bottom); } public void setStartAngle(float startAngle) { this.startAngle = startAngle; } public Canvas getCanvas() { return arcCanvas; } public void setEndAngle(float endAngle){ this.endAngle = endAngle; } public float getEndAngle(){ return this.endAngle; } public RectF getOval() { return arcOval; } public Paint getPaint() { return paint; } public void setFlippingEnabled(boolean flipping) { this.flipping = flipping; } public void setFlippingUnit(int unit) { this.flipUnit = unit; } public boolean isFlipping() { return this.flipping; } public int getFlippingUnit() { return this.flipUnit; } public void setOnAngleChangedListener(OnAngleChangedListener listener) { this.listener = listener; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); arcCanvas = canvas; float sweep = this.getEndAngle() - startAngle; if (sweep > 360){ sweep -= 360; } arcCanvas.drawArc(arcOval, startAngle, sweep, false, paint); } @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_MOVE: float x = event.getX(); float y = event.getY(); float centerX = getWidth() / 2; float centerY = getHeight() / 2; float relativeX = x - centerX; float relativeY = y - centerY; double cos = relativeX / Math.sqrt(Math.pow(relativeX, 2) + Math.pow(relativeY, 2)); double rad = Math.acos(cos); rad = relativeY > 0 ? rad : Math.PI * 2 - rad; double angle = rad * 180 / Math.PI; setEndAngle((float) angle); invalidate(); if(listener != null) { listener.onChanging((float) angle); } break; case MotionEvent.ACTION_UP: setStrokeWidth(width); float touchUpAngle = getEndAngle(); float targetAngle = touchUpAngle; if(flipping) { - float flipToAngle = touchUpAngle - touchUpAngle % 30; + int flippingUnit = getFlippingUnit(); + float flipToAngle = touchUpAngle - touchUpAngle % flippingUnit; - if(touchUpAngle % 30 >= 15) { - flipToAngle = flipToAngle + 30; + if(touchUpAngle % flippingUnit >= flippingUnit / 2) { + flipToAngle = flipToAngle + flippingUnit; } targetAngle = flipToAngle; } setEndAngle(targetAngle); invalidate(); if(listener != null) { listener.onChanged(targetAngle); } break; } return true; } }
false
true
public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_MOVE: float x = event.getX(); float y = event.getY(); float centerX = getWidth() / 2; float centerY = getHeight() / 2; float relativeX = x - centerX; float relativeY = y - centerY; double cos = relativeX / Math.sqrt(Math.pow(relativeX, 2) + Math.pow(relativeY, 2)); double rad = Math.acos(cos); rad = relativeY > 0 ? rad : Math.PI * 2 - rad; double angle = rad * 180 / Math.PI; setEndAngle((float) angle); invalidate(); if(listener != null) { listener.onChanging((float) angle); } break; case MotionEvent.ACTION_UP: setStrokeWidth(width); float touchUpAngle = getEndAngle(); float targetAngle = touchUpAngle; if(flipping) { float flipToAngle = touchUpAngle - touchUpAngle % 30; if(touchUpAngle % 30 >= 15) { flipToAngle = flipToAngle + 30; } targetAngle = flipToAngle; } setEndAngle(targetAngle); invalidate(); if(listener != null) { listener.onChanged(targetAngle); } break; } return true; }
public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_MOVE: float x = event.getX(); float y = event.getY(); float centerX = getWidth() / 2; float centerY = getHeight() / 2; float relativeX = x - centerX; float relativeY = y - centerY; double cos = relativeX / Math.sqrt(Math.pow(relativeX, 2) + Math.pow(relativeY, 2)); double rad = Math.acos(cos); rad = relativeY > 0 ? rad : Math.PI * 2 - rad; double angle = rad * 180 / Math.PI; setEndAngle((float) angle); invalidate(); if(listener != null) { listener.onChanging((float) angle); } break; case MotionEvent.ACTION_UP: setStrokeWidth(width); float touchUpAngle = getEndAngle(); float targetAngle = touchUpAngle; if(flipping) { int flippingUnit = getFlippingUnit(); float flipToAngle = touchUpAngle - touchUpAngle % flippingUnit; if(touchUpAngle % flippingUnit >= flippingUnit / 2) { flipToAngle = flipToAngle + flippingUnit; } targetAngle = flipToAngle; } setEndAngle(targetAngle); invalidate(); if(listener != null) { listener.onChanged(targetAngle); } break; } return true; }
diff --git a/src/main/java/de/paymill/net/GsonAdapter.java b/src/main/java/de/paymill/net/GsonAdapter.java index d9a6121..5feaaf0 100755 --- a/src/main/java/de/paymill/net/GsonAdapter.java +++ b/src/main/java/de/paymill/net/GsonAdapter.java @@ -1,239 +1,239 @@ package de.paymill.net; import java.io.IOException; import java.lang.reflect.Type; import java.util.Date; import java.util.HashMap; import java.util.Locale; import java.util.Map; import com.google.gson.FieldNamingPolicy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonArray; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import com.google.gson.TypeAdapter; import com.google.gson.TypeAdapterFactory; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import com.google.gson.stream.JsonWriter; import de.paymill.PaymillException; import de.paymill.model.Client; import de.paymill.model.IPaymillObject; import de.paymill.model.Interval; import de.paymill.model.Offer; import de.paymill.model.Payment; import de.paymill.model.Refund; import de.paymill.model.Subscription; import de.paymill.model.Transaction; import de.paymill.model.Webhook; /** * Base class for gson encoder/decoder. */ public class GsonAdapter { /** * Construct a gson instance and add custom serializers/deserializers. * * @return */ protected Gson createGson() { JsonSerializer<Date> serializer = new JsonSerializer<Date>() { @Override public JsonElement serialize(Date src, Type type, JsonSerializationContext context) { return src == null ? null : new JsonPrimitive( (int) (src.getTime() / 1000)); } }; JsonDeserializer<Date> deserializer = new JsonDeserializer<Date>() { @Override public Date deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException { // The API may deliver a date as "false" instead of "null"... if ("false".equals(json.getAsString())) { return null; } - return json == null ? null : new Date(json.getAsInt() * 1000); + return json == null ? null : new Date(json.getAsLong() * 1000); } }; TypeAdapterFactory enumFactory = new TypeAdapterFactory() { public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { @SuppressWarnings("unchecked") final Class<T> rawType = (Class<T>) type.getRawType(); if (!rawType.isEnum()) { return null; } final Map<String, T> lowercaseToConstant = new HashMap<String, T>(); for (T constant : rawType.getEnumConstants()) { lowercaseToConstant.put(toLowercase(constant), constant); } return new TypeAdapter<T>() { public void write(JsonWriter out, T value) throws IOException { if (value == null) { out.nullValue(); } else { if (rawType.isAssignableFrom(Webhook.EventType.class)) { out.value(toLowercase(value).replace('_', '.')); } else { out.value(toLowercase(value)); } } } public T read(JsonReader reader) throws IOException { if (reader.peek() == JsonToken.NULL) { reader.nextNull(); return null; } else { String val = reader.nextString(); if (rawType.isAssignableFrom(Webhook.EventType.class)) { val = val.replace('.', '_'); } return lowercaseToConstant.get(val); } } }; } private String toLowercase(Object o) { return o.toString().toLowerCase(Locale.US); } }; JsonSerializer<Interval> intervalSerializer = new JsonSerializer<Interval>() { @Override public JsonElement serialize(Interval src, Type type, JsonSerializationContext context) { return src == null ? null : new JsonPrimitive(src.getInterval() + " " + src.getUnit()); } }; JsonDeserializer<Interval> intervalDeserializer = new JsonDeserializer<Interval>() { @Override public Interval deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException { if (json == null) { return null; } String str = json.getAsString(); String interval = str.substring(0, str.indexOf(' ')); String unit = str.substring(str.indexOf(' ') + 1); Interval res = new Interval(); res.setInterval(Integer.parseInt(interval)); res.setUnit(Interval.Unit.valueOf(unit)); return res; } }; return new GsonBuilder() .registerTypeAdapter(Date.class, serializer) .registerTypeAdapter(Date.class, deserializer) .registerTypeAdapter(Interval.class, intervalSerializer) .registerTypeAdapter(Interval.class, intervalDeserializer) .registerTypeAdapter(Client.class, new PaymillObjectDeserializer(Client.class, Client0.class)) .registerTypeAdapter(Offer.class, new PaymillObjectDeserializer(Offer.class, Offer0.class)) .registerTypeAdapter(Payment.class, new PaymillObjectDeserializer(Payment.class, Payment0.class)) .registerTypeAdapter(Refund.class, new PaymillObjectDeserializer(Refund.class, Refund0.class)) .registerTypeAdapter(Subscription.class, new SubscriptionDeserializer()) .registerTypeAdapter(Transaction.class, new PaymillObjectDeserializer(Transaction.class, Transaction0.class)) .registerTypeAdapterFactory(enumFactory) .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .create(); } private static class SubscriptionDeserializer implements JsonDeserializer<IPaymillObject> { @Override public IPaymillObject deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException { if (json == null) { return null; } if (json.isJsonObject()) { JsonObject jsonObject = json.getAsJsonObject(); JsonElement offerElement = jsonObject.get("offer"); if (offerElement != null && offerElement.isJsonArray()) { JsonArray jsonArray = offerElement.getAsJsonArray(); if (jsonArray.size() == 0) { jsonObject.remove("offer"); } else { throw new IllegalArgumentException( "Received non empty offer array " + jsonArray); } } return context.deserialize(json, Subscription0.class); } try { String id = json.getAsString(); IPaymillObject instance = new Subscription(); instance.setId(id); return instance; } catch (Exception e) { throw new PaymillException("Error instantiating subscription ", e); } } } class PaymillObjectDeserializer implements JsonDeserializer<IPaymillObject> { private Class<?> targetClass; private Class<?> dummyClass; public PaymillObjectDeserializer(Class<?> targetClass, Class<?> dummyClass) { this.targetClass = targetClass; this.dummyClass = dummyClass; } @Override public IPaymillObject deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException { if (json == null) { return null; } if (json.isJsonObject()) { return context.deserialize(json, dummyClass); } try { String id = json.getAsString(); IPaymillObject instance = (IPaymillObject)targetClass.newInstance(); instance.setId(id); return instance; } catch (Exception e) { throw new PaymillException("Error instantiating " + targetClass, e); } } }; public static class Client0 extends Client {} public static class Offer0 extends Offer {} public static class Payment0 extends Payment {} public static class Refund0 extends Refund {} public static class Subscription0 extends Subscription {} public static class Transaction0 extends Transaction {} }
true
true
protected Gson createGson() { JsonSerializer<Date> serializer = new JsonSerializer<Date>() { @Override public JsonElement serialize(Date src, Type type, JsonSerializationContext context) { return src == null ? null : new JsonPrimitive( (int) (src.getTime() / 1000)); } }; JsonDeserializer<Date> deserializer = new JsonDeserializer<Date>() { @Override public Date deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException { // The API may deliver a date as "false" instead of "null"... if ("false".equals(json.getAsString())) { return null; } return json == null ? null : new Date(json.getAsInt() * 1000); } }; TypeAdapterFactory enumFactory = new TypeAdapterFactory() { public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { @SuppressWarnings("unchecked") final Class<T> rawType = (Class<T>) type.getRawType(); if (!rawType.isEnum()) { return null; } final Map<String, T> lowercaseToConstant = new HashMap<String, T>(); for (T constant : rawType.getEnumConstants()) { lowercaseToConstant.put(toLowercase(constant), constant); } return new TypeAdapter<T>() { public void write(JsonWriter out, T value) throws IOException { if (value == null) { out.nullValue(); } else { if (rawType.isAssignableFrom(Webhook.EventType.class)) { out.value(toLowercase(value).replace('_', '.')); } else { out.value(toLowercase(value)); } } } public T read(JsonReader reader) throws IOException { if (reader.peek() == JsonToken.NULL) { reader.nextNull(); return null; } else { String val = reader.nextString(); if (rawType.isAssignableFrom(Webhook.EventType.class)) { val = val.replace('.', '_'); } return lowercaseToConstant.get(val); } } }; } private String toLowercase(Object o) { return o.toString().toLowerCase(Locale.US); } }; JsonSerializer<Interval> intervalSerializer = new JsonSerializer<Interval>() { @Override public JsonElement serialize(Interval src, Type type, JsonSerializationContext context) { return src == null ? null : new JsonPrimitive(src.getInterval() + " " + src.getUnit()); } }; JsonDeserializer<Interval> intervalDeserializer = new JsonDeserializer<Interval>() { @Override public Interval deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException { if (json == null) { return null; } String str = json.getAsString(); String interval = str.substring(0, str.indexOf(' ')); String unit = str.substring(str.indexOf(' ') + 1); Interval res = new Interval(); res.setInterval(Integer.parseInt(interval)); res.setUnit(Interval.Unit.valueOf(unit)); return res; } }; return new GsonBuilder() .registerTypeAdapter(Date.class, serializer) .registerTypeAdapter(Date.class, deserializer) .registerTypeAdapter(Interval.class, intervalSerializer) .registerTypeAdapter(Interval.class, intervalDeserializer) .registerTypeAdapter(Client.class, new PaymillObjectDeserializer(Client.class, Client0.class)) .registerTypeAdapter(Offer.class, new PaymillObjectDeserializer(Offer.class, Offer0.class)) .registerTypeAdapter(Payment.class, new PaymillObjectDeserializer(Payment.class, Payment0.class)) .registerTypeAdapter(Refund.class, new PaymillObjectDeserializer(Refund.class, Refund0.class)) .registerTypeAdapter(Subscription.class, new SubscriptionDeserializer()) .registerTypeAdapter(Transaction.class, new PaymillObjectDeserializer(Transaction.class, Transaction0.class)) .registerTypeAdapterFactory(enumFactory) .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .create(); }
protected Gson createGson() { JsonSerializer<Date> serializer = new JsonSerializer<Date>() { @Override public JsonElement serialize(Date src, Type type, JsonSerializationContext context) { return src == null ? null : new JsonPrimitive( (int) (src.getTime() / 1000)); } }; JsonDeserializer<Date> deserializer = new JsonDeserializer<Date>() { @Override public Date deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException { // The API may deliver a date as "false" instead of "null"... if ("false".equals(json.getAsString())) { return null; } return json == null ? null : new Date(json.getAsLong() * 1000); } }; TypeAdapterFactory enumFactory = new TypeAdapterFactory() { public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { @SuppressWarnings("unchecked") final Class<T> rawType = (Class<T>) type.getRawType(); if (!rawType.isEnum()) { return null; } final Map<String, T> lowercaseToConstant = new HashMap<String, T>(); for (T constant : rawType.getEnumConstants()) { lowercaseToConstant.put(toLowercase(constant), constant); } return new TypeAdapter<T>() { public void write(JsonWriter out, T value) throws IOException { if (value == null) { out.nullValue(); } else { if (rawType.isAssignableFrom(Webhook.EventType.class)) { out.value(toLowercase(value).replace('_', '.')); } else { out.value(toLowercase(value)); } } } public T read(JsonReader reader) throws IOException { if (reader.peek() == JsonToken.NULL) { reader.nextNull(); return null; } else { String val = reader.nextString(); if (rawType.isAssignableFrom(Webhook.EventType.class)) { val = val.replace('.', '_'); } return lowercaseToConstant.get(val); } } }; } private String toLowercase(Object o) { return o.toString().toLowerCase(Locale.US); } }; JsonSerializer<Interval> intervalSerializer = new JsonSerializer<Interval>() { @Override public JsonElement serialize(Interval src, Type type, JsonSerializationContext context) { return src == null ? null : new JsonPrimitive(src.getInterval() + " " + src.getUnit()); } }; JsonDeserializer<Interval> intervalDeserializer = new JsonDeserializer<Interval>() { @Override public Interval deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException { if (json == null) { return null; } String str = json.getAsString(); String interval = str.substring(0, str.indexOf(' ')); String unit = str.substring(str.indexOf(' ') + 1); Interval res = new Interval(); res.setInterval(Integer.parseInt(interval)); res.setUnit(Interval.Unit.valueOf(unit)); return res; } }; return new GsonBuilder() .registerTypeAdapter(Date.class, serializer) .registerTypeAdapter(Date.class, deserializer) .registerTypeAdapter(Interval.class, intervalSerializer) .registerTypeAdapter(Interval.class, intervalDeserializer) .registerTypeAdapter(Client.class, new PaymillObjectDeserializer(Client.class, Client0.class)) .registerTypeAdapter(Offer.class, new PaymillObjectDeserializer(Offer.class, Offer0.class)) .registerTypeAdapter(Payment.class, new PaymillObjectDeserializer(Payment.class, Payment0.class)) .registerTypeAdapter(Refund.class, new PaymillObjectDeserializer(Refund.class, Refund0.class)) .registerTypeAdapter(Subscription.class, new SubscriptionDeserializer()) .registerTypeAdapter(Transaction.class, new PaymillObjectDeserializer(Transaction.class, Transaction0.class)) .registerTypeAdapterFactory(enumFactory) .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .create(); }
diff --git a/src/main/java/tconstruct/weaponry/client/item/CrossbowRenderer.java b/src/main/java/tconstruct/weaponry/client/item/CrossbowRenderer.java index 587e55317..9b28e3b21 100644 --- a/src/main/java/tconstruct/weaponry/client/item/CrossbowRenderer.java +++ b/src/main/java/tconstruct/weaponry/client/item/CrossbowRenderer.java @@ -1,78 +1,78 @@ package tconstruct.weaponry.client.item; import tconstruct.client.FlexibleToolRenderer; import tconstruct.weaponry.entity.ArrowEntity; import tconstruct.weaponry.entity.BoltEntity; import tconstruct.weaponry.weapons.Crossbow; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.entity.Render; import net.minecraft.client.renderer.entity.RenderManager; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import org.lwjgl.opengl.GL11; public class CrossbowRenderer extends FlexibleToolRenderer { private static final BoltEntity dummy = new BoltEntity(null); @Override protected void specialAnimation(ItemRenderType type, ItemStack item) { EntityPlayer player = Minecraft.getMinecraft().thePlayer; Crossbow crossbow = (Crossbow)item.getItem(); GL11.glTranslatef(0.5f, 0.5f, 0); GL11.glScalef(0.5f, 0.5f, 0.5f); GL11.glScalef(1.5f, 1.5f, 1.5f); if(type == ItemRenderType.EQUIPPED_FIRST_PERSON) { // we're crazy, so.. render the arrow =D ItemStack ammo = crossbow.getLoadedAmmo(item); if(crossbow.isLoaded(item)) { GL11.glTranslatef(0.0f, 0.0f, -0.3f); GL11.glRotatef(80f, 1f, 0f, 0f); GL11.glRotatef(15f, 0f, 1f, 0f); GL11.glRotatef(-20, 0, 0, 1); } else { GL11.glScalef(1.1f, 1.1f, 1.1f); GL11.glTranslatef(0.1f, 0f, 0f); GL11.glRotatef(50f, 1f, 0f, 0f); } - if(ammo != null) { + if(ammo != null && ammo.hasTagCompound()) { //float progress = crossbow.getWindupProgress(item, player); float progress = 1f; dummy.returnStack = ammo; Render renderer = RenderManager.instance.getEntityClassRenderObject(ArrowEntity.class); GL11.glPushMatrix(); // adjust position //GL11.glScalef(2, 2, 2); // bigger GL11.glRotatef(95, 0, 1, 0); // rotate it into the same direction as the bow //GL11.glRotatef(15, 0, 1, 0); // rotate it a bit more so it's not directly inside the bow GL11.glRotatef(-45, 1, 0, 0); // sprite is rotated by 45° in the graphics, correct that GL11.glTranslatef(0.05f, 0, 0); // same as the not-inside-bow-rotation // move the arrow with the charging process float offset = -0.15f; GL11.glTranslatef(0, 0, offset); // render iiit renderer.doRender(dummy, 0, 0, 0, 0, 0); GL11.glPopMatrix(); } } if(type == ItemRenderType.EQUIPPED) { GL11.glTranslatef(0.25f, 0, 0); GL11.glRotatef(45.0F, 0.0F, 0.0F, 1.0F); } GL11.glTranslatef(-0.5f, -0.5f, 0f); } }
true
true
protected void specialAnimation(ItemRenderType type, ItemStack item) { EntityPlayer player = Minecraft.getMinecraft().thePlayer; Crossbow crossbow = (Crossbow)item.getItem(); GL11.glTranslatef(0.5f, 0.5f, 0); GL11.glScalef(0.5f, 0.5f, 0.5f); GL11.glScalef(1.5f, 1.5f, 1.5f); if(type == ItemRenderType.EQUIPPED_FIRST_PERSON) { // we're crazy, so.. render the arrow =D ItemStack ammo = crossbow.getLoadedAmmo(item); if(crossbow.isLoaded(item)) { GL11.glTranslatef(0.0f, 0.0f, -0.3f); GL11.glRotatef(80f, 1f, 0f, 0f); GL11.glRotatef(15f, 0f, 1f, 0f); GL11.glRotatef(-20, 0, 0, 1); } else { GL11.glScalef(1.1f, 1.1f, 1.1f); GL11.glTranslatef(0.1f, 0f, 0f); GL11.glRotatef(50f, 1f, 0f, 0f); } if(ammo != null) { //float progress = crossbow.getWindupProgress(item, player); float progress = 1f; dummy.returnStack = ammo; Render renderer = RenderManager.instance.getEntityClassRenderObject(ArrowEntity.class); GL11.glPushMatrix(); // adjust position //GL11.glScalef(2, 2, 2); // bigger GL11.glRotatef(95, 0, 1, 0); // rotate it into the same direction as the bow //GL11.glRotatef(15, 0, 1, 0); // rotate it a bit more so it's not directly inside the bow GL11.glRotatef(-45, 1, 0, 0); // sprite is rotated by 45° in the graphics, correct that GL11.glTranslatef(0.05f, 0, 0); // same as the not-inside-bow-rotation // move the arrow with the charging process float offset = -0.15f; GL11.glTranslatef(0, 0, offset); // render iiit renderer.doRender(dummy, 0, 0, 0, 0, 0); GL11.glPopMatrix(); } } if(type == ItemRenderType.EQUIPPED) { GL11.glTranslatef(0.25f, 0, 0); GL11.glRotatef(45.0F, 0.0F, 0.0F, 1.0F); } GL11.glTranslatef(-0.5f, -0.5f, 0f); }
protected void specialAnimation(ItemRenderType type, ItemStack item) { EntityPlayer player = Minecraft.getMinecraft().thePlayer; Crossbow crossbow = (Crossbow)item.getItem(); GL11.glTranslatef(0.5f, 0.5f, 0); GL11.glScalef(0.5f, 0.5f, 0.5f); GL11.glScalef(1.5f, 1.5f, 1.5f); if(type == ItemRenderType.EQUIPPED_FIRST_PERSON) { // we're crazy, so.. render the arrow =D ItemStack ammo = crossbow.getLoadedAmmo(item); if(crossbow.isLoaded(item)) { GL11.glTranslatef(0.0f, 0.0f, -0.3f); GL11.glRotatef(80f, 1f, 0f, 0f); GL11.glRotatef(15f, 0f, 1f, 0f); GL11.glRotatef(-20, 0, 0, 1); } else { GL11.glScalef(1.1f, 1.1f, 1.1f); GL11.glTranslatef(0.1f, 0f, 0f); GL11.glRotatef(50f, 1f, 0f, 0f); } if(ammo != null && ammo.hasTagCompound()) { //float progress = crossbow.getWindupProgress(item, player); float progress = 1f; dummy.returnStack = ammo; Render renderer = RenderManager.instance.getEntityClassRenderObject(ArrowEntity.class); GL11.glPushMatrix(); // adjust position //GL11.glScalef(2, 2, 2); // bigger GL11.glRotatef(95, 0, 1, 0); // rotate it into the same direction as the bow //GL11.glRotatef(15, 0, 1, 0); // rotate it a bit more so it's not directly inside the bow GL11.glRotatef(-45, 1, 0, 0); // sprite is rotated by 45° in the graphics, correct that GL11.glTranslatef(0.05f, 0, 0); // same as the not-inside-bow-rotation // move the arrow with the charging process float offset = -0.15f; GL11.glTranslatef(0, 0, offset); // render iiit renderer.doRender(dummy, 0, 0, 0, 0, 0); GL11.glPopMatrix(); } } if(type == ItemRenderType.EQUIPPED) { GL11.glTranslatef(0.25f, 0, 0); GL11.glRotatef(45.0F, 0.0F, 0.0F, 1.0F); } GL11.glTranslatef(-0.5f, -0.5f, 0f); }
diff --git a/org.xpect.ui/src/org/xpect/ui/util/TestDataUIUtil.java b/org.xpect.ui/src/org/xpect/ui/util/TestDataUIUtil.java index 6d48eba..66322c7 100644 --- a/org.xpect.ui/src/org/xpect/ui/util/TestDataUIUtil.java +++ b/org.xpect.ui/src/org/xpect/ui/util/TestDataUIUtil.java @@ -1,113 +1,120 @@ package org.xpect.ui.util; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.emf.common.util.URI; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.junit.model.ITestCaseElement; import org.eclipse.jdt.junit.model.ITestElement; import org.eclipse.jdt.junit.model.ITestSuiteElement; /** * * @author Moritz Eysholdt */ public class TestDataUIUtil { public static class TestElementInfo { private String clazz; private String title; private IFile file; private URI uri; private IJavaProject javaProject; public IJavaProject getJavaProject() { return javaProject; } public String getTitle() { return title; } public String getClazz() { return clazz; } public IFile getFile() { return file; } public String getMethod() { if (title == null) return null; int i = 0; while (i < title.length() && Character.isJavaIdentifierPart(title.charAt(i))) i++; return title.substring(0, i); } public URI getURI() { return uri; } } protected static IFile findFile(ITestElement ele, String filename) { IProject project = ele.getTestRunSession().getLaunchedProject().getProject(); IResource resource = project.findMember(filename); if (resource == null || !resource.exists()) throw new IllegalStateException("File " + resource + " does not exist."); if (!(resource instanceof IFile)) throw new IllegalStateException(resource + " is not a file, but a " + resource.getClass().getSimpleName()); return (IFile) resource; } public static TestElementInfo parse(ITestElement element) { TestElementInfo result = new TestElementInfo(); result.javaProject = element.getTestRunSession().getLaunchedProject(); String project = result.javaProject.getProject().getName(); if (element instanceof ITestCaseElement) { ITestCaseElement tce = (ITestCaseElement) element; result.clazz = tce.getTestClassName(); String methodName = tce.getTestMethodName(); if (methodName.contains("~")) { int colon = methodName.indexOf(':'); String description; URI uri; if (colon >= 0) { description = methodName.substring(colon + 1).trim(); uri = URI.createURI(methodName.substring(0, colon).trim()); } else { description = null; uri = URI.createURI(methodName); } URI base = URI.createPlatformResourceURI(project + "/", true); result.uri = uri.resolve(base); result.file = findFile(element, uri.trimFragment().toString()); String name = uri.fragment(); int tilde = name.indexOf('~'); if (tilde >= 0) name = name.substring(0, tilde); if (description != null) result.title = name + ": " + description; else result.title = name; + } else if (methodName.contains(":")) { + int colon = methodName.indexOf(':'); + String filename = methodName.substring(0, colon).trim(); + String path = methodName.substring(colon + 1).trim(); + result.uri = URI.createPlatformResourceURI(project + "/" + path + "/" + filename, true); + result.file = findFile(element, path + "/" + filename); + result.title = tce.getTestMethodName(); } else { result.title = tce.getTestMethodName(); } } else if (element instanceof ITestSuiteElement) { ITestSuiteElement tse = (ITestSuiteElement) element; String name = tse.getSuiteTypeName(); result.title = tse.getSuiteTypeName(); if (name.contains(":")) { int colon = name.indexOf(':'); String filename = name.substring(0, colon).trim(); String path = name.substring(colon + 1).trim(); result.uri = URI.createPlatformResourceURI(project + "/" + path + "/" + filename, true); result.file = findFile(element, path + "/" + filename); } else { result.clazz = name; } } return result; } }
true
true
public static TestElementInfo parse(ITestElement element) { TestElementInfo result = new TestElementInfo(); result.javaProject = element.getTestRunSession().getLaunchedProject(); String project = result.javaProject.getProject().getName(); if (element instanceof ITestCaseElement) { ITestCaseElement tce = (ITestCaseElement) element; result.clazz = tce.getTestClassName(); String methodName = tce.getTestMethodName(); if (methodName.contains("~")) { int colon = methodName.indexOf(':'); String description; URI uri; if (colon >= 0) { description = methodName.substring(colon + 1).trim(); uri = URI.createURI(methodName.substring(0, colon).trim()); } else { description = null; uri = URI.createURI(methodName); } URI base = URI.createPlatformResourceURI(project + "/", true); result.uri = uri.resolve(base); result.file = findFile(element, uri.trimFragment().toString()); String name = uri.fragment(); int tilde = name.indexOf('~'); if (tilde >= 0) name = name.substring(0, tilde); if (description != null) result.title = name + ": " + description; else result.title = name; } else { result.title = tce.getTestMethodName(); } } else if (element instanceof ITestSuiteElement) { ITestSuiteElement tse = (ITestSuiteElement) element; String name = tse.getSuiteTypeName(); result.title = tse.getSuiteTypeName(); if (name.contains(":")) { int colon = name.indexOf(':'); String filename = name.substring(0, colon).trim(); String path = name.substring(colon + 1).trim(); result.uri = URI.createPlatformResourceURI(project + "/" + path + "/" + filename, true); result.file = findFile(element, path + "/" + filename); } else { result.clazz = name; } } return result; }
public static TestElementInfo parse(ITestElement element) { TestElementInfo result = new TestElementInfo(); result.javaProject = element.getTestRunSession().getLaunchedProject(); String project = result.javaProject.getProject().getName(); if (element instanceof ITestCaseElement) { ITestCaseElement tce = (ITestCaseElement) element; result.clazz = tce.getTestClassName(); String methodName = tce.getTestMethodName(); if (methodName.contains("~")) { int colon = methodName.indexOf(':'); String description; URI uri; if (colon >= 0) { description = methodName.substring(colon + 1).trim(); uri = URI.createURI(methodName.substring(0, colon).trim()); } else { description = null; uri = URI.createURI(methodName); } URI base = URI.createPlatformResourceURI(project + "/", true); result.uri = uri.resolve(base); result.file = findFile(element, uri.trimFragment().toString()); String name = uri.fragment(); int tilde = name.indexOf('~'); if (tilde >= 0) name = name.substring(0, tilde); if (description != null) result.title = name + ": " + description; else result.title = name; } else if (methodName.contains(":")) { int colon = methodName.indexOf(':'); String filename = methodName.substring(0, colon).trim(); String path = methodName.substring(colon + 1).trim(); result.uri = URI.createPlatformResourceURI(project + "/" + path + "/" + filename, true); result.file = findFile(element, path + "/" + filename); result.title = tce.getTestMethodName(); } else { result.title = tce.getTestMethodName(); } } else if (element instanceof ITestSuiteElement) { ITestSuiteElement tse = (ITestSuiteElement) element; String name = tse.getSuiteTypeName(); result.title = tse.getSuiteTypeName(); if (name.contains(":")) { int colon = name.indexOf(':'); String filename = name.substring(0, colon).trim(); String path = name.substring(colon + 1).trim(); result.uri = URI.createPlatformResourceURI(project + "/" + path + "/" + filename, true); result.file = findFile(element, path + "/" + filename); } else { result.clazz = name; } } return result; }
diff --git a/src/me/libraryaddict/Hungergames/Listeners/PlayerListener.java b/src/me/libraryaddict/Hungergames/Listeners/PlayerListener.java index 9686e0b..79a9869 100644 --- a/src/me/libraryaddict/Hungergames/Listeners/PlayerListener.java +++ b/src/me/libraryaddict/Hungergames/Listeners/PlayerListener.java @@ -1,394 +1,394 @@ package me.libraryaddict.Hungergames.Listeners; import java.util.Iterator; import java.util.Random; import me.libraryaddict.Hungergames.Hungergames; import me.libraryaddict.Hungergames.Events.PlayerTrackEvent; import me.libraryaddict.Hungergames.Managers.ChatManager; import me.libraryaddict.Hungergames.Managers.ConfigManager; import me.libraryaddict.Hungergames.Managers.EnchantmentManager; import me.libraryaddict.Hungergames.Managers.KitManager; import me.libraryaddict.Hungergames.Managers.KitSelectorManager; import me.libraryaddict.Hungergames.Managers.PlayerManager; import me.libraryaddict.Hungergames.Managers.ScoreboardManager; import me.libraryaddict.Hungergames.Types.Damage; import me.libraryaddict.Hungergames.Types.HungergamesApi; import me.libraryaddict.Hungergames.Types.Gamer; import me.libraryaddict.Hungergames.Types.Kit; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.command.CommandSender; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; import org.bukkit.entity.Projectile; import org.bukkit.entity.Tameable; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockDamageEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; import org.bukkit.event.entity.EntityPortalEvent; import org.bukkit.event.entity.FoodLevelChangeEvent; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryType; import org.bukkit.event.player.AsyncPlayerChatEvent; import org.bukkit.event.player.PlayerDropItemEvent; import org.bukkit.event.player.PlayerExpChangeEvent; import org.bukkit.event.player.PlayerInteractEntityEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerKickEvent; import org.bukkit.event.player.PlayerLoginEvent; import org.bukkit.event.player.PlayerPickupItemEvent; import org.bukkit.event.player.PlayerLoginEvent.Result; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.vehicle.VehicleDestroyEvent; import org.bukkit.event.vehicle.VehicleEnterEvent; import org.bukkit.event.vehicle.VehicleEntityCollisionEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.scoreboard.DisplaySlot; public class PlayerListener implements Listener { PlayerManager pm = HungergamesApi.getPlayerManager(); ConfigManager config = HungergamesApi.getConfigManager(); KitManager kits = HungergamesApi.getKitManager(); KitSelectorManager icon = HungergamesApi.getKitSelector(); Hungergames hg = HungergamesApi.getHungergames(); private ChatManager cm = HungergamesApi.getChatManager(); @EventHandler public void onExpChange(PlayerExpChangeEvent event) { if (!pm.getGamer(event.getPlayer()).isAlive()) event.setAmount(0); } @EventHandler public void onChat(AsyncPlayerChatEvent event) { Gamer gamer = pm.getGamer(event.getPlayer()); if (!config.isSpectatorChatHidden() && !gamer.isAlive() && hg.doSeconds && !gamer.getPlayer().hasPermission("hungergames.spectatorchat")) { Iterator<Player> players = event.getRecipients().iterator(); while (players.hasNext()) { Gamer g = pm.getGamer(players.next()); if (!g.getPlayer().hasPermission("hungergames.spectatorchat") && g.isAlive()) players.remove(); } } } @EventHandler public void onJoin(PlayerJoinEvent event) { if (kits.getKitByPlayer(event.getPlayer().getName()) == null) kits.setKit(event.getPlayer(), kits.defaultKit); event.setJoinMessage(null); final Gamer gamer = pm.registerGamer(event.getPlayer()); Player p = gamer.getPlayer(); if (cm.getShouldIMessagePlayersWhosePlugin()) p.sendMessage(String.format(cm.getMessagePlayerWhosePlugin(), hg.getDescription().getVersion())); p.setScoreboard(ScoreboardManager.getScoreboard("Main")); p.setAllowFlight(true); if (hg.currentTime >= 0) { pm.setSpectator(gamer); Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(hg, new Runnable() { public void run() { gamer.hide(gamer.getPlayer()); } }, 0L); } else { ScoreboardManager.makeScore("Main", DisplaySlot.SIDEBAR, cm.getScoreboardPlayersLength(), Bukkit.getOnlinePlayers().length); gamer.clearInventory(); if (config.useKitSelector()) Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(hg, new Runnable() { public void run() { gamer.getPlayer().getInventory().addItem(icon.getKitSelector()); } }, 0L); } pm.sendToSpawn(gamer); gamer.updateOthersToSelf(); gamer.updateSelfToOthers(); pm.loadGamer.add(gamer); } @EventHandler public void onDeath(PlayerDeathEvent event) { event.getDrops().clear(); Player p = event.getEntity(); EntityDamageEvent cause = event.getEntity().getLastDamageCause(); String deathMessage = ChatColor.stripColor(event.getDeathMessage()); if (cause instanceof EntityDamageByEntityEvent) { EntityDamageByEntityEvent entityEvent = (EntityDamageByEntityEvent) cause; if (entityEvent.getDamager() instanceof Player) { String weapon = "fist"; Player dmg = (Player) entityEvent.getDamager(); ItemStack item = dmg.getInventory().getItemInHand(); if (item != null && item.getType() != Material.AIR) weapon = kits.toReadable(item.getType().name()); deathMessage = cm.getKillMessages()[new Random().nextInt(cm.getKillMessages().length)]; deathMessage = deathMessage.replace("%Killed%", p.getName()).replace("%Killer%", dmg.getName()) .replace("%Weapon%", weapon); } } else if (cause.getCause() == DamageCause.FALL) deathMessage = String.format(cm.getKillMessageFellToDeath(), p.getName()); Gamer gamer = pm.getGamer(p); pm.killPlayer(gamer, null, p.getLocation(), gamer.getInventory(), deathMessage); event.setDeathMessage(null); } @EventHandler public void onLogin(PlayerLoginEvent event) { if (event.getResult() == Result.KICK_FULL) event.disallow(Result.KICK_FULL, cm.getKickGameFull()); else if (hg.currentTime >= 0 && !config.isSpectatorsEnabled() && !event.getPlayer().hasPermission("hungergames.spectate")) event.disallow(Result.KICK_OTHER, cm.getKickSpectatorsDisabled()); } @EventHandler public void onKick(PlayerKickEvent event) { event.setLeaveMessage(null); } @EventHandler public void onQuit(PlayerQuitEvent event) { event.setQuitMessage(null); Gamer gamer = pm.getGamer(event.getPlayer()); if (gamer.isAlive() && hg.currentTime >= 0 && pm.getAliveGamers().size() > 1) { pm.killPlayer(gamer, null, gamer.getPlayer().getLocation(), gamer.getInventory(), String.format(cm.getKillMessageLeavingGame(), gamer.getName())); } pm.unregisterGamer(gamer); } @EventHandler(priority = EventPriority.LOWEST) public void onBreak(BlockBreakEvent event) { Gamer gamer = pm.getGamer(event.getPlayer()); if (!gamer.canInteract()) event.setCancelled(true); } @EventHandler(priority = EventPriority.LOWEST) public void onPlace(BlockPlaceEvent event) { if (!pm.getGamer(event.getPlayer()).canInteract() || event.getBlock().getLocation().getBlockY() > event.getBlock().getWorld().getMaxHeight()) event.setCancelled(true); } @EventHandler(priority = EventPriority.LOWEST) public void onDamage(BlockDamageEvent event) { if (!pm.getGamer(event.getPlayer()).canInteract()) event.setCancelled(true); } @EventHandler public void onHungry(FoodLevelChangeEvent event) { if (!pm.getGamer(event.getEntity()).isAlive()) event.setCancelled(true); } @EventHandler(priority = EventPriority.LOWEST) public void onDamage(EntityDamageEvent event) { if (event.getEntity() instanceof Player || (event.getEntity() instanceof Tameable && ((Tameable) event.getEntity()).isTamed())) { if ((event.getEntity() instanceof Player && (!hg.doSeconds || !pm.getGamer(event.getEntity()).isAlive())) || hg.currentTime <= config.getInvincibilityTime()) event.setCancelled(true); } } @EventHandler public void onDamageByEntity(EntityDamageByEntityEvent event) { if (event.getDamager() instanceof Player && !pm.getGamer(event.getDamager()).canInteract()) { event.setCancelled(true); return; } if (event.getEntity() instanceof Player) { Gamer damager = null; if (event.getDamager() instanceof Player) damager = pm.getGamer(event.getDamager()); else if (event.getDamager() instanceof Projectile) damager = pm.getGamer(((Projectile) event.getDamager()).getShooter()); else if (event.getDamager() instanceof Tameable) { if (((Tameable) event.getDamager()).getOwner() != null) damager = pm.getGamer(((Tameable) event.getDamager()).getOwner().getName()); } if (damager != null) { if (damager.canInteract()) pm.lastDamager.put(pm.getGamer(event.getEntity()), new Damage((System.currentTimeMillis() / 1000) + 60, damager)); } } } @EventHandler(priority = EventPriority.LOWEST) public void onInteract(PlayerInteractEvent event) { Player p = event.getPlayer(); Gamer gamer = pm.getGamer(p); if (!gamer.canInteract()) { event.setCancelled(true); /* * if (event.getAction() == Action.RIGHT_CLICK_BLOCK && * event.getClickedBlock().getState() != null && * event.getClickedBlock().getState() instanceof InventoryHolder) { * p.openInventory(((InventoryHolder) * event.getClickedBlock().getState()).getInventory()); } */ } ItemStack item = event.getItem(); if (item != null && item.getType() == Material.COMPASS && event.getAction() != Action.PHYSICAL) { double distance = 10000; Player victim = null; for (Gamer game : HungergamesApi.getPlayerManager().getAliveGamers()) { double distOfPlayerToVictim = p.getLocation().distance(game.getPlayer().getLocation()); if (distOfPlayerToVictim < distance && distOfPlayerToVictim > 15) { distance = distOfPlayerToVictim; victim = game.getPlayer(); } } PlayerTrackEvent trackEvent = new PlayerTrackEvent(gamer, victim, (victim == null ? cm.getMessagePlayerTrackNoVictim() : String.format(cm.getMessagePlayerTrack(), victim.getName()))); Bukkit.getPluginManager().callEvent(trackEvent); if (!trackEvent.isCancelled()) { p.sendMessage(trackEvent.getMessage()); if (victim != null) { - p.setCompassTarget(victim.getLocation()); + p.setCompassTarget(victim.getLocation().clone()); } else { p.setCompassTarget(p.getWorld().getSpawnLocation()); } } } if (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK) { if (gamer.isAlive() && gamer.canRide()) if (p.isInsideVehicle() == true) p.leaveVehicle(); if (item != null) { if (item.equals(icon.getKitSelector())) { p.openInventory(icon.getInventory()); event.setCancelled(true); } if (item.getType() == Material.MUSHROOM_SOUP && config.isMushroomStew()) { if (p.getHealth() < 20 || p.getFoodLevel() < 19) { event.setCancelled(true); if (p.getHealth() < 20) if (p.getHealth() + config.mushroomStewRestores() <= 20) p.setHealth(p.getHealth() + config.mushroomStewRestores()); else p.setHealth(20); else if (p.getFoodLevel() < 20) if (p.getFoodLevel() + config.mushroomStewRestores() <= 20) p.setFoodLevel(p.getFoodLevel() + config.mushroomStewRestores()); else p.setFoodLevel(20); if (item.getAmount() > 1) { item.setAmount(item.getAmount() - 1); kits.addItem(p, new ItemStack(Material.BOWL)); } else item = new ItemStack(Material.BOWL); p.setItemInHand(item); } } } } } @EventHandler public void onInteractEntity(PlayerInteractEntityEvent event) { Gamer gamer = pm.getGamer(event.getPlayer()); if (!gamer.canInteract()) { event.setCancelled(true); } if (!gamer.isAlive()) { if (event.getRightClicked() instanceof Player) { Player victim = (Player) event.getRightClicked(); Player p = event.getPlayer(); p.sendMessage(String.format(cm.getMessagePlayerHasHealthAndHunger(), victim.getName(), victim.getHealth(), victim.getName(), victim.getFoodLevel())); } if (gamer.canRide()) { if (event.getPlayer().isInsideVehicle() == false && event.getRightClicked().getVehicle() != event.getPlayer()) event.getRightClicked().setPassenger(event.getPlayer()); else event.getPlayer().leaveVehicle(); } } } @EventHandler public void onPickup(PlayerPickupItemEvent event) { if (!pm.getGamer(event.getPlayer()).isAlive()) event.setCancelled(true); } @EventHandler public void onPickup(PlayerDropItemEvent event) { if (!pm.getGamer(event.getPlayer()).canInteract()) event.setCancelled(true); } @EventHandler public void onVechileEnter(VehicleEnterEvent event) { if (event.getEntered() instanceof Player) { if (!pm.getGamer(event.getEntered()).canInteract()) { event.setCancelled(true); } } } @EventHandler public void onVechileMove(VehicleEntityCollisionEvent event) { if (event.getEntity() instanceof Player) if (!pm.getGamer(event.getEntity()).canInteract()) event.setCancelled(true); } @EventHandler public void onVechileEvent(VehicleDestroyEvent event) { if (event.getAttacker() instanceof Player) { if (!pm.getGamer(event.getAttacker()).canInteract()) { event.setCancelled(true); } } } @EventHandler public void onEnter(EntityPortalEvent event) { event.setCancelled(true); } @EventHandler public void onInventoryClick(InventoryClickEvent event) { if (!pm.getGamer(event.getWhoClicked()).canInteract()) { event.setCancelled(true); } if (event.getView().getTopInventory().getType() == InventoryType.ANVIL && event.getCurrentItem() != null && event.getCurrentItem().getType() != Material.AIR) { for (Enchantment enchant : event.getCurrentItem().getEnchantments().keySet()) if (!EnchantmentManager.isNatural(enchant)) { event.setCancelled(true); ((Player) event.getWhoClicked()).sendMessage(cm.getMessagePlayerWarningForgeUnstableEnchants()); return; } } if (event.getView().getTitle() != null && event.getView().getTitle().equals(icon.getInventory().getTitle())) { event.setCancelled(true); ItemStack item = event.getCurrentItem(); if (item != null && item.hasItemMeta() && item.getItemMeta().hasDisplayName()) { Kit kit = kits.getKitByName(ChatColor.stripColor(item.getItemMeta().getDisplayName())); if (kit != null) Bukkit.dispatchCommand((CommandSender) event.getWhoClicked(), "kit " + kit.getName()); } } } }
true
true
public void onInteract(PlayerInteractEvent event) { Player p = event.getPlayer(); Gamer gamer = pm.getGamer(p); if (!gamer.canInteract()) { event.setCancelled(true); /* * if (event.getAction() == Action.RIGHT_CLICK_BLOCK && * event.getClickedBlock().getState() != null && * event.getClickedBlock().getState() instanceof InventoryHolder) { * p.openInventory(((InventoryHolder) * event.getClickedBlock().getState()).getInventory()); } */ } ItemStack item = event.getItem(); if (item != null && item.getType() == Material.COMPASS && event.getAction() != Action.PHYSICAL) { double distance = 10000; Player victim = null; for (Gamer game : HungergamesApi.getPlayerManager().getAliveGamers()) { double distOfPlayerToVictim = p.getLocation().distance(game.getPlayer().getLocation()); if (distOfPlayerToVictim < distance && distOfPlayerToVictim > 15) { distance = distOfPlayerToVictim; victim = game.getPlayer(); } } PlayerTrackEvent trackEvent = new PlayerTrackEvent(gamer, victim, (victim == null ? cm.getMessagePlayerTrackNoVictim() : String.format(cm.getMessagePlayerTrack(), victim.getName()))); Bukkit.getPluginManager().callEvent(trackEvent); if (!trackEvent.isCancelled()) { p.sendMessage(trackEvent.getMessage()); if (victim != null) { p.setCompassTarget(victim.getLocation()); } else { p.setCompassTarget(p.getWorld().getSpawnLocation()); } } } if (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK) { if (gamer.isAlive() && gamer.canRide()) if (p.isInsideVehicle() == true) p.leaveVehicle(); if (item != null) { if (item.equals(icon.getKitSelector())) { p.openInventory(icon.getInventory()); event.setCancelled(true); } if (item.getType() == Material.MUSHROOM_SOUP && config.isMushroomStew()) { if (p.getHealth() < 20 || p.getFoodLevel() < 19) { event.setCancelled(true); if (p.getHealth() < 20) if (p.getHealth() + config.mushroomStewRestores() <= 20) p.setHealth(p.getHealth() + config.mushroomStewRestores()); else p.setHealth(20); else if (p.getFoodLevel() < 20) if (p.getFoodLevel() + config.mushroomStewRestores() <= 20) p.setFoodLevel(p.getFoodLevel() + config.mushroomStewRestores()); else p.setFoodLevel(20); if (item.getAmount() > 1) { item.setAmount(item.getAmount() - 1); kits.addItem(p, new ItemStack(Material.BOWL)); } else item = new ItemStack(Material.BOWL); p.setItemInHand(item); } } } } }
public void onInteract(PlayerInteractEvent event) { Player p = event.getPlayer(); Gamer gamer = pm.getGamer(p); if (!gamer.canInteract()) { event.setCancelled(true); /* * if (event.getAction() == Action.RIGHT_CLICK_BLOCK && * event.getClickedBlock().getState() != null && * event.getClickedBlock().getState() instanceof InventoryHolder) { * p.openInventory(((InventoryHolder) * event.getClickedBlock().getState()).getInventory()); } */ } ItemStack item = event.getItem(); if (item != null && item.getType() == Material.COMPASS && event.getAction() != Action.PHYSICAL) { double distance = 10000; Player victim = null; for (Gamer game : HungergamesApi.getPlayerManager().getAliveGamers()) { double distOfPlayerToVictim = p.getLocation().distance(game.getPlayer().getLocation()); if (distOfPlayerToVictim < distance && distOfPlayerToVictim > 15) { distance = distOfPlayerToVictim; victim = game.getPlayer(); } } PlayerTrackEvent trackEvent = new PlayerTrackEvent(gamer, victim, (victim == null ? cm.getMessagePlayerTrackNoVictim() : String.format(cm.getMessagePlayerTrack(), victim.getName()))); Bukkit.getPluginManager().callEvent(trackEvent); if (!trackEvent.isCancelled()) { p.sendMessage(trackEvent.getMessage()); if (victim != null) { p.setCompassTarget(victim.getLocation().clone()); } else { p.setCompassTarget(p.getWorld().getSpawnLocation()); } } } if (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK) { if (gamer.isAlive() && gamer.canRide()) if (p.isInsideVehicle() == true) p.leaveVehicle(); if (item != null) { if (item.equals(icon.getKitSelector())) { p.openInventory(icon.getInventory()); event.setCancelled(true); } if (item.getType() == Material.MUSHROOM_SOUP && config.isMushroomStew()) { if (p.getHealth() < 20 || p.getFoodLevel() < 19) { event.setCancelled(true); if (p.getHealth() < 20) if (p.getHealth() + config.mushroomStewRestores() <= 20) p.setHealth(p.getHealth() + config.mushroomStewRestores()); else p.setHealth(20); else if (p.getFoodLevel() < 20) if (p.getFoodLevel() + config.mushroomStewRestores() <= 20) p.setFoodLevel(p.getFoodLevel() + config.mushroomStewRestores()); else p.setFoodLevel(20); if (item.getAmount() > 1) { item.setAmount(item.getAmount() - 1); kits.addItem(p, new ItemStack(Material.BOWL)); } else item = new ItemStack(Material.BOWL); p.setItemInHand(item); } } } } }
diff --git a/src/quill/quack/QuackLoader.java b/src/quill/quack/QuackLoader.java index a8c0b38..77d6762 100644 --- a/src/quill/quack/QuackLoader.java +++ b/src/quill/quack/QuackLoader.java @@ -1,523 +1,523 @@ /* * Quill and Parchment, a WYSIWYN document editor and rendering engine. * * Copyright © 2008-2010 Operational Dynamics Consulting, Pty Ltd * * The code in this file, and the program it is a part of, is made available * to you by its authors as open source software: you can redistribute it * and/or modify it under the terms of the GNU General Public License version * 2 ("GPL") 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 GPL for more details. * * You should have received a copy of the GPL along with this program. If not, * see http://www.gnu.org/licenses/. The authors of this program may be * contacted through http://research.operationaldynamics.com/projects/quill/. */ package quill.quack; import java.util.ArrayList; import nu.xom.Document; import quill.textbase.AttributionSegment; import quill.textbase.ChapterSegment; import quill.textbase.Common; import quill.textbase.ComponentSegment; import quill.textbase.DivisionSegment; import quill.textbase.EndnoteSegment; import quill.textbase.Extract; import quill.textbase.HeadingSegment; import quill.textbase.ImageSegment; import quill.textbase.LeaderSegment; import quill.textbase.ListitemSegment; import quill.textbase.Markup; import quill.textbase.NormalSegment; import quill.textbase.PoeticSegment; import quill.textbase.PreformatSegment; import quill.textbase.QuoteSegment; import quill.textbase.ReferenceSegment; import quill.textbase.Segment; import quill.textbase.Series; import quill.textbase.Span; import quill.textbase.Special; import quill.textbase.SpecialSegment; import quill.textbase.TextChain; import static quill.textbase.Span.createSpan; /** * Take a XOM tree (built using QuackNodeFactory and so having our * QuackElements) and convert it into our internal in-memory textchain * representation. * * @author Andrew Cowie */ public class QuackLoader { private final ArrayList<Segment> list; /** * The (single) formatting applicable at this insertion point. */ private Markup markup; /** * Did we just enter a block level element? */ private boolean start; /** * The current block level element wrapper */ private Segment segment; /** * The current text body we are building up. */ private TextChain chain; /** * The current metadata we have captured */ /* * This is horrid, only supporting one attribute. */ private String attribute; /** * Are we in a block where line endings and other whitespace is preserved? */ private boolean preserve; /** * Did we trim a whitespace character (newline, specifically) from the end * of the previous Text? */ private boolean space; /** * If a whitespace was swollowed, then append this Span. */ private Span pending; public QuackLoader() { list = new ArrayList<Segment>(5); chain = null; } /* * FIXME This assumes our documents have only one chapter in them. That's * not correct! */ /* * This kinda assumes we only load one Document; if that's not the case, * and we don't force instantiating a new QuackLoader, then clear the * processor state here. */ public Series process(Document doc) { final Root quack; int j; Block[] blocks; quack = (Root) doc.getRootElement(); processComponent(quack); /* * Now iterate over the Blocks. */ blocks = quack.getBlocks(); for (j = 0; j < blocks.length; j++) { processBlock(blocks[j]); } /* * Finally, transpose the resultant collection of Segments into a * Series, and return it. */ ensureChapterHasTitle(); return new Series(list); } private void processComponent(Root quack) { if (quack instanceof RootElement) { start = true; preserve = false; } else { throw new UnsupportedOperationException(); } } /** * Ensure that the first Segment in the Series is a ComponentSegment. */ /* * This is a bit of a hack, but this means that at run time inside the app * we always have at least one Segment. And, just to make the user * experience a touch better, if there wasn't a second Segment, then add a * Normal one so that there is somewhere to type. */ private void ensureChapterHasTitle() { final int num; Segment first, second; final Extract blank; num = list.size(); if (num == 0) { blank = Extract.create(); first = new ChapterSegment(blank); list.add(first); second = new NormalSegment(blank); list.add(second); return; } first = list.get(0); if (first instanceof ComponentSegment) { if (num > 1) { /* * This is the usual case; there's a title and some body. * Excellent. We're done. */ return; } blank = Extract.create(); second = new NormalSegment(blank); list.add(second); } else { blank = Extract.create(); first = new ChapterSegment(blank); list.add(0, first); } } /* * It's a bit ugly to be adding the Segment only to immediately remove it * again in the common case of a continuing run of normal text. */ private void processBlock(Block block) { Extract entire; int i; start = true; chain = new TextChain(); attribute = null; if (block instanceof TextElement) { preserve = false; if (segment instanceof NormalSegment) { entire = segment.getEntire(); chain.setTree(entire); chain.append(Span.createSpan('\n', null)); i = list.size() - 1; list.remove(i); } } else if (block instanceof CodeElement) { preserve = true; } else if (block instanceof QuoteElement) { preserve = false; if (segment instanceof QuoteSegment) { entire = segment.getEntire(); chain.setTree(entire); chain.append(Span.createSpan('\n', null)); i = list.size() - 1; list.remove(i); } } else if (block instanceof PoemElement) { preserve = true; } else if (block instanceof ListElement) { preserve = false; processData(block); if ((attribute == null) && (segment instanceof ListitemSegment)) { entire = segment.getEntire(); chain.setTree(entire); chain.append(Span.createSpan('\n', null)); i = list.size() - 1; list.remove(i); attribute = segment.getImage(); } } else if (block instanceof CreditElement) { preserve = false; if (segment instanceof AttributionSegment) { entire = segment.getEntire(); chain.setTree(entire); chain.append(Span.createSpan('\n', null)); i = list.size() - 1; list.remove(i); } } else if (block instanceof HeadingElement) { preserve = false; processData(block); } else if (block instanceof LeaderElement) { preserve = false; } else if (block instanceof ImageElement) { preserve = false; processData(block); } else if ((block instanceof ChapterElement) || (block instanceof DivisionElement)) { preserve = false; if (segment != null) { - throw new IllegalStateException("\n" - + "A <chapter> must be the first block in a Quack file."); + throw new IllegalStateException("\n" + "A " + block.toString() + + " must be the first block in a Quack file."); } processData(block); } else if (block instanceof EndnoteElement) { preserve = false; processData(block); } else if (block instanceof ReferenceElement) { preserve = false; processData(block); } else if (block instanceof SpecialElement) { preserve = false; processData(block); } else { throw new IllegalStateException("\n" + "What kind of Block is " + block); } /* * Now iterate over the text and Inlines of the Block, accumulating * into the TextChain. */ processBody(block); /* * With that done, form the [immutable] Segment based on the * accumulated data. */ entire = chain.extractAll(); if (block instanceof TextElement) { segment = new NormalSegment(entire); } else if (block instanceof CodeElement) { segment = new PreformatSegment(entire); } else if (block instanceof QuoteElement) { segment = new QuoteSegment(entire); } else if (block instanceof PoemElement) { segment = new PoeticSegment(entire); } else if (block instanceof ListElement) { segment = new ListitemSegment(entire, attribute); } else if (block instanceof CreditElement) { segment = new AttributionSegment(entire); } else if (block instanceof HeadingElement) { segment = new HeadingSegment(entire, attribute); } else if (block instanceof ImageElement) { segment = new ImageSegment(entire, attribute); } else if (block instanceof ChapterElement) { segment = new ChapterSegment(entire, attribute); } else if (block instanceof DivisionElement) { segment = new DivisionSegment(entire, attribute); } else if (block instanceof EndnoteElement) { segment = new EndnoteSegment(entire, attribute); } else if (block instanceof ReferenceElement) { segment = new ReferenceSegment(entire, attribute); } else if (block instanceof LeaderElement) { segment = new LeaderSegment(entire); } else if (block instanceof SpecialElement) { segment = new SpecialSegment(attribute); } else { throw new IllegalStateException("\n" + "What kind of Block is " + block); } list.add(segment); } private void processData(final Block block) { final Meta[] data; int i; data = block.getData(); for (i = 0; i < data.length; i++) { processMetadata(data[i]); } } private void processBody(final Block block) { Inline[] elements; int i; elements = block.getBody(); for (i = 0; i < elements.length; i++) { processInline(elements[i]); } } private void processMetadata(final Meta meta) { final String str; if (meta instanceof SourceAttribute) { str = meta.getValue(); attribute = str; } else if (meta instanceof NameAttribute) { str = meta.getValue(); attribute = str; } else if (meta instanceof LabelAttribute) { str = meta.getValue(); attribute = str; } else if (meta instanceof TypeAttribute) { str = meta.getValue(); attribute = str; } else { throw new IllegalStateException("Unknown Meta type"); } } private void processInline(Inline span) { final String str; str = span.getText(); if (span instanceof Normal) { markup = null; processText(str); } else if (span instanceof InlineElement) { if (span instanceof FunctionElement) { markup = Common.FUNCTION; } else if (span instanceof FilenameElement) { markup = Common.FILENAME; } else if (span instanceof TypeElement) { markup = Common.TYPE; } else if (span instanceof LiteralElement) { markup = Common.LITERAL; } else if (span instanceof CommandElement) { markup = Common.COMMAND; } else if (span instanceof HighlightElement) { markup = Common.HIGHLIGHT; } else if (span instanceof TitleElement) { markup = Common.TITLE; } else if (span instanceof KeyboardElement) { markup = Common.KEYBOARD; } else if (span instanceof AcronymElement) { markup = Common.ACRONYM; } else if (span instanceof ProjectElement) { markup = Common.PROJECT; } else if (span instanceof ItalicsElement) { markup = Common.ITALICS; } else if (span instanceof BoldElement) { markup = Common.BOLD; } else { throw new IllegalStateException("Unknown Inline type"); } start = false; processText(str); } else if (span instanceof MarkerElement) { if (span instanceof NoteElement) { markup = Special.NOTE; } else if (span instanceof CiteElement) { markup = Special.CITE; } processMarker(str); } } /* * This will be the contiguous text body of the element until either a) an * nested (inline) element starts, or b) the end of the element is * reached. So we trim off the leading pretty-print whitespace then add a * single StringSpan with this content. */ private void processText(String text) { final String trim, str; int len; char ch; len = text.length(); /* * This case, and the first in the next block, are common for * structure tags */ if (len == 0) { space = false; return; // empty } /* * Check for valid file format: no bare newlines. This is probably * expensive, but we have tests that expect this. */ if ((!preserve) && (len > 1)) { if (text.contains("\n\n")) { throw new IllegalStateException("Can't have bare newlines in normal Blocks"); } } /* * Do we think we're starting a block? If so, trim off the leading * newline. If we're starting an inline and we swollowed a trailing * space from the previous run of text, pad the inline with one space. */ if (start) { start = false; space = false; ch = text.charAt(0); if (ch == '\n') { if (len == 1) { return; // ignore it } text = text.substring(1); len--; } } else if (space) { chain.append(pending); pending = null; } /* * If not preformatted text, turn any interior newlines into spaces, * then add. */ if (preserve) { str = text; } else { str = text.replace('\n', ' '); } /* * Trim the trailing newline (if there is one) as it could be the * break before a close-element tag. We replace it with a space and * prepend it if we find it is just a linebreak separator between a * Text and an Inline when making the next Text node. */ ch = text.charAt(len - 1); if (ch == '\n') { trim = str.substring(0, len - 1); space = true; pending = Span.createSpan(' ', markup); if (len == 1) { return; // captured in pending } len--; } else { trim = str; space = false; } chain.append(createSpan(trim, markup)); } private void processMarker(String str) { chain.append(Span.createMarker(str, markup)); } }
true
true
private void processBlock(Block block) { Extract entire; int i; start = true; chain = new TextChain(); attribute = null; if (block instanceof TextElement) { preserve = false; if (segment instanceof NormalSegment) { entire = segment.getEntire(); chain.setTree(entire); chain.append(Span.createSpan('\n', null)); i = list.size() - 1; list.remove(i); } } else if (block instanceof CodeElement) { preserve = true; } else if (block instanceof QuoteElement) { preserve = false; if (segment instanceof QuoteSegment) { entire = segment.getEntire(); chain.setTree(entire); chain.append(Span.createSpan('\n', null)); i = list.size() - 1; list.remove(i); } } else if (block instanceof PoemElement) { preserve = true; } else if (block instanceof ListElement) { preserve = false; processData(block); if ((attribute == null) && (segment instanceof ListitemSegment)) { entire = segment.getEntire(); chain.setTree(entire); chain.append(Span.createSpan('\n', null)); i = list.size() - 1; list.remove(i); attribute = segment.getImage(); } } else if (block instanceof CreditElement) { preserve = false; if (segment instanceof AttributionSegment) { entire = segment.getEntire(); chain.setTree(entire); chain.append(Span.createSpan('\n', null)); i = list.size() - 1; list.remove(i); } } else if (block instanceof HeadingElement) { preserve = false; processData(block); } else if (block instanceof LeaderElement) { preserve = false; } else if (block instanceof ImageElement) { preserve = false; processData(block); } else if ((block instanceof ChapterElement) || (block instanceof DivisionElement)) { preserve = false; if (segment != null) { throw new IllegalStateException("\n" + "A <chapter> must be the first block in a Quack file."); } processData(block); } else if (block instanceof EndnoteElement) { preserve = false; processData(block); } else if (block instanceof ReferenceElement) { preserve = false; processData(block); } else if (block instanceof SpecialElement) { preserve = false; processData(block); } else { throw new IllegalStateException("\n" + "What kind of Block is " + block); } /* * Now iterate over the text and Inlines of the Block, accumulating * into the TextChain. */ processBody(block); /* * With that done, form the [immutable] Segment based on the * accumulated data. */ entire = chain.extractAll(); if (block instanceof TextElement) { segment = new NormalSegment(entire); } else if (block instanceof CodeElement) { segment = new PreformatSegment(entire); } else if (block instanceof QuoteElement) { segment = new QuoteSegment(entire); } else if (block instanceof PoemElement) { segment = new PoeticSegment(entire); } else if (block instanceof ListElement) { segment = new ListitemSegment(entire, attribute); } else if (block instanceof CreditElement) { segment = new AttributionSegment(entire); } else if (block instanceof HeadingElement) { segment = new HeadingSegment(entire, attribute); } else if (block instanceof ImageElement) { segment = new ImageSegment(entire, attribute); } else if (block instanceof ChapterElement) { segment = new ChapterSegment(entire, attribute); } else if (block instanceof DivisionElement) { segment = new DivisionSegment(entire, attribute); } else if (block instanceof EndnoteElement) { segment = new EndnoteSegment(entire, attribute); } else if (block instanceof ReferenceElement) { segment = new ReferenceSegment(entire, attribute); } else if (block instanceof LeaderElement) { segment = new LeaderSegment(entire); } else if (block instanceof SpecialElement) { segment = new SpecialSegment(attribute); } else { throw new IllegalStateException("\n" + "What kind of Block is " + block); } list.add(segment); }
private void processBlock(Block block) { Extract entire; int i; start = true; chain = new TextChain(); attribute = null; if (block instanceof TextElement) { preserve = false; if (segment instanceof NormalSegment) { entire = segment.getEntire(); chain.setTree(entire); chain.append(Span.createSpan('\n', null)); i = list.size() - 1; list.remove(i); } } else if (block instanceof CodeElement) { preserve = true; } else if (block instanceof QuoteElement) { preserve = false; if (segment instanceof QuoteSegment) { entire = segment.getEntire(); chain.setTree(entire); chain.append(Span.createSpan('\n', null)); i = list.size() - 1; list.remove(i); } } else if (block instanceof PoemElement) { preserve = true; } else if (block instanceof ListElement) { preserve = false; processData(block); if ((attribute == null) && (segment instanceof ListitemSegment)) { entire = segment.getEntire(); chain.setTree(entire); chain.append(Span.createSpan('\n', null)); i = list.size() - 1; list.remove(i); attribute = segment.getImage(); } } else if (block instanceof CreditElement) { preserve = false; if (segment instanceof AttributionSegment) { entire = segment.getEntire(); chain.setTree(entire); chain.append(Span.createSpan('\n', null)); i = list.size() - 1; list.remove(i); } } else if (block instanceof HeadingElement) { preserve = false; processData(block); } else if (block instanceof LeaderElement) { preserve = false; } else if (block instanceof ImageElement) { preserve = false; processData(block); } else if ((block instanceof ChapterElement) || (block instanceof DivisionElement)) { preserve = false; if (segment != null) { throw new IllegalStateException("\n" + "A " + block.toString() + " must be the first block in a Quack file."); } processData(block); } else if (block instanceof EndnoteElement) { preserve = false; processData(block); } else if (block instanceof ReferenceElement) { preserve = false; processData(block); } else if (block instanceof SpecialElement) { preserve = false; processData(block); } else { throw new IllegalStateException("\n" + "What kind of Block is " + block); } /* * Now iterate over the text and Inlines of the Block, accumulating * into the TextChain. */ processBody(block); /* * With that done, form the [immutable] Segment based on the * accumulated data. */ entire = chain.extractAll(); if (block instanceof TextElement) { segment = new NormalSegment(entire); } else if (block instanceof CodeElement) { segment = new PreformatSegment(entire); } else if (block instanceof QuoteElement) { segment = new QuoteSegment(entire); } else if (block instanceof PoemElement) { segment = new PoeticSegment(entire); } else if (block instanceof ListElement) { segment = new ListitemSegment(entire, attribute); } else if (block instanceof CreditElement) { segment = new AttributionSegment(entire); } else if (block instanceof HeadingElement) { segment = new HeadingSegment(entire, attribute); } else if (block instanceof ImageElement) { segment = new ImageSegment(entire, attribute); } else if (block instanceof ChapterElement) { segment = new ChapterSegment(entire, attribute); } else if (block instanceof DivisionElement) { segment = new DivisionSegment(entire, attribute); } else if (block instanceof EndnoteElement) { segment = new EndnoteSegment(entire, attribute); } else if (block instanceof ReferenceElement) { segment = new ReferenceSegment(entire, attribute); } else if (block instanceof LeaderElement) { segment = new LeaderSegment(entire); } else if (block instanceof SpecialElement) { segment = new SpecialSegment(attribute); } else { throw new IllegalStateException("\n" + "What kind of Block is " + block); } list.add(segment); }
diff --git a/javasrc/src/org/ccnx/ccn/impl/repo/RepositoryInterestHandler.java b/javasrc/src/org/ccnx/ccn/impl/repo/RepositoryInterestHandler.java index 0e1e0d0ad..268b5bc9c 100644 --- a/javasrc/src/org/ccnx/ccn/impl/repo/RepositoryInterestHandler.java +++ b/javasrc/src/org/ccnx/ccn/impl/repo/RepositoryInterestHandler.java @@ -1,279 +1,280 @@ /** * Part of the CCNx Java Library. * * Copyright (C) 2008, 2009 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.impl.repo; import java.io.IOException; import java.util.ArrayList; import java.util.logging.Level; import org.ccnx.ccn.CCNFilterListener; import org.ccnx.ccn.CCNHandle; import org.ccnx.ccn.impl.repo.RepositoryInfo.RepositoryInfoObject; import org.ccnx.ccn.impl.support.Log; import org.ccnx.ccn.io.content.ContentEncodingException; import org.ccnx.ccn.profiles.CommandMarker; import org.ccnx.ccn.profiles.nameenum.NameEnumerationResponse; import org.ccnx.ccn.protocol.ContentName; import org.ccnx.ccn.protocol.ContentObject; import org.ccnx.ccn.protocol.Interest; /** * Handles interests matching the repository's namespace. * * @see RepositoryServer * @see RepositoryFlowControl * @see RepositoryDataListener */ public class RepositoryInterestHandler implements CCNFilterListener { private RepositoryServer _server; private CCNHandle _handle; public RepositoryInterestHandler(RepositoryServer server) { _server = server; _handle = server.getHandle(); } /** * Parse incoming interests for type and dispatch those dedicated to some special purpose. * Interests can be to start a write or a name enumeration request. * If the interest has no special purpose, its assumed that it's to actually read data from * the repository and the request is sent to the RepositoryStore to be processed. */ public boolean handleInterest(Interest interest) { if (Log.isLoggable(Log.FAC_REPO, Level.FINER)) Log.finer(Log.FAC_REPO, "Saw interest: {0}", interest.name()); try { int pos = -1; if (interest.name().contains(CommandMarker.COMMAND_MARKER_REPO_START_WRITE.getBytes())) { if (!allowGenerated(interest)) return true; startWrite(interest); } else if (interest.name().contains(CommandMarker.COMMAND_MARKER_BASIC_ENUMERATION.getBytes())) { if (!allowGenerated(interest)) return true; nameEnumeratorResponse(interest); } else if ((pos = interest.name().whereLast(CommandMarker.COMMAND_MARKER_REPO_CHECKED_START_WRITE.getBytes())) >= 0) { if (!allowGenerated(interest)) return true; startWriteChecked(interest, pos); } else { ContentObject content = _server.getRepository().getContent(interest); if (content != null) { if (Log.isLoggable(Log.FAC_REPO, Level.FINEST)) Log.finest(Log.FAC_REPO, "Satisfying interest: {0} with content {1}", interest, content.name()); _handle.put(content); } else { if (Log.isLoggable(Log.FAC_REPO, Level.FINE)) Log.fine(Log.FAC_REPO, "Unsatisfied interest: {0}", interest); } } } catch (Exception e) { Log.logStackTrace(Level.WARNING, e); e.printStackTrace(); } return true; } protected boolean allowGenerated(Interest interest) { if (null != interest.answerOriginKind() && (interest.answerOriginKind() & Interest.ANSWER_GENERATED) == 0) return false; // Request to not answer else return true; } /** * Check for duplicate request, i.e. request already in process * Logs the request if found to be a duplicate. * @param interest the incoming interest containing the request command * @return true if request is duplicate */ protected boolean isDuplicateRequest(Interest interest) { synchronized (_server.getDataListeners()) { for (RepositoryDataListener listener : _server.getDataListeners()) { if (listener.getOrigInterest().equals(interest)) { if (Log.isLoggable(Log.FAC_REPO, Level.INFO)) Log.info(Log.FAC_REPO, "Request {0} is a duplicate, ignoring", interest.name()); return true; } } } return false; } /** * Check whether new writes are allowed now * Logs the discarded request if it cannot be processed * @param interest the incoming interest containing the command * @return true if writes are presently suspended */ protected boolean isWriteSuspended(Interest interest) { // For now we need to wait until all current sessions are complete before a namespace // change which will reset the filters is allowed. So for now, we just don't allow any // new sessions to start until a pending namespace change is complete to allow there to // be space for this to actually happen. In theory we should probably figure out a way // to allow new sessions that are within the new namespace to start but figuring out all // the locking/startup issues surrounding this is complex so for now we just don't allow it. if (_server.getPendingNameSpaceState()) { if (Log.isLoggable(Log.FAC_REPO, Level.INFO)) Log.info(Log.FAC_REPO, "Discarding write request {0} due to pending namespace change", interest.name()); return true; } return false; } /** * Handle start write requests * * @param interest */ private void startWrite(Interest interest) { if (isDuplicateRequest(interest)) return; if (isWriteSuspended(interest)) return; // Create the name for the initial interest to retrieve content from the client that it desires to // write. Strip from the write request name (in the incoming Interest) the start write command component // and the nonce component to get the prefix for the content to be written. ContentName listeningName = new ContentName(interest.name().count() - 2, interest.name().components()); try { if (Log.isLoggable(Log.FAC_REPO, Level.INFO)) Log.info(Log.FAC_REPO, "Processing write request for {0}", listeningName); // Create the initial read interest. Set maxSuffixComponents = 2 to get only content with one // component past the prefix, plus the implicit digest. This is designed to retrieve segments // of a stream and avoid other content more levels below in the name space. We do not ask for // a specific segment initially so as to support arbitrary starting segment numbers. // TODO use better exclude filters to ensure we're only getting segments. Interest readInterest = Interest.constructInterest(listeningName, _server.getExcludes(), null, 2, null, null); RepositoryDataListener listener; RepositoryInfoObject rio = _server.getRepository().getRepoInfo(interest.name(), null); if (null == rio) return; // Should have logged an error in getRepoInfo // Hand the object the outstanding interest, so it can put its first block immediately. rio.save(interest); // Check for special case file written to repo ContentName globalPrefix = _server.getRepository().getGlobalPrefix(); String localName = _server.getRepository().getLocalName(); if (BasicPolicy.getPolicyName(globalPrefix, localName).isPrefixOf(listeningName)) { new RepositoryPolicyHandler(interest, readInterest, _server); return; } listener = new RepositoryDataListener(interest, readInterest, _server); _server.addListener(listener); listener.getInterests().add(readInterest, null); _handle.expressInterest(readInterest, listener); } catch (Exception e) { Log.logStackTrace(Level.WARNING, e); e.printStackTrace(); } } /** * Handle requests to check for specific stream content and read and store it if not * already present. * @param interest the interest containing the request * @param pos index of the command marker in the interest name * @throws RepositoryException * @throws ContentEncodingException * @throws IOException */ private void startWriteChecked(Interest interest, int pos) { if (isDuplicateRequest(interest)) return; if (isWriteSuspended(interest)) return; try { Log.finer(Log.FAC_REPO, "Repo checked write request: {0}", interest.name()); ContentName orig = interest.name(); if (pos+3 >= orig.count()) { Log.warning(Log.FAC_REPO, "Repo checked write malformed request {0}", interest.name()); + return; } // Strip out the command marker and nonce so we get name with those components removed from middle ContentName head = orig.subname(0, pos); ContentName tail = orig.subname(pos+2, orig.count()-pos-2); ContentName target = head.append(tail); boolean verified = false; RepositoryInfoObject rio = null; if (_server.getRepository().hasContent(target)) { // First impl, no further checks, if we have first segment, assume we have (or are fetching) // the whole thing // TODO: add better verification: // find highest segment in the store (probably a new internal interest seeking rightmost) // getContent(): need full object in this case, verify that last segment matches segment name => verified = true verified = true; // Send back a RepositoryInfoObject that contains a confirmation that content is already in repo ArrayList<ContentName> target_names = new ArrayList<ContentName>(); target_names.add(target); rio = _server.getRepository().getRepoInfo(interest.name(), target_names); } else { // Send back response that does not confirm content rio = _server.getRepository().getRepoInfo(interest.name(), null); } if (null == rio) return; // Should have logged an error in getRepoInfo // Hand the object the outstanding interest, so it can put its first block immediately. rio.save(interest); if (!verified) { Log.finer(Log.FAC_REPO, "Repo checked write no content for {0}, starting read", interest.name()); // Create the initial read interest. Set maxSuffixComponents = minSuffixComponents = 0 // because in this SPECIAL CASE we have the complete name of the first segment. Interest readInterest = Interest.constructInterest(target, _server.getExcludes(), null, 0, 0, null); RepositoryDataListener listener; // SPECIAL CASE: this initial interest is more specific than the standard reading interests, so // it will not be recognized as requesting a specific segment (segment is not final component). // However, until this initial interest is satisfied, there is no processing requiring standard // segment format, and when the first (satisfying) data arrives this interest will be immediately // discarded. The returned data (ContentObject) explicit name will never include the implicit // digest and so is processed correctly regardless of the interest that retrieved it. listener = new RepositoryDataListener(interest, readInterest, _server); _server.addListener(listener); listener.getInterests().add(readInterest, null); _handle.expressInterest(readInterest, listener); } else { Log.finer(Log.FAC_REPO, "Repo checked write content verified for {0}", interest.name()); } } catch (Exception e) { Log.logStackTrace(Level.WARNING, e); e.printStackTrace(); } } /** * Handle name enumeration requests * * @param interest */ public void nameEnumeratorResponse(Interest interest) { NameEnumerationResponse ner = _server.getRepository().getNamesWithPrefix(interest, _server.getResponseName()); if (ner!=null && ner.hasNames()) { _server.sendEnumerationResponse(ner); if (Log.isLoggable(Log.FAC_REPO, Level.FINE)) Log.fine(Log.FAC_REPO, "sending back name enumeration response {0}", ner.getPrefix()); } else { if (Log.isLoggable(Log.FAC_REPO, Level.FINE)) Log.fine(Log.FAC_REPO, "we are not sending back a response to the name enumeration interest (interest.name() = {0})", interest.name()); } } }
true
true
private void startWriteChecked(Interest interest, int pos) { if (isDuplicateRequest(interest)) return; if (isWriteSuspended(interest)) return; try { Log.finer(Log.FAC_REPO, "Repo checked write request: {0}", interest.name()); ContentName orig = interest.name(); if (pos+3 >= orig.count()) { Log.warning(Log.FAC_REPO, "Repo checked write malformed request {0}", interest.name()); } // Strip out the command marker and nonce so we get name with those components removed from middle ContentName head = orig.subname(0, pos); ContentName tail = orig.subname(pos+2, orig.count()-pos-2); ContentName target = head.append(tail); boolean verified = false; RepositoryInfoObject rio = null; if (_server.getRepository().hasContent(target)) { // First impl, no further checks, if we have first segment, assume we have (or are fetching) // the whole thing // TODO: add better verification: // find highest segment in the store (probably a new internal interest seeking rightmost) // getContent(): need full object in this case, verify that last segment matches segment name => verified = true verified = true; // Send back a RepositoryInfoObject that contains a confirmation that content is already in repo ArrayList<ContentName> target_names = new ArrayList<ContentName>(); target_names.add(target); rio = _server.getRepository().getRepoInfo(interest.name(), target_names); } else { // Send back response that does not confirm content rio = _server.getRepository().getRepoInfo(interest.name(), null); } if (null == rio) return; // Should have logged an error in getRepoInfo // Hand the object the outstanding interest, so it can put its first block immediately. rio.save(interest); if (!verified) { Log.finer(Log.FAC_REPO, "Repo checked write no content for {0}, starting read", interest.name()); // Create the initial read interest. Set maxSuffixComponents = minSuffixComponents = 0 // because in this SPECIAL CASE we have the complete name of the first segment. Interest readInterest = Interest.constructInterest(target, _server.getExcludes(), null, 0, 0, null); RepositoryDataListener listener; // SPECIAL CASE: this initial interest is more specific than the standard reading interests, so // it will not be recognized as requesting a specific segment (segment is not final component). // However, until this initial interest is satisfied, there is no processing requiring standard // segment format, and when the first (satisfying) data arrives this interest will be immediately // discarded. The returned data (ContentObject) explicit name will never include the implicit // digest and so is processed correctly regardless of the interest that retrieved it. listener = new RepositoryDataListener(interest, readInterest, _server); _server.addListener(listener); listener.getInterests().add(readInterest, null); _handle.expressInterest(readInterest, listener); } else { Log.finer(Log.FAC_REPO, "Repo checked write content verified for {0}", interest.name()); } } catch (Exception e) { Log.logStackTrace(Level.WARNING, e); e.printStackTrace(); } }
private void startWriteChecked(Interest interest, int pos) { if (isDuplicateRequest(interest)) return; if (isWriteSuspended(interest)) return; try { Log.finer(Log.FAC_REPO, "Repo checked write request: {0}", interest.name()); ContentName orig = interest.name(); if (pos+3 >= orig.count()) { Log.warning(Log.FAC_REPO, "Repo checked write malformed request {0}", interest.name()); return; } // Strip out the command marker and nonce so we get name with those components removed from middle ContentName head = orig.subname(0, pos); ContentName tail = orig.subname(pos+2, orig.count()-pos-2); ContentName target = head.append(tail); boolean verified = false; RepositoryInfoObject rio = null; if (_server.getRepository().hasContent(target)) { // First impl, no further checks, if we have first segment, assume we have (or are fetching) // the whole thing // TODO: add better verification: // find highest segment in the store (probably a new internal interest seeking rightmost) // getContent(): need full object in this case, verify that last segment matches segment name => verified = true verified = true; // Send back a RepositoryInfoObject that contains a confirmation that content is already in repo ArrayList<ContentName> target_names = new ArrayList<ContentName>(); target_names.add(target); rio = _server.getRepository().getRepoInfo(interest.name(), target_names); } else { // Send back response that does not confirm content rio = _server.getRepository().getRepoInfo(interest.name(), null); } if (null == rio) return; // Should have logged an error in getRepoInfo // Hand the object the outstanding interest, so it can put its first block immediately. rio.save(interest); if (!verified) { Log.finer(Log.FAC_REPO, "Repo checked write no content for {0}, starting read", interest.name()); // Create the initial read interest. Set maxSuffixComponents = minSuffixComponents = 0 // because in this SPECIAL CASE we have the complete name of the first segment. Interest readInterest = Interest.constructInterest(target, _server.getExcludes(), null, 0, 0, null); RepositoryDataListener listener; // SPECIAL CASE: this initial interest is more specific than the standard reading interests, so // it will not be recognized as requesting a specific segment (segment is not final component). // However, until this initial interest is satisfied, there is no processing requiring standard // segment format, and when the first (satisfying) data arrives this interest will be immediately // discarded. The returned data (ContentObject) explicit name will never include the implicit // digest and so is processed correctly regardless of the interest that retrieved it. listener = new RepositoryDataListener(interest, readInterest, _server); _server.addListener(listener); listener.getInterests().add(readInterest, null); _handle.expressInterest(readInterest, listener); } else { Log.finer(Log.FAC_REPO, "Repo checked write content verified for {0}", interest.name()); } } catch (Exception e) { Log.logStackTrace(Level.WARNING, e); e.printStackTrace(); } }
diff --git a/jetty-nosql/src/test/java/org/eclipse/jetty/nosql/mongodb/MongoTestServer.java b/jetty-nosql/src/test/java/org/eclipse/jetty/nosql/mongodb/MongoTestServer.java index 5bda287bf..269cf4c71 100644 --- a/jetty-nosql/src/test/java/org/eclipse/jetty/nosql/mongodb/MongoTestServer.java +++ b/jetty-nosql/src/test/java/org/eclipse/jetty/nosql/mongodb/MongoTestServer.java @@ -1,137 +1,137 @@ package org.eclipse.jetty.nosql.mongodb; // ======================================================================== // Copyright (c) 1996-2009 Mort Bay Consulting Pty. Ltd. // ------------------------------------------------------------------------ // All rights reserved. This program and the accompanying materials // are made available under the terms of the Eclipse Public License v1.0 // and Apache License v2.0 which accompanies this distribution. // The Eclipse Public License is available at // http://www.eclipse.org/legal/epl-v10.html // The Apache License v2.0 is available at // http://www.opensource.org/licenses/apache2.0.php // You may elect to redistribute this code under either of these licenses. // ======================================================================== import java.util.concurrent.TimeUnit; import org.eclipse.jetty.nosql.mongodb.MongoSessionIdManager; import org.eclipse.jetty.nosql.mongodb.MongoSessionManager; import org.eclipse.jetty.server.SessionIdManager; import org.eclipse.jetty.server.SessionManager; import org.eclipse.jetty.server.session.AbstractTestServer; import org.eclipse.jetty.server.session.SessionHandler; /** * @version $Revision$ $Date$ */ public class MongoTestServer extends AbstractTestServer { static MongoSessionIdManager _idManager; private boolean _saveAllAttributes = false; // false save dirty, true save all public MongoTestServer(int port) { super(port, 30, 10); } public MongoTestServer(int port, int maxInactivePeriod, int scavengePeriod) { super(port, maxInactivePeriod, scavengePeriod); } public MongoTestServer(int port, int maxInactivePeriod, int scavengePeriod, boolean saveAllAttributes) { super(port, maxInactivePeriod, scavengePeriod); _saveAllAttributes = saveAllAttributes; } - public SessionIdManager newSessionIdManager() + public SessionIdManager newSessionIdManager(String config) { if ( _idManager != null ) { try { _idManager.stop(); } catch (Exception e) { e.printStackTrace(); } _idManager.setScavengeDelay(_scavengePeriod + 1000); _idManager.setScavengePeriod(_maxInactivePeriod); try { _idManager.start(); } catch (Exception e) { e.printStackTrace(); } return _idManager; } try { System.err.println("MongoTestServer:SessionIdManager:" + _maxInactivePeriod + "/" + _scavengePeriod); _idManager = new MongoSessionIdManager(_server); _idManager.setScavengeDelay((int)TimeUnit.SECONDS.toMillis(_scavengePeriod)); _idManager.setScavengePeriod(_maxInactivePeriod); return _idManager; } catch (Exception e) { throw new IllegalStateException(); } } public SessionManager newSessionManager() { MongoSessionManager manager; try { manager = new MongoSessionManager(); } catch (Exception e) { throw new RuntimeException(e); } manager.setSavePeriod(1); manager.setStalePeriod(0); manager.setSaveAllAttributes(_saveAllAttributes); //manager.setScavengePeriod((int)TimeUnit.SECONDS.toMillis(_scavengePeriod)); return manager; } public SessionHandler newSessionHandler(SessionManager sessionManager) { return new SessionHandler(sessionManager); } public static void main(String... args) throws Exception { MongoTestServer server8080 = new MongoTestServer(8080); server8080.addContext("/").addServlet(SessionDump.class,"/"); server8080.start(); MongoTestServer server8081 = new MongoTestServer(8081); server8081.addContext("/").addServlet(SessionDump.class,"/"); server8081.start(); server8080.join(); server8081.join(); } }
true
true
public SessionIdManager newSessionIdManager() { if ( _idManager != null ) { try { _idManager.stop(); } catch (Exception e) { e.printStackTrace(); } _idManager.setScavengeDelay(_scavengePeriod + 1000); _idManager.setScavengePeriod(_maxInactivePeriod); try { _idManager.start(); } catch (Exception e) { e.printStackTrace(); } return _idManager; } try { System.err.println("MongoTestServer:SessionIdManager:" + _maxInactivePeriod + "/" + _scavengePeriod); _idManager = new MongoSessionIdManager(_server); _idManager.setScavengeDelay((int)TimeUnit.SECONDS.toMillis(_scavengePeriod)); _idManager.setScavengePeriod(_maxInactivePeriod); return _idManager; } catch (Exception e) { throw new IllegalStateException(); } }
public SessionIdManager newSessionIdManager(String config) { if ( _idManager != null ) { try { _idManager.stop(); } catch (Exception e) { e.printStackTrace(); } _idManager.setScavengeDelay(_scavengePeriod + 1000); _idManager.setScavengePeriod(_maxInactivePeriod); try { _idManager.start(); } catch (Exception e) { e.printStackTrace(); } return _idManager; } try { System.err.println("MongoTestServer:SessionIdManager:" + _maxInactivePeriod + "/" + _scavengePeriod); _idManager = new MongoSessionIdManager(_server); _idManager.setScavengeDelay((int)TimeUnit.SECONDS.toMillis(_scavengePeriod)); _idManager.setScavengePeriod(_maxInactivePeriod); return _idManager; } catch (Exception e) { throw new IllegalStateException(); } }
diff --git a/module-api/src/test/java/org/xbrlapi/fragment/tests/EntityTestCase.java b/module-api/src/test/java/org/xbrlapi/fragment/tests/EntityTestCase.java index 3ab09984..d1b36f8f 100644 --- a/module-api/src/test/java/org/xbrlapi/fragment/tests/EntityTestCase.java +++ b/module-api/src/test/java/org/xbrlapi/fragment/tests/EntityTestCase.java @@ -1,59 +1,59 @@ package org.xbrlapi.fragment.tests; import java.util.List; import org.xbrlapi.DOMLoadingTestCase; import org.xbrlapi.Entity; /** * Tests the implementation of the org.xbrlapi.Entity interface. * Uses the DOM-based data store to ensure rapid testing. * @author Geoffrey Shuetrim ([email protected]) */ public class EntityTestCase extends DOMLoadingTestCase { private final String STARTING_POINT = "test.data.segments"; protected void setUp() throws Exception { super.setUp(); loader.discover(this.getURI(STARTING_POINT)); } protected void tearDown() throws Exception { super.tearDown(); } public EntityTestCase(String arg0) { super(arg0); } /** * Test getting the scenario. */ public void testGetScenario() { try { List<Entity> entities = store.<Entity>getXMLResources("Entity"); assertTrue(entities.size() > 0); for (Entity entity: entities) { assertEquals("org.xbrlapi.impl.SegmentImpl", entity.getSegment().getType()); } } catch (Exception e) { fail(e.getMessage()); } } /** * Test getting the identifier information. */ public void testGetSchemeAndValue() { try { List<Entity> entities = store.<Entity>getXMLResources("Entity"); assertTrue(entities.size() > 0); for (Entity entity: entities) { - assertEquals("www.dnb.com", entity.getIdentifierScheme()); + assertEquals("www.dnb.com", entity.getIdentifierScheme().toString()); assertEquals("121064880", entity.getIdentifierValue()); } } catch (Exception e) { fail(e.getMessage()); } } }
true
true
public void testGetSchemeAndValue() { try { List<Entity> entities = store.<Entity>getXMLResources("Entity"); assertTrue(entities.size() > 0); for (Entity entity: entities) { assertEquals("www.dnb.com", entity.getIdentifierScheme()); assertEquals("121064880", entity.getIdentifierValue()); } } catch (Exception e) { fail(e.getMessage()); } }
public void testGetSchemeAndValue() { try { List<Entity> entities = store.<Entity>getXMLResources("Entity"); assertTrue(entities.size() > 0); for (Entity entity: entities) { assertEquals("www.dnb.com", entity.getIdentifierScheme().toString()); assertEquals("121064880", entity.getIdentifierValue()); } } catch (Exception e) { fail(e.getMessage()); } }
diff --git a/src/eu/cassandra/sim/Simulation.java b/src/eu/cassandra/sim/Simulation.java index c09f4d6..5460ff8 100644 --- a/src/eu/cassandra/sim/Simulation.java +++ b/src/eu/cassandra/sim/Simulation.java @@ -1,832 +1,833 @@ /* Copyright 2011-2013 The Cassandra Consortium (cassandra-fp7.eu) 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 eu.cassandra.sim; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.util.Calendar; import java.util.Collection; import java.util.HashMap; import java.util.Set; import java.util.Vector; import java.util.concurrent.PriorityBlockingQueue; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import javax.servlet.ServletContext; import org.apache.log4j.Logger; import org.bson.types.ObjectId; import com.mongodb.BasicDBList; import com.mongodb.BasicDBObject; import com.mongodb.DBObject; import com.mongodb.util.JSON; import eu.cassandra.server.mongo.MongoActivityModels; import eu.cassandra.server.mongo.MongoDistributions; import eu.cassandra.server.mongo.MongoResults; import eu.cassandra.server.mongo.MongoRuns; import eu.cassandra.server.mongo.util.DBConn; import eu.cassandra.sim.entities.Entity; import eu.cassandra.sim.entities.appliances.Appliance; import eu.cassandra.sim.entities.appliances.ConsumptionModel; import eu.cassandra.sim.entities.external.ThermalModule; import eu.cassandra.sim.entities.installations.Installation; import eu.cassandra.sim.entities.people.Activity; import eu.cassandra.sim.entities.people.Person; import eu.cassandra.sim.math.Gaussian; import eu.cassandra.sim.math.GaussianMixtureModels; import eu.cassandra.sim.math.Histogram; import eu.cassandra.sim.math.ProbabilityDistribution; import eu.cassandra.sim.math.Uniform; import eu.cassandra.sim.utilities.Constants; import eu.cassandra.sim.utilities.ORNG; import eu.cassandra.sim.utilities.Utils; /** * The Simulation class can simulate up to 4085 years of simulation. * * @author Kyriakos C. Chatzidimitriou (kyrcha [at] iti [dot] gr) * */ public class Simulation implements Runnable { static Logger logger = Logger.getLogger(Simulation.class); private Vector<Installation> installations; private PriorityBlockingQueue<Event> queue; private int tick; private int endTick; private int mcruns; private double co2; private MongoResults m; private SimulationParams simulationWorld; private PricingPolicy pricing; private PricingPolicy baseline_pricing; private String scenario; private String dbname; private String resources_path; private ORNG orng; public Collection<Installation> getInstallations () { return installations; } public Installation getInstallation (int index) { return installations.get(index); } public int getCurrentTick () { return tick; } public int getEndTick () { return endTick; } public Simulation(String ascenario, String adbname, String aresources_path, int seed) { scenario = ascenario; dbname = adbname; resources_path = aresources_path; m = new MongoResults(dbname); m.createIndexes(); if(seed > 0) { orng = new ORNG(seed); } else { orng = new ORNG(); } } public SimulationParams getSimulationWorld () { return simulationWorld; } public void run () { DBObject query = new BasicDBObject(); query.put("_id", new ObjectId(dbname)); DBObject objRun = DBConn.getConn().getCollection(MongoRuns.COL_RUNS).findOne(query); try { System.out.println("Run " + dbname + " started @ " + Calendar.getInstance().getTimeInMillis()); calculateExpectedPower(dbname); long startTime = System.currentTimeMillis(); int percentage = 0; int mccount = 0; double mcrunsRatio = 1.0/(double)mcruns; for(int i = 0; i < mcruns; i++) { tick = 0; double avgPPowerPerHour = 0; double avgQPowerPerHour = 0; double[] avgPPowerPerHourPerInst = new double[installations.size()]; double[] avgQPowerPerHourPerInst = new double[installations.size()]; double maxPower = 0; // double cycleMaxPower = 0; double avgPower = 0; double energy = 0; double energyOffpeak = 0; double cost = 0; // double billingCycleEnergy = 0; // double billingCycleEnergyOffpeak = 0; while (tick < endTick) { // If it is the beginning of the day create the events if (tick % Constants.MIN_IN_DAY == 0) { // System.out.println("Day " + ((tick / Constants.MIN_IN_DAY) + 1)); for (Installation installation: installations) { // System.out.println(installation.getName()); installation.updateDailySchedule(tick, queue, simulationWorld.getResponseType(), orng); } // System.out.println("Daily queue size: " + queue.size() + "(" + // simulationWorld.getSimCalendar().isWeekend(tick) + ")"); } Event top = queue.peek(); while (top != null && top.getTick() == tick) { Event e = queue.poll(); boolean applied = e.apply(); if(applied) { if(e.getAction() == Event.SWITCH_ON) { try { //m.addOpenTick(e.getAppliance().getId(), tick); } catch (Exception exc) { throw exc; } } else if(e.getAction() == Event.SWITCH_OFF){ //m.addCloseTick(e.getAppliance().getId(), tick); } } top = queue.peek(); } /* * Calculate the total power for this simulation step for all the * installations. */ float sumP = 0; float sumQ = 0; int counter = 0; for(Installation installation: installations) { installation.nextStep(tick); double p = installation.getCurrentPowerP(); double q = installation.getCurrentPowerQ(); // if(p> 0.001) System.out.println(p); installation.updateMaxPower(p); installation.updateAvgPower(p/endTick); if(installation.getPricing().isOffpeak(tick)) { installation.updateEnergyOffpeak(p); } else { installation.updateEnergy(p); } installation.updateAppliancesAndActivitiesConsumptions(tick, endTick); m.addTickResultForInstallation(tick, installation.getId(), p * mcrunsRatio, q * mcrunsRatio, MongoResults.COL_INSTRESULTS); sumP += p; sumQ += q; avgPPowerPerHour += p; avgQPowerPerHour += q; avgPPowerPerHourPerInst[counter] += p; avgQPowerPerHourPerInst[counter] += q; String name = installation.getName(); // logger.info("Tick: " + tick + " \t " + "Name: " + name + " \t " // + "Power: " + power); // System.out.println("Tick: " + tick + " \t " + "Name: " + name + " \t " // + "Power: " + p); if((tick + 1) % (Constants.MIN_IN_DAY * installation.getPricing().getBillingCycle()) == 0 || installation.getPricing().getType().equalsIgnoreCase("TOUPricing")) { installation.updateCost(tick); } counter++; } if(sumP > maxPower) maxPower = sumP; // if(sumP > cycleMaxPower) cycleMaxPower = sumP; avgPower += sumP/endTick; + energy += (sumP/1000.0) * Constants.MINUTE_HOUR_RATIO; // if(pricing.isOffpeak(tick)) { // energyOffpeak += (sumP/1000.0) * Constants.MINUTE_HOUR_RATIO; // } else { // energy += (sumP/1000.0) * Constants.MINUTE_HOUR_RATIO; // } // if((tick + 1) % (Constants.MIN_IN_DAY * pricing.getBillingCycle()) == 0 || pricing.getType().equalsIgnoreCase("TOUPricing")) { // cost = totalInstCost(); //alternate method // billingCycleEnergy = totalInstEnergy(); // billingCycleEnergyOffpeak = totalInstOffpeak(); // cycleMaxPower = 0; // } m.addAggregatedTickResult(tick, sumP * mcrunsRatio, sumQ * mcrunsRatio, MongoResults.COL_AGGRRESULTS); tick++; if(tick % Constants.MIN_IN_HOUR == 0) { m.addAggregatedTickResult((tick/Constants.MIN_IN_HOUR), (avgPPowerPerHour/Constants.MIN_IN_HOUR) * mcrunsRatio, (avgQPowerPerHour/Constants.MIN_IN_HOUR) * mcrunsRatio, MongoResults.COL_AGGRRESULTS_HOURLY); m.addAggregatedTickResult((tick/Constants.MIN_IN_HOUR), (avgPPowerPerHour) * mcrunsRatio, (avgQPowerPerHour) * mcrunsRatio, MongoResults.COL_AGGRRESULTS_HOURLY_EN); avgPPowerPerHour = 0; avgQPowerPerHour = 0; counter = 0; for(Installation installation: installations) { m.addTickResultForInstallation((tick/Constants.MIN_IN_HOUR), installation.getId(), (avgPPowerPerHourPerInst[counter]/Constants.MIN_IN_HOUR) * mcrunsRatio, (avgQPowerPerHourPerInst[counter]/Constants.MIN_IN_HOUR) * mcrunsRatio, MongoResults.COL_INSTRESULTS_HOURLY); m.addTickResultForInstallation((tick/Constants.MIN_IN_HOUR), installation.getId(), (avgPPowerPerHourPerInst[counter]) * mcrunsRatio, (avgQPowerPerHourPerInst[counter]) * mcrunsRatio, MongoResults.COL_INSTRESULTS_HOURLY_EN); avgPPowerPerHourPerInst[counter] = 0; avgQPowerPerHourPerInst[counter] = 0; counter++; } } mccount++; percentage = (int)(0.75 * mccount * 100.0 / (mcruns * endTick)); objRun.put("percentage", 25 + percentage); DBConn.getConn().getCollection(MongoRuns.COL_RUNS).update(query, objRun); } for(Installation installation: installations) { installation.updateCost(tick); // update the rest of the energy m.addKPIs(installation.getId(), installation.getMaxPower() * mcrunsRatio, installation.getAvgPower() * mcrunsRatio, installation.getEnergy() * mcrunsRatio, installation.getCost() * mcrunsRatio, installation.getEnergy() * co2 * mcrunsRatio); installation.addAppliancesKPIs(m, mcrunsRatio, co2); installation.addActivitiesKPIs(m, mcrunsRatio, co2); } cost = totalInstCost(); m.addKPIs(MongoResults.AGGR, maxPower * mcrunsRatio, avgPower * mcrunsRatio, energy * mcrunsRatio, cost * mcrunsRatio, energy * co2 * mcrunsRatio); if(i+1 != mcruns) setup(true); } // Write installation results to csv file String filename = resources_path + "/csvs/" + dbname + ".csv"; System.out.println(filename); File csvFile = new File(filename); FileWriter fw = new FileWriter(csvFile); String row = "tick"; for(Installation installation: installations) { row += "," + installation.getId() + "_p"; row += "," + installation.getId() + "_q"; } fw.write(row+"\n"); for(int i = 0; i < endTick; i++) { row = String.valueOf(i); for(Installation installation: installations) { DBObject tickResult = m.getTickResultForInstallation(i, installation.getId(), MongoResults.COL_INSTRESULTS); double p = ((Double)tickResult.get("p")).doubleValue(); double q = ((Double)tickResult.get("q")).doubleValue(); row += "," + p; row += "," + q; } fw.write(row+"\n"); } fw.flush(); fw.close(); // End of file writing // zip file // http://www.mkyong.com/java/how-to-compress-files-in-zip-format/ System.out.println("Zipping..."); byte[] buffer = new byte[1024]; FileOutputStream fos = new FileOutputStream(filename + ".zip"); ZipOutputStream zos = new ZipOutputStream(fos); ZipEntry ze= new ZipEntry(dbname + ".csv"); zos.putNextEntry(ze); FileInputStream in = new FileInputStream(filename); int len; while ((len = in.read(buffer)) > 0) { zos.write(buffer, 0, len); } in.close(); zos.closeEntry(); //remember close it zos.close(); fos.close(); csvFile.delete(); // End of zip file System.out.println("End of Zipping..."); long endTime = System.currentTimeMillis(); objRun.put("ended", endTime); System.out.println("Updating DB..."); DBConn.getConn().getCollection(MongoRuns.COL_RUNS).update(query, objRun); System.out.println("End of Updating DB..."); logger.info("Time elapsed for Run " + dbname + ": " + ((endTime - startTime)/(1000.0 * 60)) + " mins"); logger.info("Run " + dbname + " ended @ " + Calendar.getInstance().toString()); } catch(Exception e) { e.printStackTrace(); System.out.println(Utils.stackTraceToString(e.getStackTrace())); // Change the run object in the db to reflect the exception if(objRun != null) { objRun.put("percentage", -1); objRun.put("state", e.getMessage()); DBConn.getConn().getCollection(MongoRuns.COL_RUNS).update(query, objRun); } } } private double totalInstCost() { double cost = 0; for(Installation installation: installations) { cost += installation.getCost(); } return cost; } public void setup(boolean jump) throws Exception { installations = new Vector<Installation>(); /* TODO Change the Simulation Calendar initialization */ logger.info("Simulation setup started: " + dbname); DBObject jsonScenario = (DBObject) JSON.parse(scenario); DBObject scenarioDoc = (DBObject) jsonScenario.get("scenario"); DBObject simParamsDoc = (DBObject) jsonScenario.get("sim_params"); simulationWorld = new SimulationParams(simParamsDoc); // get from scenario for each installation otherwise fallback DBObject pricingDoc = (DBObject) jsonScenario.get("pricing"); DBObject basePricingDoc = (DBObject) jsonScenario.get("baseline_pricing"); if(pricingDoc != null) { pricing = new PricingPolicy(pricingDoc); } else { pricing = new PricingPolicy(); } if(basePricingDoc != null) { baseline_pricing = new PricingPolicy(basePricingDoc); } else { baseline_pricing = new PricingPolicy(); } int numOfDays = ((Integer)simParamsDoc.get("numberOfDays")).intValue(); endTick = Constants.MIN_IN_DAY * numOfDays; mcruns = ((Integer)simParamsDoc.get("mcruns")).intValue(); co2 = Utils.getDouble(simParamsDoc.get("co2")); // Check type of setup String setup = (String)scenarioDoc.get("setup"); if(setup.equalsIgnoreCase("static")) { staticSetup(jsonScenario); } else if(setup.equalsIgnoreCase("dynamic")) { dynamicSetup(jsonScenario, jump); } else { throw new Exception("Problem with setup property!!!"); } logger.info("Simulation setup finished: " + dbname); } public void staticSetup (DBObject jsonScenario) throws Exception { int numOfInstallations = ((Integer)jsonScenario.get("instcount")).intValue(); queue = new PriorityBlockingQueue<Event>(2 * numOfInstallations); for (int i = 1; i <= numOfInstallations; i++) { DBObject instDoc = (DBObject)jsonScenario.get("inst"+i); String id = ((ObjectId)instDoc.get("_id")).toString(); String name = (String)instDoc.get("name"); String description = (String)instDoc.get("description"); String type = (String)instDoc.get("type"); String clustername = (String)instDoc.get("cluster"); PricingPolicy instPricing = pricing; PricingPolicy instBaseline_pricing = baseline_pricing; if(jsonScenario.get("pricing-" + clustername + "-" + id) != null) { DBObject pricingDoc = (DBObject) jsonScenario.get("pricing-" + clustername + "-" + id); instPricing = new PricingPolicy(pricingDoc); } if(jsonScenario.get("baseline_pricing-" + clustername + "-" + id) != null) { DBObject basePricingDoc = (DBObject) jsonScenario.get("baseline_pricing-" + clustername + "-" + id); instBaseline_pricing = new PricingPolicy(basePricingDoc); } Installation inst = new Installation.Builder( id, name, description, type, clustername, instPricing, instBaseline_pricing).build(); // Thermal module if exists DBObject thermalDoc = (DBObject)instDoc.get("thermal"); if(thermalDoc != null && inst.getPricing().getType().equalsIgnoreCase("TOUPricing")) { ThermalModule tm = new ThermalModule(thermalDoc, inst.getPricing().getTOUArray()); inst.setThermalModule(tm); } int appcount = ((Integer)instDoc.get("appcount")).intValue(); // Create the appliances HashMap<String,Appliance> existing = new HashMap<String,Appliance>(); for (int j = 1; j <= appcount; j++) { DBObject applianceDoc = (DBObject)instDoc.get("app"+j); String appid = ((ObjectId)applianceDoc.get("_id")).toString(); String appname = (String)applianceDoc.get("name"); String appdescription = (String)applianceDoc.get("description"); String apptype = (String)applianceDoc.get("type"); double standy = Utils.getDouble(applianceDoc.get("standy_consumption")); boolean base = Utils.getBoolean(applianceDoc.get("base")); DBObject consModDoc = (DBObject)applianceDoc.get("consmod"); ConsumptionModel pconsmod = new ConsumptionModel(consModDoc.get("pmodel").toString(), "p"); ConsumptionModel qconsmod = new ConsumptionModel(consModDoc.get("qmodel").toString(), "q"); Appliance app = new Appliance.Builder( appid, appname, appdescription, apptype, inst, pconsmod, qconsmod, standy, base).build(orng); existing.put(appid, app); inst.addAppliance(app); } DBObject personDoc = (DBObject)instDoc.get("person1"); String personid = ((ObjectId)personDoc.get("_id")).toString(); String personName = (String)personDoc.get("name"); String personDescription = (String)personDoc.get("description"); String personType = (String)personDoc.get("type"); double awareness = Utils.getDouble(personDoc.get("awareness")); double sensitivity = Utils.getDouble(personDoc.get("sensitivity")); Person person = new Person.Builder( personid, personName, personDescription, personType, inst, awareness, sensitivity).build(); inst.addPerson(person); int actcount = ((Integer)personDoc.get("activitycount")).intValue(); for (int j = 1; j <= actcount; j++) { DBObject activityDoc = (DBObject)personDoc.get("activity"+j); String activityName = (String)activityDoc.get("name"); String activityType = (String)activityDoc.get("type"); String actid = ((ObjectId)activityDoc.get("_id")).toString(); int actmodcount = ((Integer)activityDoc.get("actmodcount")).intValue(); Activity act = new Activity.Builder(actid, activityName, "", activityType, simulationWorld).build(); ProbabilityDistribution startDist; ProbabilityDistribution durDist; ProbabilityDistribution timesDist; for (int k = 1; k <= actmodcount; k++) { DBObject actmodDoc = (DBObject)activityDoc.get("actmod"+k); String actmodName = (String)actmodDoc.get("name"); String actmodType = (String)actmodDoc.get("type"); String actmodDayType = (String)actmodDoc.get("day_type"); boolean shiftable = Utils.getBoolean(actmodDoc.get("shiftable")); boolean exclusive = Utils.getEquality(actmodDoc.get("config"), "exclusive", true); DBObject duration = (DBObject)actmodDoc.get("duration"); durDist = json2dist(duration, "duration"); DBObject start = (DBObject)actmodDoc.get("start"); startDist = json2dist(start, "start"); DBObject rep = (DBObject)actmodDoc.get("repetitions"); timesDist = json2dist(rep, "reps"); act.addDuration(actmodDayType, durDist); act.addStartTime(actmodDayType, startDist); act.addTimes(actmodDayType, timesDist); act.addShiftable(actmodDayType, shiftable); act.addConfig(actmodDayType, exclusive); // add appliances BasicDBList containsAppliances = (BasicDBList)actmodDoc.get("containsAppliances"); for(int l = 0; l < containsAppliances.size(); l++) { String containAppId = (String)containsAppliances.get(l); Appliance app = existing.get(containAppId); act.addAppliance(actmodDayType,app,1.0/containsAppliances.size()); } } person.addActivity(act); } installations.add(inst); } } private void calculateExpectedPower(String dbname) { DBObject query = new BasicDBObject(); query.put("_id", new ObjectId(dbname)); DBObject objRun = DBConn.getConn().getCollection(MongoRuns.COL_RUNS).findOne(query); System.out.println("Start exp power calc."); int percentage = 0; double[] aggr_exp = new double[Constants.MIN_IN_DAY]; int count = 0; for(Installation installation: installations) { double[] inst_exp = new double[Constants.MIN_IN_DAY]; Person person = installation.getPersons().get(0); for(Activity activity: person.getActivities()) { System.out.println("CEP: " + activity.getName()); double[] act_exp = activity.calcExpPower(); for(int i = 0; i < act_exp.length; i++) { inst_exp[i] += act_exp[i]; m.addExpectedPowerTick(i, activity.getId(), act_exp[i], 0, MongoResults.COL_ACTRESULTS_EXP); } } // For every appliance that is a base load find mean value and add for(Appliance appliance: installation.getAppliances()) { if(appliance.isBase()) { double mean = 0; Double[] cons = appliance.getActiveConsumption(); for(int i = 0; i < cons.length; i++) { mean += cons[i].doubleValue(); } mean /= cons.length; for(int i = 0; i < inst_exp.length; i++) { inst_exp[i] += mean; } } } for(int i = 0; i < inst_exp.length; i++) { aggr_exp[i] += inst_exp[i]; m.addExpectedPowerTick(i, installation.getId(), inst_exp[i], 0, MongoResults.COL_INSTRESULTS_EXP); } count++; percentage = (int)(0.25 * count * 100.0) / (installations.size()); objRun.put("percentage", percentage); DBConn.getConn().getCollection(MongoRuns.COL_RUNS).update(query, objRun); } for(int i = 0; i < aggr_exp.length; i++) { m.addExpectedPowerTick(i, "aggr", aggr_exp[i], 0, MongoResults.COL_AGGRRESULTS_EXP); System.out.println(aggr_exp[i]); } System.out.println("End exp power calc."); } private String addEntity(Entity e, boolean jump) { BasicDBObject obj = e.toDBObject(); if(!jump) DBConn.getConn(dbname).getCollection(e.getCollection()).insert(obj); ObjectId objId = (ObjectId)obj.get("_id"); return objId.toString(); } public void dynamicSetup(DBObject jsonScenario, boolean jump) throws Exception { DBObject scenario = (DBObject)jsonScenario.get("scenario"); String scenario_id = ((ObjectId)scenario.get("_id")).toString(); DBObject demog = (DBObject)jsonScenario.get("demog"); BasicDBList generators = (BasicDBList) demog.get("generators"); // Initialize simulation variables int numOfInstallations = Utils.getInt(demog.get("numberOfEntities")); //System.out.println(numOfInstallations+""); queue = new PriorityBlockingQueue<Event>(2 * numOfInstallations); for (int i = 1; i <= numOfInstallations; i++) { DBObject instDoc = (DBObject)jsonScenario.get("inst"+1); String id = i+""; String name = ((String)instDoc.get("name")) + i; String description = (String)instDoc.get("description"); String type = (String)instDoc.get("type"); Installation inst = new Installation.Builder( id, name, description, type, null, pricing, baseline_pricing).build(); inst.setParentId(scenario_id); String inst_id = addEntity(inst, jump); inst.setId(inst_id); int appcount = Utils.getInt(instDoc.get("appcount")); // Create the appliances HashMap<String,Appliance> existing = new HashMap<String,Appliance>(); for (int j = 1; j <= appcount; j++) { DBObject applianceDoc = (DBObject)instDoc.get("app"+j); String appid = ((ObjectId)applianceDoc.get("_id")).toString(); String appname = (String)applianceDoc.get("name"); String appdescription = (String)applianceDoc.get("description"); String apptype = (String)applianceDoc.get("type"); double standy = Utils.getDouble(applianceDoc.get("standy_consumption")); boolean base = Utils.getBoolean(applianceDoc.get("base")); DBObject consModDoc = (DBObject)applianceDoc.get("consmod"); ConsumptionModel pconsmod = new ConsumptionModel(consModDoc.get("pmodel").toString(), "p"); ConsumptionModel qconsmod = new ConsumptionModel(consModDoc.get("qmodel").toString(), "q"); Appliance app = new Appliance.Builder( appid, appname, appdescription, apptype, inst, pconsmod, qconsmod, standy, base).build(orng); existing.put(appid, app); } HashMap<String,Double> gens = new HashMap<String,Double>(); for(int k = 0; k < generators.size(); k++) { DBObject generator = (DBObject)generators.get(k); String entityId = (String)generator.get("entity_id"); double prob = Utils.getDouble(generator.get("probability")); gens.put(entityId, new Double(prob)); } Set<String> keys = existing.keySet(); for(String key : keys) { Double prob = gens.get(key); if(prob != null) { double probValue = prob.doubleValue(); if(orng.nextDouble() < probValue) { Appliance selectedApp = existing.get(key); selectedApp.setParentId(inst.getId()); String app_id = addEntity(selectedApp, jump); selectedApp.setId(app_id); inst.addAppliance(selectedApp); ConsumptionModel cm = selectedApp.getPConsumptionModel(); cm.setParentId(app_id); String cm_id = addEntity(cm, jump); cm.setId(cm_id); } } } int personcount = Utils.getInt(instDoc.get("personcount")); // Create the appliances HashMap<String,Person> existingPersons = new HashMap<String,Person>(); for (int j = 1; j <= personcount; j++) { DBObject personDoc = (DBObject)instDoc.get("person"+j); String personid = ((ObjectId)personDoc.get("_id")).toString(); String personName = (String)personDoc.get("name"); String personDescription = (String)personDoc.get("description"); String personType = (String)personDoc.get("type"); double awareness = Utils.getDouble(personDoc.get("awareness")); double sensitivity = Utils.getDouble(personDoc.get("sensitivity")); Person person = new Person.Builder( personid, personName, personDescription, personType, inst, awareness, sensitivity).build(); int actcount = Utils.getInt(personDoc.get("activitycount")); //System.out.println("Act-Count: " + actcount); for (int k = 1; k <= actcount; k++) { DBObject activityDoc = (DBObject)personDoc.get("activity"+k); String activityName = (String)activityDoc.get("name"); String activityType = (String)activityDoc.get("type"); String actid = ((ObjectId)activityDoc.get("_id")).toString(); int actmodcount = Utils.getInt(activityDoc.get("actmodcount")); Activity act = new Activity.Builder(actid, activityName, "", activityType, simulationWorld).build(); ProbabilityDistribution startDist; ProbabilityDistribution durDist; ProbabilityDistribution timesDist; for (int l = 1; l <= actmodcount; l++) { DBObject actmodDoc = (DBObject)activityDoc.get("actmod"+l); act.addModels(actmodDoc); String actmodName = (String)actmodDoc.get("name"); String actmodType = (String)actmodDoc.get("type"); String actmodDayType = (String)actmodDoc.get("day_type"); boolean shiftable = Utils.getBoolean(actmodDoc.get("shiftable")); boolean exclusive = Utils.getEquality(actmodDoc.get("config"), "exclusive", true); DBObject duration = (DBObject)actmodDoc.get("duration"); act.addDurations(duration); durDist = json2dist(duration, "duration"); //System.out.println(durDist.getPrecomputedBin()); DBObject start = (DBObject)actmodDoc.get("start"); act.addStarts(start); startDist = json2dist(start, "start"); //System.out.println(startDist.getPrecomputedBin()); DBObject rep = (DBObject)actmodDoc.get("repetitions"); act.addTimes(rep); timesDist = json2dist(rep, "reps"); //System.out.println(timesDist.getPrecomputedBin()); act.addDuration(actmodDayType, durDist); act.addStartTime(actmodDayType, startDist); act.addTimes(actmodDayType, timesDist); act.addShiftable(actmodDayType, shiftable); act.addConfig(actmodDayType, exclusive); // add appliances BasicDBList containsAppliances = (BasicDBList)actmodDoc.get("containsAppliances"); for(int m = 0; m < containsAppliances.size(); m++) { String containAppId = (String)containsAppliances.get(m); Appliance app = existing.get(containAppId); //act.addAppliance(actmodDayType,app,1.0/containsAppliances.size()); act.addAppliance(actmodDayType,app,1.0); } } person.addActivity(act); } existingPersons.put(personid, person); } double roulette = orng.nextDouble(); double sum = 0; for(int k = 0; k < generators.size(); k++) { DBObject generator = (DBObject)generators.get(k); String entityId = (String)generator.get("entity_id"); if(existingPersons.containsKey(entityId)) { double prob = Utils.getDouble(generator.get("probability")); sum += prob; if(roulette < sum) { Person selectedPerson = existingPersons.get(entityId); selectedPerson.setParentId(inst.getId()); String person_id = addEntity(selectedPerson, jump); selectedPerson.setId(person_id); inst.addPerson(selectedPerson); Vector<Activity> activities = selectedPerson.getActivities(); for(Activity a : activities) { a.setParentId(person_id); String act_id = addEntity(a, jump); a.setId(act_id); Vector<DBObject> models = a.getModels(); Vector<DBObject> starts = a.getStarts(); Vector<DBObject> durations = a.getDurations(); Vector<DBObject> times = a.getTimes(); for(int l = 0; l < models.size(); l++ ) { DBObject m = models.get(l); m.put("act_id", act_id); if(!jump)DBConn.getConn(dbname).getCollection(MongoActivityModels.COL_ACTMODELS).insert(m); ObjectId objId = (ObjectId)m.get("_id"); String actmod_id = objId.toString(); DBObject s = starts.get(l); s.put("actmod_id", actmod_id); if(!jump)DBConn.getConn(dbname).getCollection(MongoDistributions.COL_DISTRIBUTIONS).insert(s); DBObject d = durations.get(l); d.put("actmod_id", actmod_id); if(!jump)DBConn.getConn(dbname).getCollection(MongoActivityModels.COL_ACTMODELS).insert(d); DBObject t = times.get(l); t.put("actmod_id", actmod_id); if(!jump)DBConn.getConn(dbname).getCollection(MongoActivityModels.COL_ACTMODELS).insert(t); } } break; } } } installations.add(inst); } } public static ProbabilityDistribution json2dist(DBObject distribution, String flag) throws Exception { String distType = (String)distribution.get("distrType"); switch (distType) { case ("Normal Distribution"): BasicDBList normalList = (BasicDBList)distribution.get("parameters"); DBObject normalDoc = (DBObject)normalList.get(0); double mean = Double.parseDouble(normalDoc.get("mean").toString()); double std = Double.parseDouble(normalDoc.get("std").toString()); Gaussian normal = new Gaussian(mean, std); normal.precompute(0, 1439, 1440); return normal; case ("Uniform Distribution"): BasicDBList unifList = (BasicDBList)distribution.get("parameters"); DBObject unifDoc = (DBObject)unifList.get(0); double from = Double.parseDouble(unifDoc.get("start").toString()); double to = Double.parseDouble(unifDoc.get("end").toString()); // System.out.println(from + " " + to); Uniform uniform = null; if(flag.equalsIgnoreCase("start")) { uniform = new Uniform(Math.max(from-1,0), Math.min(to-1, 1439), true); } else { uniform = new Uniform(from, to, false); } return uniform; case ("Gaussian Mixture Models"): BasicDBList mixList = (BasicDBList)distribution.get("parameters"); int length = mixList.size(); double[] w = new double[length]; double[] means = new double[length]; double[] stds = new double[length]; for(int i = 0; i < mixList.size(); i++) { DBObject tuple = (DBObject)mixList.get(i); w[i] = Double.parseDouble(tuple.get("w").toString()); means[i] = Double.parseDouble(tuple.get("mean").toString()); stds[i] = Double.parseDouble(tuple.get("std").toString()); } GaussianMixtureModels gmm = new GaussianMixtureModels(length, w, means, stds); gmm.precompute(0, 1439, 1440); return gmm; case ("Histogram"): BasicDBList hList = (BasicDBList)distribution.get("values"); int l = hList.size(); double[] v = new double[l]; for(int i = 0; i < l; i++) { v[i] = Double.parseDouble(hList.get(i).toString()); } Histogram h = new Histogram(v); return h; default: throw new Exception("Non existing distribution type. Problem in setting up the simulation."); } } }
true
true
public void run () { DBObject query = new BasicDBObject(); query.put("_id", new ObjectId(dbname)); DBObject objRun = DBConn.getConn().getCollection(MongoRuns.COL_RUNS).findOne(query); try { System.out.println("Run " + dbname + " started @ " + Calendar.getInstance().getTimeInMillis()); calculateExpectedPower(dbname); long startTime = System.currentTimeMillis(); int percentage = 0; int mccount = 0; double mcrunsRatio = 1.0/(double)mcruns; for(int i = 0; i < mcruns; i++) { tick = 0; double avgPPowerPerHour = 0; double avgQPowerPerHour = 0; double[] avgPPowerPerHourPerInst = new double[installations.size()]; double[] avgQPowerPerHourPerInst = new double[installations.size()]; double maxPower = 0; // double cycleMaxPower = 0; double avgPower = 0; double energy = 0; double energyOffpeak = 0; double cost = 0; // double billingCycleEnergy = 0; // double billingCycleEnergyOffpeak = 0; while (tick < endTick) { // If it is the beginning of the day create the events if (tick % Constants.MIN_IN_DAY == 0) { // System.out.println("Day " + ((tick / Constants.MIN_IN_DAY) + 1)); for (Installation installation: installations) { // System.out.println(installation.getName()); installation.updateDailySchedule(tick, queue, simulationWorld.getResponseType(), orng); } // System.out.println("Daily queue size: " + queue.size() + "(" + // simulationWorld.getSimCalendar().isWeekend(tick) + ")"); } Event top = queue.peek(); while (top != null && top.getTick() == tick) { Event e = queue.poll(); boolean applied = e.apply(); if(applied) { if(e.getAction() == Event.SWITCH_ON) { try { //m.addOpenTick(e.getAppliance().getId(), tick); } catch (Exception exc) { throw exc; } } else if(e.getAction() == Event.SWITCH_OFF){ //m.addCloseTick(e.getAppliance().getId(), tick); } } top = queue.peek(); } /* * Calculate the total power for this simulation step for all the * installations. */ float sumP = 0; float sumQ = 0; int counter = 0; for(Installation installation: installations) { installation.nextStep(tick); double p = installation.getCurrentPowerP(); double q = installation.getCurrentPowerQ(); // if(p> 0.001) System.out.println(p); installation.updateMaxPower(p); installation.updateAvgPower(p/endTick); if(installation.getPricing().isOffpeak(tick)) { installation.updateEnergyOffpeak(p); } else { installation.updateEnergy(p); } installation.updateAppliancesAndActivitiesConsumptions(tick, endTick); m.addTickResultForInstallation(tick, installation.getId(), p * mcrunsRatio, q * mcrunsRatio, MongoResults.COL_INSTRESULTS); sumP += p; sumQ += q; avgPPowerPerHour += p; avgQPowerPerHour += q; avgPPowerPerHourPerInst[counter] += p; avgQPowerPerHourPerInst[counter] += q; String name = installation.getName(); // logger.info("Tick: " + tick + " \t " + "Name: " + name + " \t " // + "Power: " + power); // System.out.println("Tick: " + tick + " \t " + "Name: " + name + " \t " // + "Power: " + p); if((tick + 1) % (Constants.MIN_IN_DAY * installation.getPricing().getBillingCycle()) == 0 || installation.getPricing().getType().equalsIgnoreCase("TOUPricing")) { installation.updateCost(tick); } counter++; } if(sumP > maxPower) maxPower = sumP; // if(sumP > cycleMaxPower) cycleMaxPower = sumP; avgPower += sumP/endTick; // if(pricing.isOffpeak(tick)) { // energyOffpeak += (sumP/1000.0) * Constants.MINUTE_HOUR_RATIO; // } else { // energy += (sumP/1000.0) * Constants.MINUTE_HOUR_RATIO; // } // if((tick + 1) % (Constants.MIN_IN_DAY * pricing.getBillingCycle()) == 0 || pricing.getType().equalsIgnoreCase("TOUPricing")) { // cost = totalInstCost(); //alternate method // billingCycleEnergy = totalInstEnergy(); // billingCycleEnergyOffpeak = totalInstOffpeak(); // cycleMaxPower = 0; // } m.addAggregatedTickResult(tick, sumP * mcrunsRatio, sumQ * mcrunsRatio, MongoResults.COL_AGGRRESULTS); tick++; if(tick % Constants.MIN_IN_HOUR == 0) { m.addAggregatedTickResult((tick/Constants.MIN_IN_HOUR), (avgPPowerPerHour/Constants.MIN_IN_HOUR) * mcrunsRatio, (avgQPowerPerHour/Constants.MIN_IN_HOUR) * mcrunsRatio, MongoResults.COL_AGGRRESULTS_HOURLY); m.addAggregatedTickResult((tick/Constants.MIN_IN_HOUR), (avgPPowerPerHour) * mcrunsRatio, (avgQPowerPerHour) * mcrunsRatio, MongoResults.COL_AGGRRESULTS_HOURLY_EN); avgPPowerPerHour = 0; avgQPowerPerHour = 0; counter = 0; for(Installation installation: installations) { m.addTickResultForInstallation((tick/Constants.MIN_IN_HOUR), installation.getId(), (avgPPowerPerHourPerInst[counter]/Constants.MIN_IN_HOUR) * mcrunsRatio, (avgQPowerPerHourPerInst[counter]/Constants.MIN_IN_HOUR) * mcrunsRatio, MongoResults.COL_INSTRESULTS_HOURLY); m.addTickResultForInstallation((tick/Constants.MIN_IN_HOUR), installation.getId(), (avgPPowerPerHourPerInst[counter]) * mcrunsRatio, (avgQPowerPerHourPerInst[counter]) * mcrunsRatio, MongoResults.COL_INSTRESULTS_HOURLY_EN); avgPPowerPerHourPerInst[counter] = 0; avgQPowerPerHourPerInst[counter] = 0; counter++; } } mccount++; percentage = (int)(0.75 * mccount * 100.0 / (mcruns * endTick)); objRun.put("percentage", 25 + percentage); DBConn.getConn().getCollection(MongoRuns.COL_RUNS).update(query, objRun); } for(Installation installation: installations) { installation.updateCost(tick); // update the rest of the energy m.addKPIs(installation.getId(), installation.getMaxPower() * mcrunsRatio, installation.getAvgPower() * mcrunsRatio, installation.getEnergy() * mcrunsRatio, installation.getCost() * mcrunsRatio, installation.getEnergy() * co2 * mcrunsRatio); installation.addAppliancesKPIs(m, mcrunsRatio, co2); installation.addActivitiesKPIs(m, mcrunsRatio, co2); } cost = totalInstCost(); m.addKPIs(MongoResults.AGGR, maxPower * mcrunsRatio, avgPower * mcrunsRatio, energy * mcrunsRatio, cost * mcrunsRatio, energy * co2 * mcrunsRatio); if(i+1 != mcruns) setup(true); } // Write installation results to csv file String filename = resources_path + "/csvs/" + dbname + ".csv"; System.out.println(filename); File csvFile = new File(filename); FileWriter fw = new FileWriter(csvFile); String row = "tick"; for(Installation installation: installations) { row += "," + installation.getId() + "_p"; row += "," + installation.getId() + "_q"; } fw.write(row+"\n"); for(int i = 0; i < endTick; i++) { row = String.valueOf(i); for(Installation installation: installations) { DBObject tickResult = m.getTickResultForInstallation(i, installation.getId(), MongoResults.COL_INSTRESULTS); double p = ((Double)tickResult.get("p")).doubleValue(); double q = ((Double)tickResult.get("q")).doubleValue(); row += "," + p; row += "," + q; } fw.write(row+"\n"); } fw.flush(); fw.close(); // End of file writing // zip file // http://www.mkyong.com/java/how-to-compress-files-in-zip-format/ System.out.println("Zipping..."); byte[] buffer = new byte[1024]; FileOutputStream fos = new FileOutputStream(filename + ".zip"); ZipOutputStream zos = new ZipOutputStream(fos); ZipEntry ze= new ZipEntry(dbname + ".csv"); zos.putNextEntry(ze); FileInputStream in = new FileInputStream(filename); int len; while ((len = in.read(buffer)) > 0) { zos.write(buffer, 0, len); } in.close(); zos.closeEntry(); //remember close it zos.close(); fos.close(); csvFile.delete(); // End of zip file System.out.println("End of Zipping..."); long endTime = System.currentTimeMillis(); objRun.put("ended", endTime); System.out.println("Updating DB..."); DBConn.getConn().getCollection(MongoRuns.COL_RUNS).update(query, objRun); System.out.println("End of Updating DB..."); logger.info("Time elapsed for Run " + dbname + ": " + ((endTime - startTime)/(1000.0 * 60)) + " mins"); logger.info("Run " + dbname + " ended @ " + Calendar.getInstance().toString()); } catch(Exception e) { e.printStackTrace(); System.out.println(Utils.stackTraceToString(e.getStackTrace())); // Change the run object in the db to reflect the exception if(objRun != null) { objRun.put("percentage", -1); objRun.put("state", e.getMessage()); DBConn.getConn().getCollection(MongoRuns.COL_RUNS).update(query, objRun); } } }
public void run () { DBObject query = new BasicDBObject(); query.put("_id", new ObjectId(dbname)); DBObject objRun = DBConn.getConn().getCollection(MongoRuns.COL_RUNS).findOne(query); try { System.out.println("Run " + dbname + " started @ " + Calendar.getInstance().getTimeInMillis()); calculateExpectedPower(dbname); long startTime = System.currentTimeMillis(); int percentage = 0; int mccount = 0; double mcrunsRatio = 1.0/(double)mcruns; for(int i = 0; i < mcruns; i++) { tick = 0; double avgPPowerPerHour = 0; double avgQPowerPerHour = 0; double[] avgPPowerPerHourPerInst = new double[installations.size()]; double[] avgQPowerPerHourPerInst = new double[installations.size()]; double maxPower = 0; // double cycleMaxPower = 0; double avgPower = 0; double energy = 0; double energyOffpeak = 0; double cost = 0; // double billingCycleEnergy = 0; // double billingCycleEnergyOffpeak = 0; while (tick < endTick) { // If it is the beginning of the day create the events if (tick % Constants.MIN_IN_DAY == 0) { // System.out.println("Day " + ((tick / Constants.MIN_IN_DAY) + 1)); for (Installation installation: installations) { // System.out.println(installation.getName()); installation.updateDailySchedule(tick, queue, simulationWorld.getResponseType(), orng); } // System.out.println("Daily queue size: " + queue.size() + "(" + // simulationWorld.getSimCalendar().isWeekend(tick) + ")"); } Event top = queue.peek(); while (top != null && top.getTick() == tick) { Event e = queue.poll(); boolean applied = e.apply(); if(applied) { if(e.getAction() == Event.SWITCH_ON) { try { //m.addOpenTick(e.getAppliance().getId(), tick); } catch (Exception exc) { throw exc; } } else if(e.getAction() == Event.SWITCH_OFF){ //m.addCloseTick(e.getAppliance().getId(), tick); } } top = queue.peek(); } /* * Calculate the total power for this simulation step for all the * installations. */ float sumP = 0; float sumQ = 0; int counter = 0; for(Installation installation: installations) { installation.nextStep(tick); double p = installation.getCurrentPowerP(); double q = installation.getCurrentPowerQ(); // if(p> 0.001) System.out.println(p); installation.updateMaxPower(p); installation.updateAvgPower(p/endTick); if(installation.getPricing().isOffpeak(tick)) { installation.updateEnergyOffpeak(p); } else { installation.updateEnergy(p); } installation.updateAppliancesAndActivitiesConsumptions(tick, endTick); m.addTickResultForInstallation(tick, installation.getId(), p * mcrunsRatio, q * mcrunsRatio, MongoResults.COL_INSTRESULTS); sumP += p; sumQ += q; avgPPowerPerHour += p; avgQPowerPerHour += q; avgPPowerPerHourPerInst[counter] += p; avgQPowerPerHourPerInst[counter] += q; String name = installation.getName(); // logger.info("Tick: " + tick + " \t " + "Name: " + name + " \t " // + "Power: " + power); // System.out.println("Tick: " + tick + " \t " + "Name: " + name + " \t " // + "Power: " + p); if((tick + 1) % (Constants.MIN_IN_DAY * installation.getPricing().getBillingCycle()) == 0 || installation.getPricing().getType().equalsIgnoreCase("TOUPricing")) { installation.updateCost(tick); } counter++; } if(sumP > maxPower) maxPower = sumP; // if(sumP > cycleMaxPower) cycleMaxPower = sumP; avgPower += sumP/endTick; energy += (sumP/1000.0) * Constants.MINUTE_HOUR_RATIO; // if(pricing.isOffpeak(tick)) { // energyOffpeak += (sumP/1000.0) * Constants.MINUTE_HOUR_RATIO; // } else { // energy += (sumP/1000.0) * Constants.MINUTE_HOUR_RATIO; // } // if((tick + 1) % (Constants.MIN_IN_DAY * pricing.getBillingCycle()) == 0 || pricing.getType().equalsIgnoreCase("TOUPricing")) { // cost = totalInstCost(); //alternate method // billingCycleEnergy = totalInstEnergy(); // billingCycleEnergyOffpeak = totalInstOffpeak(); // cycleMaxPower = 0; // } m.addAggregatedTickResult(tick, sumP * mcrunsRatio, sumQ * mcrunsRatio, MongoResults.COL_AGGRRESULTS); tick++; if(tick % Constants.MIN_IN_HOUR == 0) { m.addAggregatedTickResult((tick/Constants.MIN_IN_HOUR), (avgPPowerPerHour/Constants.MIN_IN_HOUR) * mcrunsRatio, (avgQPowerPerHour/Constants.MIN_IN_HOUR) * mcrunsRatio, MongoResults.COL_AGGRRESULTS_HOURLY); m.addAggregatedTickResult((tick/Constants.MIN_IN_HOUR), (avgPPowerPerHour) * mcrunsRatio, (avgQPowerPerHour) * mcrunsRatio, MongoResults.COL_AGGRRESULTS_HOURLY_EN); avgPPowerPerHour = 0; avgQPowerPerHour = 0; counter = 0; for(Installation installation: installations) { m.addTickResultForInstallation((tick/Constants.MIN_IN_HOUR), installation.getId(), (avgPPowerPerHourPerInst[counter]/Constants.MIN_IN_HOUR) * mcrunsRatio, (avgQPowerPerHourPerInst[counter]/Constants.MIN_IN_HOUR) * mcrunsRatio, MongoResults.COL_INSTRESULTS_HOURLY); m.addTickResultForInstallation((tick/Constants.MIN_IN_HOUR), installation.getId(), (avgPPowerPerHourPerInst[counter]) * mcrunsRatio, (avgQPowerPerHourPerInst[counter]) * mcrunsRatio, MongoResults.COL_INSTRESULTS_HOURLY_EN); avgPPowerPerHourPerInst[counter] = 0; avgQPowerPerHourPerInst[counter] = 0; counter++; } } mccount++; percentage = (int)(0.75 * mccount * 100.0 / (mcruns * endTick)); objRun.put("percentage", 25 + percentage); DBConn.getConn().getCollection(MongoRuns.COL_RUNS).update(query, objRun); } for(Installation installation: installations) { installation.updateCost(tick); // update the rest of the energy m.addKPIs(installation.getId(), installation.getMaxPower() * mcrunsRatio, installation.getAvgPower() * mcrunsRatio, installation.getEnergy() * mcrunsRatio, installation.getCost() * mcrunsRatio, installation.getEnergy() * co2 * mcrunsRatio); installation.addAppliancesKPIs(m, mcrunsRatio, co2); installation.addActivitiesKPIs(m, mcrunsRatio, co2); } cost = totalInstCost(); m.addKPIs(MongoResults.AGGR, maxPower * mcrunsRatio, avgPower * mcrunsRatio, energy * mcrunsRatio, cost * mcrunsRatio, energy * co2 * mcrunsRatio); if(i+1 != mcruns) setup(true); } // Write installation results to csv file String filename = resources_path + "/csvs/" + dbname + ".csv"; System.out.println(filename); File csvFile = new File(filename); FileWriter fw = new FileWriter(csvFile); String row = "tick"; for(Installation installation: installations) { row += "," + installation.getId() + "_p"; row += "," + installation.getId() + "_q"; } fw.write(row+"\n"); for(int i = 0; i < endTick; i++) { row = String.valueOf(i); for(Installation installation: installations) { DBObject tickResult = m.getTickResultForInstallation(i, installation.getId(), MongoResults.COL_INSTRESULTS); double p = ((Double)tickResult.get("p")).doubleValue(); double q = ((Double)tickResult.get("q")).doubleValue(); row += "," + p; row += "," + q; } fw.write(row+"\n"); } fw.flush(); fw.close(); // End of file writing // zip file // http://www.mkyong.com/java/how-to-compress-files-in-zip-format/ System.out.println("Zipping..."); byte[] buffer = new byte[1024]; FileOutputStream fos = new FileOutputStream(filename + ".zip"); ZipOutputStream zos = new ZipOutputStream(fos); ZipEntry ze= new ZipEntry(dbname + ".csv"); zos.putNextEntry(ze); FileInputStream in = new FileInputStream(filename); int len; while ((len = in.read(buffer)) > 0) { zos.write(buffer, 0, len); } in.close(); zos.closeEntry(); //remember close it zos.close(); fos.close(); csvFile.delete(); // End of zip file System.out.println("End of Zipping..."); long endTime = System.currentTimeMillis(); objRun.put("ended", endTime); System.out.println("Updating DB..."); DBConn.getConn().getCollection(MongoRuns.COL_RUNS).update(query, objRun); System.out.println("End of Updating DB..."); logger.info("Time elapsed for Run " + dbname + ": " + ((endTime - startTime)/(1000.0 * 60)) + " mins"); logger.info("Run " + dbname + " ended @ " + Calendar.getInstance().toString()); } catch(Exception e) { e.printStackTrace(); System.out.println(Utils.stackTraceToString(e.getStackTrace())); // Change the run object in the db to reflect the exception if(objRun != null) { objRun.put("percentage", -1); objRun.put("state", e.getMessage()); DBConn.getConn().getCollection(MongoRuns.COL_RUNS).update(query, objRun); } } }
diff --git a/src/me/desht/util/PermissionsUtils.java b/src/me/desht/util/PermissionsUtils.java index 8e03a1c..13ce911 100644 --- a/src/me/desht/util/PermissionsUtils.java +++ b/src/me/desht/util/PermissionsUtils.java @@ -1,327 +1,327 @@ package me.desht.util; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.logging.Level; import me.desht.scrollingmenusign.SMSException; import org.bukkit.Bukkit; import org.bukkit.World; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginManager; import ru.tehkode.permissions.PermissionManager; import ru.tehkode.permissions.PermissionUser; import ru.tehkode.permissions.bukkit.PermissionsEx; import com.platymuus.bukkit.permissions.Group; import com.platymuus.bukkit.permissions.PermissionInfo; import com.platymuus.bukkit.permissions.PermissionsPlugin; import de.bananaco.permissions.worlds.WorldPermissionsManager; public class PermissionsUtils { private static Plugin activePlugin = null; private static PermissionsPlugin permissionsBukkit = null; // PermissionsBukkit private static PermissionManager permissionManager = null; // PermissionsEx private static WorldPermissionsManager wpm = null; // bPermissions private PermissionsUtils() { } /** * Try to detect a supported permissions plugin. */ public static void setup() { PluginManager pm = Bukkit.getServer().getPluginManager(); Plugin plugin = null; if ((plugin = pm.getPlugin("PermissionsBukkit")) != null) { permissionsBukkit = (PermissionsPlugin) plugin; } else if ((plugin = pm.getPlugin("PermissionsEx")) != null) { permissionManager = PermissionsEx.getPermissionManager(); } else if ((plugin = pm.getPlugin("bPermissions")) != null) { wpm = de.bananaco.permissions.Permissions.getWorldPermissionsManager(); } activePlugin = plugin; if (plugin != null) { MiscUtil.log(Level.INFO, "Permissions plugin detected: " + plugin.getDescription().getName() + " v" + plugin.getDescription().getVersion()); } else { MiscUtil.log(Level.INFO, "No Permissions plugin detected - using built-in Bukkit superperms for permissions."); } } /** * Is there a supported permissions plugin active? * * @return true if a supported permissions plugin is active, false otherwise */ public static boolean isPluginActive() { return activePlugin != null; } /** * Check if the player has the specified permission node. * * @param player Player to check * @param node Node to check for * @return true if the player has the permission node, false otherwise */ public static Boolean isAllowedTo(Player player, String node) { if (player == null || node == null) return true; else return player.hasPermission(node); } /** * Throw an exception if the player does not have the specified permission. * * @param player Player to check * @param node Require permission node * @throws SMSException if the player does not have the node */ public static void requirePerms(Player player, String node) throws SMSException { if (!isAllowedTo(player, node)) { throw new SMSException("You are not allowed to do that (need node " + node + ")."); } } /** * Check if the player is in the specified group. * * @param player * @param group * @return */ public static boolean isInGroup(Player player, String group) { if (permissionsBukkit != null) { for (Group grp : permissionsBukkit.getGroups(player.getName())) { if (grp.getName().equalsIgnoreCase(group)) return true; } } else if (permissionManager != null) { return permissionManager.getUser(player).inGroup(group); } else if (wpm != null) { for (String grp : wpm.getPermissionSet(player.getWorld().getName()).getGroups(player)) { if (grp.equalsIgnoreCase(group)) return true; } } return false; } // /** // * Elevate the permissions of player to match those of target // * // * @param player The player to elevate // * @param target The target player to copy the permissions from // * @return List of temporary nodes which were granted // */ // public static List<String> elevate(Player player, String target) { // List<String> tempNodes = new ArrayList<String>(); // // if (wpm != null) { // // bPermissions does things a bit differently - we copy the target's group(s) // // to the player, not permission nodes // PermissionSet ps = wpm.getPermissionSet(player.getWorld()); // for (String grp : ps.getGroups(target)) { // if (!isInGroup(player, grp)) { // ps.addGroup(player, grp); // tempNodes.add(grp); // } // } // return tempNodes; // } else { // List<String> nodes = getPermissionNodes(target, player.getWorld()); // if (nodes == null) // return null; // for (String node : nodes) { // if (!isAllowedTo(player, node)) // tempNodes.add(node); // } // } // // for (String perm: tempNodes) { // Debugger.getDebugger().debug("grant perm " + perm); // if (permissionsBukkit != null) { // // PermissionsBukkit has no API call to modify permissions - use a console command to do it // String cmd = String.format("permissions player setperm %s %s true", player.getName(), perm); // QuietConsoleCommandSender console = new QuietConsoleCommandSender(Bukkit.getServer()); // Bukkit.getServer().dispatchCommand(console, cmd); // } else if (permissionHandler != null) { // com.nijiko.permissions.User user = permissionHandler.getUserObject(player.getWorld().getName(), player.getName()); // if (user != null) { // user.addPermission(perm); // } // } else if (permissionManager != null) { // PermissionUser user = permissionManager.getUser(player.getName()); // if (user != null) { // user.addPermission(perm, player.getWorld().getName()); // } // } else if (wpm != null) { // PermissionSet ps = wpm.getPermissionSet(player.getWorld()); // for (String grp : tempNodes) { // ps.addGroup(player, grp); // } // } // } // // return tempNodes; // } // // /** // * De-elevate a player's permissions. // * // * @param player The player to de-elevate // * @param tempPerms The list of permission nodes to remove // */ // public static void deElevate(Player player, List<String> tempPerms) { // if (tempPerms == null) // return; // // QuietConsoleCommandSender console = new QuietConsoleCommandSender(Bukkit.getServer()); // for (String perm : tempPerms) { // // Debugger.getDebugger().debug("withdraw perm " + perm); // // if (permissionsBukkit != null) { // String cmd = String.format("permissions player unsetperm %s %s true", player.getName(), perm); // Bukkit.getServer().dispatchCommand(console, cmd); // } else if (permissionHandler != null) { // com.nijiko.permissions.User user = permissionHandler.getUserObject(player.getWorld().getName(), player.getName()); // if (user != null) { // user.removePermission(perm); // } // } else if (permissionManager != null) { // PermissionUser user = permissionManager.getUser(player.getName()); // if (user != null) { // user.removePermission(perm, player.getWorld().getName()); // } // } else if (wpm != null) { // // bPermissions does things a bit differently - // // we need to remove groups from the player rather than permission nodes // PermissionSet ps = wpm.getPermissionSet(player.getWorld()); // for (String grp : tempPerms) { // ps.removeGroup(player, grp); // } // } // } // } // /** * Get a full list of the player's permission nodes. * * @param playerName Name of the player to check for * @param w Player's world (use first known world if null is passed) * @return A list of permission node strings */ public static List<String> getPermissionNodes(String playerName, World w) { if (w == null) w = Bukkit.getServer().getWorlds().get(0); System.out.println("get nodes " + playerName); - List<String> res = null; + List<String> res = new ArrayList<String>(); if (permissionsBukkit != null) { System.out.println("permissions bukkit get nodes"); Map<String, Boolean> perms; PermissionInfo info = permissionsBukkit.getPlayerInfo(playerName); if (info == null) - return null; + return res; try { // this call currently throws an NPE if no explicit permissions defined perms = info.getPermissions(); } catch (NullPointerException e) { perms = new HashMap<String, Boolean>(); } for (Group grp : info.getGroups()) { PermissionInfo gInfo = grp.getInfo(); try { // this call currently throws an NPE if no explicit permissions defined Map<String, Boolean> gPerms = gInfo.getPermissions(); for (Entry<String, Boolean> e : gPerms.entrySet()) { perms.put(e.getKey(), e.getValue()); } } catch (NullPointerException e) { } } res = new ArrayList<String>(perms.keySet()); } else if (permissionManager != null) { PermissionUser user = permissionManager.getUser(playerName); if (user != null) { res = Arrays.asList(user.getPermissions(w.getName())); } } else if (wpm != null) { res = wpm.getPermissionSet(w).getPlayerNodes(playerName); } return res; } // /** // * Temporarily grant op status to a player. We don't use player.setOp() because we don't // * want the ops.txt file to be written. // * // * @param player The player to grant ops status to // * @return A set of all player names who currently have ops status // */ // @SuppressWarnings("unchecked") // public static Set<String> grantOpStatus(Player player) { // Field opsSetField = null; // Set<String> opsSet = null; // // try { // opsSetField = ServerConfigurationManager.class.getDeclaredField("operators"); // opsSet = (Set<String>) opsSetField.get(((CraftServer)player.getServer()).getHandle()); // } catch (NoSuchFieldException nfe) { // // earlier versions of CraftBukkit don't have the public "operators" field // // instead we need to use reflection to expose the private "h" field (yuck) // try { // opsSetField = ServerConfigurationManager.class.getDeclaredField("h"); // opsSetField.setAccessible(true); // opsSet = (Set<String>) opsSetField.get(((CraftServer)player.getServer()).getHandle()); // } catch (Exception e) { // MiscUtil.log(Level.WARNING, "Exception thrown when finding opsSet: " + e.getClass() + ": " + e.getMessage()); // } // } catch (IllegalAccessException e) { // MiscUtil.log(Level.WARNING, "Exception thrown when finding opsSet: " + e.getClass() + ": " + e.getMessage()); // } // // if (opsSet != null) { // if (opsSet.contains(player.getName().toLowerCase())) { // // player is already an Op // opsSet = null; // } else { // opsSet.add(player.getName().toLowerCase()); // } // player.recalculatePermissions(); // Debugger.getDebugger().debug("granted op to " + player.getName()); // } // // return opsSet; // } // // /** // * Revoke ops status from a player // * // * @param player The player to revoke ops status from // * @param opsSet A set of all player names who currently have ops status, as returned by @see #grantOpStatus(Player) // */ // public static void revokeOpStatus(Player player, Set<String> opsSet) { // if (opsSet != null) { // opsSet.remove(player.getName().toLowerCase()); // player.recalculatePermissions(); // Debugger.getDebugger().debug("revoked op from " + player.getName()); // } // } }
false
true
public static List<String> getPermissionNodes(String playerName, World w) { if (w == null) w = Bukkit.getServer().getWorlds().get(0); System.out.println("get nodes " + playerName); List<String> res = null; if (permissionsBukkit != null) { System.out.println("permissions bukkit get nodes"); Map<String, Boolean> perms; PermissionInfo info = permissionsBukkit.getPlayerInfo(playerName); if (info == null) return null; try { // this call currently throws an NPE if no explicit permissions defined perms = info.getPermissions(); } catch (NullPointerException e) { perms = new HashMap<String, Boolean>(); } for (Group grp : info.getGroups()) { PermissionInfo gInfo = grp.getInfo(); try { // this call currently throws an NPE if no explicit permissions defined Map<String, Boolean> gPerms = gInfo.getPermissions(); for (Entry<String, Boolean> e : gPerms.entrySet()) { perms.put(e.getKey(), e.getValue()); } } catch (NullPointerException e) { } } res = new ArrayList<String>(perms.keySet()); } else if (permissionManager != null) { PermissionUser user = permissionManager.getUser(playerName); if (user != null) { res = Arrays.asList(user.getPermissions(w.getName())); } } else if (wpm != null) { res = wpm.getPermissionSet(w).getPlayerNodes(playerName); } return res; }
public static List<String> getPermissionNodes(String playerName, World w) { if (w == null) w = Bukkit.getServer().getWorlds().get(0); System.out.println("get nodes " + playerName); List<String> res = new ArrayList<String>(); if (permissionsBukkit != null) { System.out.println("permissions bukkit get nodes"); Map<String, Boolean> perms; PermissionInfo info = permissionsBukkit.getPlayerInfo(playerName); if (info == null) return res; try { // this call currently throws an NPE if no explicit permissions defined perms = info.getPermissions(); } catch (NullPointerException e) { perms = new HashMap<String, Boolean>(); } for (Group grp : info.getGroups()) { PermissionInfo gInfo = grp.getInfo(); try { // this call currently throws an NPE if no explicit permissions defined Map<String, Boolean> gPerms = gInfo.getPermissions(); for (Entry<String, Boolean> e : gPerms.entrySet()) { perms.put(e.getKey(), e.getValue()); } } catch (NullPointerException e) { } } res = new ArrayList<String>(perms.keySet()); } else if (permissionManager != null) { PermissionUser user = permissionManager.getUser(playerName); if (user != null) { res = Arrays.asList(user.getPermissions(w.getName())); } } else if (wpm != null) { res = wpm.getPermissionSet(w).getPlayerNodes(playerName); } return res; }
diff --git a/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/history/command/ShowVersionsHandler.java b/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/history/command/ShowVersionsHandler.java index 8a9ce037..2fdb9974 100644 --- a/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/history/command/ShowVersionsHandler.java +++ b/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/history/command/ShowVersionsHandler.java @@ -1,183 +1,183 @@ /******************************************************************************* * Copyright (C) 2010, Mathias Kinzler <[email protected]> * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.eclipse.egit.ui.internal.history.command; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.eclipse.compare.ITypedElement; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.egit.core.project.RepositoryMapping; import org.eclipse.egit.ui.Activator; import org.eclipse.egit.ui.UIText; import org.eclipse.egit.ui.internal.CompareUtils; import org.eclipse.egit.ui.internal.EgitUiEditorUtils; import org.eclipse.egit.ui.internal.GitCompareFileRevisionEditorInput; import org.eclipse.egit.ui.internal.history.GitHistoryPage; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.revwalk.RevWalk; import org.eclipse.osgi.util.NLS; import org.eclipse.team.core.history.IFileRevision; import org.eclipse.team.ui.synchronize.SaveableCompareEditorInput; /** * Show versions/open. * <p> * If a single version is selected, open it, otherwise open several versions of * the file content. */ public class ShowVersionsHandler extends AbstractHistoryCommanndHandler { public Object execute(ExecutionEvent event) throws ExecutionException { boolean compareMode = Boolean.TRUE.toString().equals( event.getParameter(HistoryViewCommands.COMPARE_MODE_PARAM)); IStructuredSelection selection = getSelection(getPage()); if (selection.size() < 1) return null; Object input = getPage().getInputInternal().getSingleFile(); if (input == null) return null; boolean errorOccured = false; List<ObjectId> ids = new ArrayList<ObjectId>(); String gitPath = null; if (input instanceof IFile) { IFile resource = (IFile) input; final RepositoryMapping map = RepositoryMapping .getMapping(resource); gitPath = map.getRepoRelativePath(resource); Iterator<?> it = selection.iterator(); while (it.hasNext()) { RevCommit commit = (RevCommit) it.next(); IFileRevision rev = null; try { rev = CompareUtils.getFileRevision(gitPath, commit, map .getRepository(), null); } catch (IOException e) { Activator.logError(NLS.bind( UIText.GitHistoryPage_errorLookingUpPath, gitPath, commit.getId()), e); errorOccured = true; } if (rev != null) { if (compareMode) { ITypedElement right = CompareUtils .getFileRevisionTypedElement(gitPath, commit, map.getRepository()); final GitCompareFileRevisionEditorInput in = new GitCompareFileRevisionEditorInput( SaveableCompareEditorInput .createFileElement(resource), right, null); try { openInCompare(event, in); } catch (Exception e) { errorOccured = true; } } else { try { EgitUiEditorUtils.openEditor(getPart(event) .getSite().getPage(), rev, new NullProgressMonitor()); } catch (CoreException e) { Activator.logError( UIText.GitHistoryPage_openFailed, e); errorOccured = true; } } } else { ids.add(commit.getId()); } } } if (input instanceof File) { File fileInput = (File) input; Repository repo = getRepository(event); gitPath = getRepoRelativePath(repo, fileInput); Iterator<?> it = selection.iterator(); while (it.hasNext()) { RevCommit commit = (RevCommit) it.next(); IFileRevision rev = null; try { rev = CompareUtils.getFileRevision(gitPath, commit, repo, null); } catch (IOException e) { Activator.logError(NLS.bind( UIText.GitHistoryPage_errorLookingUpPath, gitPath, commit.getId()), e); errorOccured = true; } if (rev != null) { if (compareMode) { try { ITypedElement left = CompareUtils .getFileRevisionTypedElement(gitPath, new RevWalk(repo).parseCommit(repo .resolve(Constants.HEAD)), repo); ITypedElement right = CompareUtils .getFileRevisionTypedElement(gitPath, commit, repo); final GitCompareFileRevisionEditorInput in = new GitCompareFileRevisionEditorInput( left, right, null); openInCompare(event, in); - } catch (Exception e) { + } catch (IOException e) { errorOccured = true; } } else { try { EgitUiEditorUtils.openEditor(getPart(event) .getSite().getPage(), rev, new NullProgressMonitor()); } catch (CoreException e) { Activator.logError( UIText.GitHistoryPage_openFailed, e); errorOccured = true; } } } else { ids.add(commit.getId()); } } } if (errorOccured) Activator.showError(UIText.GitHistoryPage_openFailed, null); if (ids.size() > 0) { String idList = ""; //$NON-NLS-1$ for (ObjectId objectId : ids) { idList += objectId.getName() + " "; //$NON-NLS-1$ } MessageDialog.openError(getPart(event).getSite().getShell(), UIText.GitHistoryPage_fileNotFound, NLS.bind( UIText.GitHistoryPage_notContainedInCommits, gitPath, idList)); } return null; } @Override public boolean isEnabled() { GitHistoryPage page = getPage(); if (page == null) return false; int size = getSelection(page).size(); if (size == 0) return false; return page.getInputInternal().isSingleFile(); } }
true
true
public Object execute(ExecutionEvent event) throws ExecutionException { boolean compareMode = Boolean.TRUE.toString().equals( event.getParameter(HistoryViewCommands.COMPARE_MODE_PARAM)); IStructuredSelection selection = getSelection(getPage()); if (selection.size() < 1) return null; Object input = getPage().getInputInternal().getSingleFile(); if (input == null) return null; boolean errorOccured = false; List<ObjectId> ids = new ArrayList<ObjectId>(); String gitPath = null; if (input instanceof IFile) { IFile resource = (IFile) input; final RepositoryMapping map = RepositoryMapping .getMapping(resource); gitPath = map.getRepoRelativePath(resource); Iterator<?> it = selection.iterator(); while (it.hasNext()) { RevCommit commit = (RevCommit) it.next(); IFileRevision rev = null; try { rev = CompareUtils.getFileRevision(gitPath, commit, map .getRepository(), null); } catch (IOException e) { Activator.logError(NLS.bind( UIText.GitHistoryPage_errorLookingUpPath, gitPath, commit.getId()), e); errorOccured = true; } if (rev != null) { if (compareMode) { ITypedElement right = CompareUtils .getFileRevisionTypedElement(gitPath, commit, map.getRepository()); final GitCompareFileRevisionEditorInput in = new GitCompareFileRevisionEditorInput( SaveableCompareEditorInput .createFileElement(resource), right, null); try { openInCompare(event, in); } catch (Exception e) { errorOccured = true; } } else { try { EgitUiEditorUtils.openEditor(getPart(event) .getSite().getPage(), rev, new NullProgressMonitor()); } catch (CoreException e) { Activator.logError( UIText.GitHistoryPage_openFailed, e); errorOccured = true; } } } else { ids.add(commit.getId()); } } } if (input instanceof File) { File fileInput = (File) input; Repository repo = getRepository(event); gitPath = getRepoRelativePath(repo, fileInput); Iterator<?> it = selection.iterator(); while (it.hasNext()) { RevCommit commit = (RevCommit) it.next(); IFileRevision rev = null; try { rev = CompareUtils.getFileRevision(gitPath, commit, repo, null); } catch (IOException e) { Activator.logError(NLS.bind( UIText.GitHistoryPage_errorLookingUpPath, gitPath, commit.getId()), e); errorOccured = true; } if (rev != null) { if (compareMode) { try { ITypedElement left = CompareUtils .getFileRevisionTypedElement(gitPath, new RevWalk(repo).parseCommit(repo .resolve(Constants.HEAD)), repo); ITypedElement right = CompareUtils .getFileRevisionTypedElement(gitPath, commit, repo); final GitCompareFileRevisionEditorInput in = new GitCompareFileRevisionEditorInput( left, right, null); openInCompare(event, in); } catch (Exception e) { errorOccured = true; } } else { try { EgitUiEditorUtils.openEditor(getPart(event) .getSite().getPage(), rev, new NullProgressMonitor()); } catch (CoreException e) { Activator.logError( UIText.GitHistoryPage_openFailed, e); errorOccured = true; } } } else { ids.add(commit.getId()); } } } if (errorOccured) Activator.showError(UIText.GitHistoryPage_openFailed, null); if (ids.size() > 0) { String idList = ""; //$NON-NLS-1$ for (ObjectId objectId : ids) { idList += objectId.getName() + " "; //$NON-NLS-1$ } MessageDialog.openError(getPart(event).getSite().getShell(), UIText.GitHistoryPage_fileNotFound, NLS.bind( UIText.GitHistoryPage_notContainedInCommits, gitPath, idList)); } return null; }
public Object execute(ExecutionEvent event) throws ExecutionException { boolean compareMode = Boolean.TRUE.toString().equals( event.getParameter(HistoryViewCommands.COMPARE_MODE_PARAM)); IStructuredSelection selection = getSelection(getPage()); if (selection.size() < 1) return null; Object input = getPage().getInputInternal().getSingleFile(); if (input == null) return null; boolean errorOccured = false; List<ObjectId> ids = new ArrayList<ObjectId>(); String gitPath = null; if (input instanceof IFile) { IFile resource = (IFile) input; final RepositoryMapping map = RepositoryMapping .getMapping(resource); gitPath = map.getRepoRelativePath(resource); Iterator<?> it = selection.iterator(); while (it.hasNext()) { RevCommit commit = (RevCommit) it.next(); IFileRevision rev = null; try { rev = CompareUtils.getFileRevision(gitPath, commit, map .getRepository(), null); } catch (IOException e) { Activator.logError(NLS.bind( UIText.GitHistoryPage_errorLookingUpPath, gitPath, commit.getId()), e); errorOccured = true; } if (rev != null) { if (compareMode) { ITypedElement right = CompareUtils .getFileRevisionTypedElement(gitPath, commit, map.getRepository()); final GitCompareFileRevisionEditorInput in = new GitCompareFileRevisionEditorInput( SaveableCompareEditorInput .createFileElement(resource), right, null); try { openInCompare(event, in); } catch (Exception e) { errorOccured = true; } } else { try { EgitUiEditorUtils.openEditor(getPart(event) .getSite().getPage(), rev, new NullProgressMonitor()); } catch (CoreException e) { Activator.logError( UIText.GitHistoryPage_openFailed, e); errorOccured = true; } } } else { ids.add(commit.getId()); } } } if (input instanceof File) { File fileInput = (File) input; Repository repo = getRepository(event); gitPath = getRepoRelativePath(repo, fileInput); Iterator<?> it = selection.iterator(); while (it.hasNext()) { RevCommit commit = (RevCommit) it.next(); IFileRevision rev = null; try { rev = CompareUtils.getFileRevision(gitPath, commit, repo, null); } catch (IOException e) { Activator.logError(NLS.bind( UIText.GitHistoryPage_errorLookingUpPath, gitPath, commit.getId()), e); errorOccured = true; } if (rev != null) { if (compareMode) { try { ITypedElement left = CompareUtils .getFileRevisionTypedElement(gitPath, new RevWalk(repo).parseCommit(repo .resolve(Constants.HEAD)), repo); ITypedElement right = CompareUtils .getFileRevisionTypedElement(gitPath, commit, repo); final GitCompareFileRevisionEditorInput in = new GitCompareFileRevisionEditorInput( left, right, null); openInCompare(event, in); } catch (IOException e) { errorOccured = true; } } else { try { EgitUiEditorUtils.openEditor(getPart(event) .getSite().getPage(), rev, new NullProgressMonitor()); } catch (CoreException e) { Activator.logError( UIText.GitHistoryPage_openFailed, e); errorOccured = true; } } } else { ids.add(commit.getId()); } } } if (errorOccured) Activator.showError(UIText.GitHistoryPage_openFailed, null); if (ids.size() > 0) { String idList = ""; //$NON-NLS-1$ for (ObjectId objectId : ids) { idList += objectId.getName() + " "; //$NON-NLS-1$ } MessageDialog.openError(getPart(event).getSite().getShell(), UIText.GitHistoryPage_fileNotFound, NLS.bind( UIText.GitHistoryPage_notContainedInCommits, gitPath, idList)); } return null; }
diff --git a/src/org/eclipse/core/internal/localstore/RefreshLocalVisitor.java b/src/org/eclipse/core/internal/localstore/RefreshLocalVisitor.java index f85cfad9..9b78c9a2 100644 --- a/src/org/eclipse/core/internal/localstore/RefreshLocalVisitor.java +++ b/src/org/eclipse/core/internal/localstore/RefreshLocalVisitor.java @@ -1,301 +1,301 @@ /******************************************************************************* * 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.core.internal.localstore; import org.eclipse.core.resources.*; import org.eclipse.core.runtime.*; import org.eclipse.core.internal.resources.*; import org.eclipse.core.internal.utils.Policy; // /** * Visits a unified tree, and synchronizes the file system with the * resource tree. After the visit is complete, the file system will * be synchronized with the workspace tree with respect to * resource existence, gender, and timestamp. */ public class RefreshLocalVisitor implements IUnifiedTreeVisitor, ILocalStoreConstants { protected IProgressMonitor monitor; protected Workspace workspace; protected boolean resourceChanged; protected MultiStatus errors; /* * Fields for progress monitoring algorithm. * Initially, give progress for every 4 resources, double * this value at halfway point, then reset halfway point * to be half of remaining work. (this gives an infinite * series that converges at total work after an infinite * number of resources). */ public static final int TOTAL_WORK = 250; private int halfWay = TOTAL_WORK / 2; private int currentIncrement = 4; private int nextProgress = currentIncrement; private int worked = 0; /** control constants */ protected static final int RL_UNKNOWN = 0; protected static final int RL_IN_SYNC = 1; protected static final int RL_NOT_IN_SYNC = 2; public RefreshLocalVisitor(IProgressMonitor monitor) { this.monitor = monitor; workspace = (Workspace) ResourcesPlugin.getWorkspace(); resourceChanged = false; String msg = Policy.bind("resources.errorMultiRefresh"); //$NON-NLS-1$ errors = new MultiStatus(ResourcesPlugin.PI_RESOURCES, IResourceStatus.FAILED_READ_LOCAL, msg, null); } /** * This method has the same implementation as resourceChanged but as they are different * cases, we prefer to use different methods. */ protected void contentAdded(UnifiedTreeNode node, Resource target) throws CoreException { resourceChanged(node, target); } protected void createResource(UnifiedTreeNode node, Resource target) throws CoreException { ResourceInfo info = target.getResourceInfo(false, false); int flags = target.getFlags(info); if (target.exists(flags, false)) return; /* make sure target's parent exists */ if (node.getLevel() == 0) { IContainer parent = target.getParent(); if (parent.getType() == IResource.FOLDER) ((Folder) target.getParent()).ensureExists(monitor); } /* Use the basic file creation protocol since we don't want to create any content on disk. */ info = workspace.createResource(target, false); target.getLocalManager().updateLocalSync(info, node.getLastModified()); } protected void deleteResource(UnifiedTreeNode node, Resource target) throws CoreException { ResourceInfo info = target.getResourceInfo(false, false); int flags = target.getFlags(info); //don't delete linked resources if (ResourceInfo.isSet(flags, ICoreConstants.M_LINK)) return; if (target.exists(flags, false)) target.deleteResource(true, null); node.setExistsWorkspace(false); } protected void fileToFolder(UnifiedTreeNode node, Resource target) throws CoreException { ResourceInfo info = target.getResourceInfo(false, false); int flags = target.getFlags(info); if (target.exists(flags, true)) { target = (Folder) ((File) target).changeToFolder(); } else { if (!target.exists(flags, false)) { target = (Resource) workspace.getRoot().getFolder(target.getFullPath()); // Use the basic file creation protocol since we don't want to create any content on disk. workspace.createResource(target, false); } } node.setResource(target); info = target.getResourceInfo(false, true); target.getLocalManager().updateLocalSync(info, node.getLastModified()); } protected void folderToFile(UnifiedTreeNode node, Resource target) throws CoreException { ResourceInfo info = target.getResourceInfo(false, false); int flags = target.getFlags(info); if (target.exists(flags, true)) target = (File) ((Folder) target).changeToFile(); else { if (!target.exists(flags, false)) { target = (Resource) workspace.getRoot().getFile(target.getFullPath()); // Use the basic file creation protocol since we don't want to // create any content on disk. workspace.createResource(target, false); } } node.setResource(target); info = target.getResourceInfo(false, true); target.getLocalManager().updateLocalSync(info, node.getLastModified()); } /** * Returns the status of the nodes visited so far. This will be a multi-status * that describes all problems that have occurred, or an OK status if everything * went smoothly. */ public IStatus getErrorStatus() { return errors; } /** * Refreshes the parent of a resource currently being synchronized. */ protected void refresh(Container parent) throws CoreException { parent.getLocalManager().refresh(parent, IResource.DEPTH_ZERO, false, null); } protected void resourceChanged(UnifiedTreeNode node, Resource target) throws CoreException { ResourceInfo info = target.getResourceInfo(false, true); if (info == null) return; target.getLocalManager().updateLocalSync(info, node.getLastModified()); info.incrementContentId(); workspace.updateModificationStamp(info); } public boolean resourcesChanged() { return resourceChanged; } /** * deletion or creation -- Returns: * - RL_IN_SYNC - the resource is in-sync with the file system * - RL_NOT_IN_SYNC - the resource is not in-sync with file system * - RL_UNKNOWN - couldn't determine the sync status for this resource */ protected int synchronizeExistence(UnifiedTreeNode node, Resource target, int level) throws CoreException { boolean existsInWorkspace = node.existsInWorkspace(); if (!existsInWorkspace) { if (!CoreFileSystemLibrary.isCaseSensitive() && level == 0) { // do we have any alphabetic variants on the workspace? IResource variant = target.findExistingResourceVariant(target.getFullPath()); if (variant != null) return RL_UNKNOWN; } // do we have a gender variant in the workspace? IResource genderVariant = workspace.getRoot().findMember(target.getFullPath()); if (genderVariant != null) return RL_UNKNOWN; } if (existsInWorkspace) { if (!node.existsInFileSystem()) { //non-local files are always in sync if (target.isLocal(IResource.DEPTH_ZERO)) { deleteResource(node, target); resourceChanged = true; return RL_NOT_IN_SYNC; } else return RL_IN_SYNC; } } else { if (node.existsInFileSystem()) { if (!CoreFileSystemLibrary.isCaseSensitive()) { Container parent = (Container) target.getParent(); if (!parent.exists()) { refresh(parent); if (!parent.exists()) return RL_NOT_IN_SYNC; } if (!target.getName().equals(node.getLocalName())) return RL_IN_SYNC; } createResource(node, target); resourceChanged = true; return RL_NOT_IN_SYNC; } } return RL_UNKNOWN; } /** * gender change -- Returns true if gender was in sync. */ protected boolean synchronizeGender(UnifiedTreeNode node, Resource target) throws CoreException { if (!node.existsInWorkspace()) { //may be an existing resource in the workspace of different gender IResource genderVariant = workspace.getRoot().findMember(target.getFullPath()); if (genderVariant != null) target = (Resource)genderVariant; } if (target.getType() == IResource.FILE) { if (!node.isFile()) { fileToFolder(node, target); resourceChanged = true; return false; } } else { if (!node.isFolder()) { folderToFile(node, target); resourceChanged = true; return false; } } return true; } /** * lastModified */ protected void synchronizeLastModified(UnifiedTreeNode node, Resource target) throws CoreException { if (target.isLocal(IResource.DEPTH_ZERO)) resourceChanged(node, target); else contentAdded(node, target); resourceChanged = true; } public boolean visit(UnifiedTreeNode node) throws CoreException { Policy.checkCanceled(monitor); try { Resource target = (Resource) node.getResource(); int targetType = target.getType(); if (targetType == IResource.PROJECT) return true; if (node.existsInWorkspace() && node.existsInFileSystem()) { /* for folders we only care about updating local status */ if (targetType == IResource.FOLDER && node.isFolder()) { // if not local, mark as local if (!target.isLocal(IResource.DEPTH_ZERO)) { ResourceInfo info = target.getResourceInfo(false, true); if (info == null) return true; target.getLocalManager().updateLocalSync(info, node.getLastModified()); } return true; } /* compare file last modified */ if (targetType == IResource.FILE && node.isFile()) { - long lastModifed = target.getResourceInfo(false, false).getLocalSyncInfo(); - if (lastModifed == node.getLastModified()) + ResourceInfo info = target.getResourceInfo(false, false); + if (info != null && info.getLocalSyncInfo() == node.getLastModified()) return true; } } else { if (node.existsInFileSystem() && !Path.EMPTY.isValidSegment(node.getLocalName())) { String message = Policy.bind("resources.invalidResourceName", node.getLocalName()); //$NON-NLS-1$ errors.merge(new ResourceStatus(IResourceStatus.INVALID_RESOURCE_NAME, message)); return false; } int state = synchronizeExistence(node, target, node.getLevel()); if (state == RL_IN_SYNC || state == RL_NOT_IN_SYNC) { if (targetType == IResource.FILE) { try { ((File)target).updateProjectDescription(); } catch (CoreException e) { errors.merge(e.getStatus()); } } return true; } } if (synchronizeGender(node, target)) synchronizeLastModified(node, target); if (targetType == IResource.FILE) { try { ((File)target).updateProjectDescription(); } catch (CoreException e) { errors.merge(e.getStatus()); } } return true; } finally { if (--nextProgress <= 0) { //we have exhausted the current increment, so report progress monitor.worked(1); worked++; if (worked >= halfWay) { //we have passed the current halfway point, so double the //increment and reset the halfway point. currentIncrement *= 2; halfWay += (TOTAL_WORK - halfWay) / 2; } //reset the progress counter to another full increment nextProgress = currentIncrement; } } } }
true
true
public boolean visit(UnifiedTreeNode node) throws CoreException { Policy.checkCanceled(monitor); try { Resource target = (Resource) node.getResource(); int targetType = target.getType(); if (targetType == IResource.PROJECT) return true; if (node.existsInWorkspace() && node.existsInFileSystem()) { /* for folders we only care about updating local status */ if (targetType == IResource.FOLDER && node.isFolder()) { // if not local, mark as local if (!target.isLocal(IResource.DEPTH_ZERO)) { ResourceInfo info = target.getResourceInfo(false, true); if (info == null) return true; target.getLocalManager().updateLocalSync(info, node.getLastModified()); } return true; } /* compare file last modified */ if (targetType == IResource.FILE && node.isFile()) { long lastModifed = target.getResourceInfo(false, false).getLocalSyncInfo(); if (lastModifed == node.getLastModified()) return true; } } else { if (node.existsInFileSystem() && !Path.EMPTY.isValidSegment(node.getLocalName())) { String message = Policy.bind("resources.invalidResourceName", node.getLocalName()); //$NON-NLS-1$ errors.merge(new ResourceStatus(IResourceStatus.INVALID_RESOURCE_NAME, message)); return false; } int state = synchronizeExistence(node, target, node.getLevel()); if (state == RL_IN_SYNC || state == RL_NOT_IN_SYNC) { if (targetType == IResource.FILE) { try { ((File)target).updateProjectDescription(); } catch (CoreException e) { errors.merge(e.getStatus()); } } return true; } } if (synchronizeGender(node, target)) synchronizeLastModified(node, target); if (targetType == IResource.FILE) { try { ((File)target).updateProjectDescription(); } catch (CoreException e) { errors.merge(e.getStatus()); } } return true; } finally { if (--nextProgress <= 0) { //we have exhausted the current increment, so report progress monitor.worked(1); worked++; if (worked >= halfWay) { //we have passed the current halfway point, so double the //increment and reset the halfway point. currentIncrement *= 2; halfWay += (TOTAL_WORK - halfWay) / 2; } //reset the progress counter to another full increment nextProgress = currentIncrement; } } }
public boolean visit(UnifiedTreeNode node) throws CoreException { Policy.checkCanceled(monitor); try { Resource target = (Resource) node.getResource(); int targetType = target.getType(); if (targetType == IResource.PROJECT) return true; if (node.existsInWorkspace() && node.existsInFileSystem()) { /* for folders we only care about updating local status */ if (targetType == IResource.FOLDER && node.isFolder()) { // if not local, mark as local if (!target.isLocal(IResource.DEPTH_ZERO)) { ResourceInfo info = target.getResourceInfo(false, true); if (info == null) return true; target.getLocalManager().updateLocalSync(info, node.getLastModified()); } return true; } /* compare file last modified */ if (targetType == IResource.FILE && node.isFile()) { ResourceInfo info = target.getResourceInfo(false, false); if (info != null && info.getLocalSyncInfo() == node.getLastModified()) return true; } } else { if (node.existsInFileSystem() && !Path.EMPTY.isValidSegment(node.getLocalName())) { String message = Policy.bind("resources.invalidResourceName", node.getLocalName()); //$NON-NLS-1$ errors.merge(new ResourceStatus(IResourceStatus.INVALID_RESOURCE_NAME, message)); return false; } int state = synchronizeExistence(node, target, node.getLevel()); if (state == RL_IN_SYNC || state == RL_NOT_IN_SYNC) { if (targetType == IResource.FILE) { try { ((File)target).updateProjectDescription(); } catch (CoreException e) { errors.merge(e.getStatus()); } } return true; } } if (synchronizeGender(node, target)) synchronizeLastModified(node, target); if (targetType == IResource.FILE) { try { ((File)target).updateProjectDescription(); } catch (CoreException e) { errors.merge(e.getStatus()); } } return true; } finally { if (--nextProgress <= 0) { //we have exhausted the current increment, so report progress monitor.worked(1); worked++; if (worked >= halfWay) { //we have passed the current halfway point, so double the //increment and reset the halfway point. currentIncrement *= 2; halfWay += (TOTAL_WORK - halfWay) / 2; } //reset the progress counter to another full increment nextProgress = currentIncrement; } } }
diff --git a/src/com/judoguys/bukkit/gps/GPS.java b/src/com/judoguys/bukkit/gps/GPS.java index d2697be..e5c9077 100644 --- a/src/com/judoguys/bukkit/gps/GPS.java +++ b/src/com/judoguys/bukkit/gps/GPS.java @@ -1,249 +1,249 @@ package com.judoguys.bukkit.gps; /** * Copyright (C) 2011 William Bowers <http://williambowers.net/> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import com.judoguys.bukkit.commands.Action; import com.judoguys.bukkit.commands.CommandHandler; import com.judoguys.bukkit.commands.InvalidCommandException; import com.judoguys.bukkit.gps.actions.FindAction; import com.judoguys.bukkit.gps.actions.FollowAction; import com.judoguys.bukkit.gps.actions.PointToAction; import com.judoguys.bukkit.gps.actions.ResetAction; import com.judoguys.bukkit.gps.actions.SetIsHiddenAction; import com.judoguys.bukkit.gps.configuration.GPSConfiguration; import com.judoguys.bukkit.utils.CommandUtils; import com.judoguys.bukkit.utils.MessageUtils; import java.io.File; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.logging.Level; import java.util.logging.Logger; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.event.Event.Priority; import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; /** * GPS - A plugin that provides location-based information and compass * reorienting. * * Allows players to: * - Point their compass to another player's current location. * - Make their compass follow another player around, and update as * they move. * - Point their compass to spawn. * - Point their compass at a specific set of coordinates. * * In the future, will allow players to: * - Save all of their settings so they persist across server runs. ^_^ * - Name coordinates and point to them by their names. * - List all of their named coordinates. * - Find out how far (in blocks) they are away from a location * or player. * - Disallow others from locating them using GPS (and reallow). * - See where their compass is currently pointing. * - See the coordinates of a named location or player. * - See the coordinates of where they are currently standing. * * See the TODO file for more information on what's planned for GPS. */ public class GPS extends JavaPlugin { public static String COMMAND_NAME = "gps"; public Logger log; public PluginManager pm; public HashMap<String, GPSConfiguration> configurations; private GPSPlayerListener playerListener; private CommandHandler commandHandler; private PluginDescriptionFile desc; private File playersFolder; private String version; private String label; public GPS () { // Does nothing. } /** * Returns a string that identifies this plugin, mostly used * for logging. */ public String getLabel () { return label; } /** * Returns the players folder, where all of the player-specific * GPS information is stored. */ public File getPlayersFolder () { return playersFolder; } /** * Called when the plugin is enabled. */ public void onEnable () { log = getServer().getLogger(); configurations = new HashMap<String, GPSConfiguration>(); desc = getDescription(); version = desc.getVersion(); label = "[" + desc.getName() + "]"; log.info(getLabel() + " version " + version + " by willurd"); pm = getServer().getPluginManager(); playerListener = new GPSPlayerListener(this); pm.registerEvent(Event.Type.PLAYER_JOIN, playerListener, Priority.Normal, this); pm.registerEvent(Event.Type.PLAYER_MOVE, playerListener, Priority.Normal, this); pm.registerEvent(Event.Type.PLAYER_TELEPORT, playerListener, Priority.Normal, this); File dataFolder = getDataFolder(); playersFolder = new File(dataFolder.getAbsolutePath() + "/players/"); loadSettings(); setupPermissions(); setupCommands(); log.info(getLabel() + " enabled!"); } /** * Called when the plugin is disabled (either disabled explicitely, * or when the server is gracefully shutdown). */ @Override public void onDisable () { // TODO: What should be done here?. log.info(getLabel() + " disabled"); } /** * Handles commands from a client (any sentance that starts with "/sometext"). */ @Override public boolean onCommand (CommandSender sender, Command cmd, String label, String[] args) { String name = cmd.getName(); if (name.equalsIgnoreCase(COMMAND_NAME)) { if (!(sender instanceof Player)) { MessageUtils.sendError(sender, "GPS can only be used in game"); return true; } try { boolean handled = commandHandler.handleCommand(sender, cmd, label, args); if (!handled) { throw new InvalidCommandException("Invalid command"); } return handled; } catch (InvalidCommandException ex) { MessageUtils.sendError(sender, "Invalid command: " + CommandUtils.buildCommandString(cmd, args)); return false; } } - return true; + return super.onCommand(sender, cmd, label, args); } /** * Load in the settings files, which make gps settings persistent * across server runs. */ private void loadSettings () { // Make sure we have all the folders we need for this to work. ensureDataDirectoriesExist(); // TODO: Load plugin-wide settings, like the command for example. } /** * Creates the directories this plugin uses to store its data. */ private void ensureDataDirectoriesExist () { // Make sure the data folder exists. File dataFolder = getDataFolder(); if (!dataFolder.exists()) { log.info(getLabel() + " Data folder does not exist. Creating it now."); dataFolder.mkdir(); } // Make sure the players folder exists. File playersFolder = getPlayersFolder(); if (!playersFolder.exists()) { log.info(getLabel() + " Players folder does not exist. Creating it now."); playersFolder.mkdir(); } } /** * NOTE: Permissions is not supported...yet. * * Thought this does nothing now, once permissions is supported * it will load the permissions information and do the requisite * setup. */ private void setupPermissions () { } /** * This is where Actions are registered with the command handler. * If an action is not registered here, it won't get handled. * * If you want to add a new sub command to /gps, like '/gps orbit', * create a new Action class, OribitAction, and register an instance * of it here. */ private void setupCommands () { commandHandler = new CommandHandler(this); commandHandler.addAction(new FindAction(this)); commandHandler.addAction(new FollowAction(this)); commandHandler.addAction(new PointToAction(this)); commandHandler.addAction(new ResetAction(this)); commandHandler.addAction(new SetIsHiddenAction(this, "hide", true, "Prevents you from being located")); commandHandler.addAction(new SetIsHiddenAction(this, "unhide", false, "Allows you to be located")); } }
true
true
public boolean onCommand (CommandSender sender, Command cmd, String label, String[] args) { String name = cmd.getName(); if (name.equalsIgnoreCase(COMMAND_NAME)) { if (!(sender instanceof Player)) { MessageUtils.sendError(sender, "GPS can only be used in game"); return true; } try { boolean handled = commandHandler.handleCommand(sender, cmd, label, args); if (!handled) { throw new InvalidCommandException("Invalid command"); } return handled; } catch (InvalidCommandException ex) { MessageUtils.sendError(sender, "Invalid command: " + CommandUtils.buildCommandString(cmd, args)); return false; } } return true; }
public boolean onCommand (CommandSender sender, Command cmd, String label, String[] args) { String name = cmd.getName(); if (name.equalsIgnoreCase(COMMAND_NAME)) { if (!(sender instanceof Player)) { MessageUtils.sendError(sender, "GPS can only be used in game"); return true; } try { boolean handled = commandHandler.handleCommand(sender, cmd, label, args); if (!handled) { throw new InvalidCommandException("Invalid command"); } return handled; } catch (InvalidCommandException ex) { MessageUtils.sendError(sender, "Invalid command: " + CommandUtils.buildCommandString(cmd, args)); return false; } } return super.onCommand(sender, cmd, label, args); }
diff --git a/src/examples/Example.java b/src/examples/Example.java index ea20c8d..3dfa550 100644 --- a/src/examples/Example.java +++ b/src/examples/Example.java @@ -1,95 +1,95 @@ package examples; import trains.*; public class Example { private static final class myCallbackCircuitChange implements CallbackCircuitChange{ public myCallbackCircuitChange(){ //Nothing to do } @Override public void run(CircuitView cv){ //Printing the circuit modification //Printing the new/departed participant if(cv.getJoined() != 0){ System.out.println(Integer.toString(cv.getJoined()) + "has arrived."); } else { System.out.println(Integer.toString(cv.getDeparted()) + "is gone."); } //Printing the current number of members System.out.println("Currently " + cv.getMemb() + " in the circuit."); } } private static final class myCallbackUtoDeliver implements CallbackUtoDeliver{ public myCallbackUtoDeliver(){ //Nothing to do } @Override public void run(int sender, Message msg){ //Printing the message sender and the content upon receiving a message System.out.println("I received a message from " + sender); System.out.println("The content size is " + msg.getMessageHeader().getLen()); System.out.println("The content is " + msg.getPayload()); } } - public static void main() { + public static void main(String args[]) { //trInit parameters: values by default int trainsNumber = 0; int wagonLength = 0; int waitNb = 0; int waitTime = 0; myCallbackCircuitChange mycallbackCircuit = new myCallbackCircuitChange(); myCallbackUtoDeliver mycallbackUto = new myCallbackUtoDeliver(); int payload = 0; Message msg = null; int exitcode; System.out.println("** Load interface"); Interface trin = Interface.trainsInterface(); System.out.println("** trInit"); exitcode = trin.JtrInit(trainsNumber, wagonLength, waitNb, waitTime, mycallbackCircuit.getClass().getName(), mycallbackUto.getClass().getName()); if (exitcode < 0){ System.out.println("JtrInit failed."); return; } payload = 3; //Filling the message System.out.println("** Filling a message"); msg = Message.messageFromPayload(String.valueOf(payload)); //Needed to keep count of the messages System.out.println("** JnewMsg"); trin.JnewMsg(msg.getMessageHeader().getLen()); //Sending the message System.out.println("** JutoBroadcast"); exitcode = trin.JutoBroadcast(msg); if (exitcode < 0){ System.out.println("JutoBroadcast failed."); return; } System.out.println("JtrTerminate"); exitcode = trin.JtrTerminate(); return; } }
true
true
public static void main() { //trInit parameters: values by default int trainsNumber = 0; int wagonLength = 0; int waitNb = 0; int waitTime = 0; myCallbackCircuitChange mycallbackCircuit = new myCallbackCircuitChange(); myCallbackUtoDeliver mycallbackUto = new myCallbackUtoDeliver(); int payload = 0; Message msg = null; int exitcode; System.out.println("** Load interface"); Interface trin = Interface.trainsInterface(); System.out.println("** trInit"); exitcode = trin.JtrInit(trainsNumber, wagonLength, waitNb, waitTime, mycallbackCircuit.getClass().getName(), mycallbackUto.getClass().getName()); if (exitcode < 0){ System.out.println("JtrInit failed."); return; } payload = 3; //Filling the message System.out.println("** Filling a message"); msg = Message.messageFromPayload(String.valueOf(payload)); //Needed to keep count of the messages System.out.println("** JnewMsg"); trin.JnewMsg(msg.getMessageHeader().getLen()); //Sending the message System.out.println("** JutoBroadcast"); exitcode = trin.JutoBroadcast(msg); if (exitcode < 0){ System.out.println("JutoBroadcast failed."); return; } System.out.println("JtrTerminate"); exitcode = trin.JtrTerminate(); return; }
public static void main(String args[]) { //trInit parameters: values by default int trainsNumber = 0; int wagonLength = 0; int waitNb = 0; int waitTime = 0; myCallbackCircuitChange mycallbackCircuit = new myCallbackCircuitChange(); myCallbackUtoDeliver mycallbackUto = new myCallbackUtoDeliver(); int payload = 0; Message msg = null; int exitcode; System.out.println("** Load interface"); Interface trin = Interface.trainsInterface(); System.out.println("** trInit"); exitcode = trin.JtrInit(trainsNumber, wagonLength, waitNb, waitTime, mycallbackCircuit.getClass().getName(), mycallbackUto.getClass().getName()); if (exitcode < 0){ System.out.println("JtrInit failed."); return; } payload = 3; //Filling the message System.out.println("** Filling a message"); msg = Message.messageFromPayload(String.valueOf(payload)); //Needed to keep count of the messages System.out.println("** JnewMsg"); trin.JnewMsg(msg.getMessageHeader().getLen()); //Sending the message System.out.println("** JutoBroadcast"); exitcode = trin.JutoBroadcast(msg); if (exitcode < 0){ System.out.println("JutoBroadcast failed."); return; } System.out.println("JtrTerminate"); exitcode = trin.JtrTerminate(); return; }
diff --git a/MonTransit/src/org/montrealtransit/android/api/SupportFactory.java b/MonTransit/src/org/montrealtransit/android/api/SupportFactory.java index 7832e607..ebfc359d 100755 --- a/MonTransit/src/org/montrealtransit/android/api/SupportFactory.java +++ b/MonTransit/src/org/montrealtransit/android/api/SupportFactory.java @@ -1,46 +1,46 @@ package org.montrealtransit.android.api; import org.montrealtransit.android.MyLog; import android.content.Context; import android.os.Build; public class SupportFactory { private static final String TAG = SupportFactory.class.getSimpleName(); public static SupportUtil getInstance(Context context) { String className = SupportFactory.class.getPackage().getName(); int sdkVersion = Integer.parseInt(Build.VERSION.SDK); if (sdkVersion < Build.VERSION_CODES.CUPCAKE) { MyLog.d(TAG, "Unknow API Level: " + sdkVersion); className += ".CupcakeSupport"; // unsupported version } else if (sdkVersion == Build.VERSION_CODES.CUPCAKE) { className += ".CupcakeSupport"; // 3 } else if (sdkVersion == Build.VERSION_CODES.DONUT) { className += ".DonutSupport"; // 4 } else if (sdkVersion == Build.VERSION_CODES.ECLAIR || sdkVersion == Build.VERSION_CODES.ECLAIR_0_1 || sdkVersion == Build.VERSION_CODES.ECLAIR_MR1) { className += ".EclairSupport"; // 5 6 7 } else if (sdkVersion == Build.VERSION_CODES.FROYO) { className += ".FroyoSupport"; // 8 } else if (sdkVersion == Build.VERSION_CODES.GINGERBREAD || sdkVersion == Build.VERSION_CODES.GINGERBREAD_MR1) { className += ".GingerbreadSupport"; // 9 10 - } else if (sdkVersion == Build.VERSION_CODES.HONEYCOMB || sdkVersion == Build.VERSION_CODES.HONEYCOMB_MR1) { - className += ".HoneycombSupport"; // 11 12 + } else if (sdkVersion == Build.VERSION_CODES.HONEYCOMB || sdkVersion == Build.VERSION_CODES.HONEYCOMB_MR1 || sdkVersion == Build.VERSION_CODES.HONEYCOMB_MR2) { + className += ".HoneycombSupport"; // 11 12 13 } else if (sdkVersion == Build.VERSION_CODES.ICE_CREAM_SANDWICH) { - className += ".IceCreamSandwichSupport"; // 13 + className += ".IceCreamSandwichSupport"; // 14 } else if (sdkVersion > Build.VERSION_CODES.ICE_CREAM_SANDWICH) { MyLog.w(TAG, "Unknow API Level: %s", Build.VERSION.SDK); className += ".IceCreamSandwichSupport"; // default for newer SDK } try { Class<?> detectorClass = Class.forName(className); return (SupportUtil) detectorClass.getConstructor(Context.class).newInstance(context); } catch (Exception e) { MyLog.e(TAG, e, "INTERNAL ERROR!"); throw new RuntimeException(e); } } }
false
true
public static SupportUtil getInstance(Context context) { String className = SupportFactory.class.getPackage().getName(); int sdkVersion = Integer.parseInt(Build.VERSION.SDK); if (sdkVersion < Build.VERSION_CODES.CUPCAKE) { MyLog.d(TAG, "Unknow API Level: " + sdkVersion); className += ".CupcakeSupport"; // unsupported version } else if (sdkVersion == Build.VERSION_CODES.CUPCAKE) { className += ".CupcakeSupport"; // 3 } else if (sdkVersion == Build.VERSION_CODES.DONUT) { className += ".DonutSupport"; // 4 } else if (sdkVersion == Build.VERSION_CODES.ECLAIR || sdkVersion == Build.VERSION_CODES.ECLAIR_0_1 || sdkVersion == Build.VERSION_CODES.ECLAIR_MR1) { className += ".EclairSupport"; // 5 6 7 } else if (sdkVersion == Build.VERSION_CODES.FROYO) { className += ".FroyoSupport"; // 8 } else if (sdkVersion == Build.VERSION_CODES.GINGERBREAD || sdkVersion == Build.VERSION_CODES.GINGERBREAD_MR1) { className += ".GingerbreadSupport"; // 9 10 } else if (sdkVersion == Build.VERSION_CODES.HONEYCOMB || sdkVersion == Build.VERSION_CODES.HONEYCOMB_MR1) { className += ".HoneycombSupport"; // 11 12 } else if (sdkVersion == Build.VERSION_CODES.ICE_CREAM_SANDWICH) { className += ".IceCreamSandwichSupport"; // 13 } else if (sdkVersion > Build.VERSION_CODES.ICE_CREAM_SANDWICH) { MyLog.w(TAG, "Unknow API Level: %s", Build.VERSION.SDK); className += ".IceCreamSandwichSupport"; // default for newer SDK } try { Class<?> detectorClass = Class.forName(className); return (SupportUtil) detectorClass.getConstructor(Context.class).newInstance(context); } catch (Exception e) { MyLog.e(TAG, e, "INTERNAL ERROR!"); throw new RuntimeException(e); } }
public static SupportUtil getInstance(Context context) { String className = SupportFactory.class.getPackage().getName(); int sdkVersion = Integer.parseInt(Build.VERSION.SDK); if (sdkVersion < Build.VERSION_CODES.CUPCAKE) { MyLog.d(TAG, "Unknow API Level: " + sdkVersion); className += ".CupcakeSupport"; // unsupported version } else if (sdkVersion == Build.VERSION_CODES.CUPCAKE) { className += ".CupcakeSupport"; // 3 } else if (sdkVersion == Build.VERSION_CODES.DONUT) { className += ".DonutSupport"; // 4 } else if (sdkVersion == Build.VERSION_CODES.ECLAIR || sdkVersion == Build.VERSION_CODES.ECLAIR_0_1 || sdkVersion == Build.VERSION_CODES.ECLAIR_MR1) { className += ".EclairSupport"; // 5 6 7 } else if (sdkVersion == Build.VERSION_CODES.FROYO) { className += ".FroyoSupport"; // 8 } else if (sdkVersion == Build.VERSION_CODES.GINGERBREAD || sdkVersion == Build.VERSION_CODES.GINGERBREAD_MR1) { className += ".GingerbreadSupport"; // 9 10 } else if (sdkVersion == Build.VERSION_CODES.HONEYCOMB || sdkVersion == Build.VERSION_CODES.HONEYCOMB_MR1 || sdkVersion == Build.VERSION_CODES.HONEYCOMB_MR2) { className += ".HoneycombSupport"; // 11 12 13 } else if (sdkVersion == Build.VERSION_CODES.ICE_CREAM_SANDWICH) { className += ".IceCreamSandwichSupport"; // 14 } else if (sdkVersion > Build.VERSION_CODES.ICE_CREAM_SANDWICH) { MyLog.w(TAG, "Unknow API Level: %s", Build.VERSION.SDK); className += ".IceCreamSandwichSupport"; // default for newer SDK } try { Class<?> detectorClass = Class.forName(className); return (SupportUtil) detectorClass.getConstructor(Context.class).newInstance(context); } catch (Exception e) { MyLog.e(TAG, e, "INTERNAL ERROR!"); throw new RuntimeException(e); } }
diff --git a/src/game/MovingObject.java b/src/game/MovingObject.java index df06d01..ebd66c0 100644 --- a/src/game/MovingObject.java +++ b/src/game/MovingObject.java @@ -1,108 +1,108 @@ package game; import game.gameplayStates.GamePlayState; public class MovingObject extends GameObject{ protected GamePlayState m_game; protected static final int SIZE = 64; protected static final int BUFFER = 14; protected static final int RAD = 30; protected float m_x, m_y; public float getX() { return m_x; } public void setX(float x) { m_x = x; } public float getY() { return m_y; } public void setY(float y) { m_y = y; } public MovingObject(GamePlayState game){ m_game = game; this.setName("MovingObject"); } public MovingObject(String name, GamePlayState game) { super(name); m_game = game; } /** * Moves the MovingObject in the given direction, with the given * delta. * @param dir * @param delta */ protected void move(Direction dir, int delta) { if(dir==Direction.DOWN) { if (!isBlocked(m_x, m_y + SIZE + delta * 0.1f, dir)) { m_y += delta * 0.1f; } } else if(dir==Direction.LEFT) { if (!isBlocked(m_x - delta * 0.1f, m_y, Direction.LEFT)) { m_x -= delta * 0.1f; } } else if(dir==Direction.RIGHT) { if (!isBlocked(m_x + SIZE + delta * 0.1f, m_y, Direction.RIGHT)) { m_x += delta * 0.1f; } } else if(dir==Direction.UP) { if (!isBlocked(m_x, m_y - delta * 0.1f, Direction.UP)) { m_y -= delta * 0.1f; } } } protected boolean isBlocked(float x, float y, Direction dir) { switch(dir){ case UP: { int xBlock1 = ((int)x +BUFFER) / SIZE; int yBlock = (int)y / SIZE; int xBlock2 = ((int)x + SIZE-BUFFER)/SIZE; return m_game.blocked(xBlock1, yBlock)|m_game.blocked(xBlock2, yBlock); } case DOWN: { int xBlock1 = ((int)x +BUFFER) / SIZE; int yBlock = (int)y / SIZE; int xBlock2 = ((int)x + SIZE-BUFFER)/SIZE; return m_game.blocked(xBlock1, yBlock)|m_game.blocked(xBlock2, yBlock); } case LEFT: { int xBlock = (int)x / SIZE; int yBlock1 = ((int)y +BUFFER)/ SIZE; - int yBlock2 = ((int) y +SIZE - BUFFER)/SIZE; + int yBlock2 = ((int) y +SIZE - 2)/SIZE; return m_game.blocked(xBlock, yBlock1)||m_game.blocked(xBlock, yBlock2); } case RIGHT: { int xBlock = (int)x / SIZE; int yBlock1 = ((int)y +BUFFER)/ SIZE; - int yBlock2 = ((int) y +SIZE - BUFFER)/SIZE; + int yBlock2 = ((int) y +SIZE - 2)/SIZE; return m_game.blocked(xBlock, yBlock1)||m_game.blocked(xBlock, yBlock2); } default: { System.out.println("ERROR WHRE IS THIS " + dir + " ENUM COMING FROM"); return false; } } } @Override public boolean isBlocking() { return false; } @Override public int[] getSquare() { // TODO Auto-generated method stub return new int[] {(int) (m_x/SIZE), (int) (m_y/SIZE)}; } @Override public Types getType() { // TODO Auto-generated method stub return null; } protected boolean checkCollision(MovingObject mo1, MovingObject mo2){ if(mo1.m_game!=mo2.m_game) return false; float xDist = mo1.getX()-mo2.getX(); float yDist = mo1.getY()-mo2.getY(); float radSum = 2*RAD; return radSum*radSum>xDist*xDist+yDist*yDist; } }
false
true
protected boolean isBlocked(float x, float y, Direction dir) { switch(dir){ case UP: { int xBlock1 = ((int)x +BUFFER) / SIZE; int yBlock = (int)y / SIZE; int xBlock2 = ((int)x + SIZE-BUFFER)/SIZE; return m_game.blocked(xBlock1, yBlock)|m_game.blocked(xBlock2, yBlock); } case DOWN: { int xBlock1 = ((int)x +BUFFER) / SIZE; int yBlock = (int)y / SIZE; int xBlock2 = ((int)x + SIZE-BUFFER)/SIZE; return m_game.blocked(xBlock1, yBlock)|m_game.blocked(xBlock2, yBlock); } case LEFT: { int xBlock = (int)x / SIZE; int yBlock1 = ((int)y +BUFFER)/ SIZE; int yBlock2 = ((int) y +SIZE - BUFFER)/SIZE; return m_game.blocked(xBlock, yBlock1)||m_game.blocked(xBlock, yBlock2); } case RIGHT: { int xBlock = (int)x / SIZE; int yBlock1 = ((int)y +BUFFER)/ SIZE; int yBlock2 = ((int) y +SIZE - BUFFER)/SIZE; return m_game.blocked(xBlock, yBlock1)||m_game.blocked(xBlock, yBlock2); } default: { System.out.println("ERROR WHRE IS THIS " + dir + " ENUM COMING FROM"); return false; } } }
protected boolean isBlocked(float x, float y, Direction dir) { switch(dir){ case UP: { int xBlock1 = ((int)x +BUFFER) / SIZE; int yBlock = (int)y / SIZE; int xBlock2 = ((int)x + SIZE-BUFFER)/SIZE; return m_game.blocked(xBlock1, yBlock)|m_game.blocked(xBlock2, yBlock); } case DOWN: { int xBlock1 = ((int)x +BUFFER) / SIZE; int yBlock = (int)y / SIZE; int xBlock2 = ((int)x + SIZE-BUFFER)/SIZE; return m_game.blocked(xBlock1, yBlock)|m_game.blocked(xBlock2, yBlock); } case LEFT: { int xBlock = (int)x / SIZE; int yBlock1 = ((int)y +BUFFER)/ SIZE; int yBlock2 = ((int) y +SIZE - 2)/SIZE; return m_game.blocked(xBlock, yBlock1)||m_game.blocked(xBlock, yBlock2); } case RIGHT: { int xBlock = (int)x / SIZE; int yBlock1 = ((int)y +BUFFER)/ SIZE; int yBlock2 = ((int) y +SIZE - 2)/SIZE; return m_game.blocked(xBlock, yBlock1)||m_game.blocked(xBlock, yBlock2); } default: { System.out.println("ERROR WHRE IS THIS " + dir + " ENUM COMING FROM"); return false; } } }
diff --git a/src/main/java/net/dandielo/citizens/trader/types/ServerTrader.java b/src/main/java/net/dandielo/citizens/trader/types/ServerTrader.java index 696efb4..9a86400 100644 --- a/src/main/java/net/dandielo/citizens/trader/types/ServerTrader.java +++ b/src/main/java/net/dandielo/citizens/trader/types/ServerTrader.java @@ -1,950 +1,941 @@ package net.dandielo.citizens.trader.types; import java.text.DecimalFormat; import java.text.NumberFormat; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.GameMode; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.inventory.ItemStack; import net.citizensnpcs.api.npc.NPC; import net.dandielo.citizens.trader.CitizensTrader; import net.dandielo.citizens.trader.TraderTrait; import net.dandielo.citizens.trader.TraderTrait.EType; import net.dandielo.citizens.trader.events.TraderOpenEvent; import net.dandielo.citizens.trader.events.TraderTransactionEvent; import net.dandielo.citizens.trader.events.TraderTransactionEvent.TransactionResult; import net.dandielo.citizens.trader.limits.Limits.Limit; import net.dandielo.citizens.trader.locale.LocaleManager; import net.dandielo.citizens.trader.objects.MetaTools; import net.dandielo.citizens.trader.objects.StockItem; import net.dandielo.citizens.trader.parts.TraderStockPart; import net.dandielo.citizens.trader.patterns.TPattern; public class ServerTrader extends Trader { // private TPattern pattern = getStock().getPattern(); private LocaleManager locale = CitizensTrader.getLocaleManager(); public ServerTrader(TraderTrait trait, NPC npc, Player player) { super(trait, npc, player); } @Override public void simpleMode(InventoryClickEvent event) { NumberFormat f = NumberFormat.getCurrencyInstance(); int slot = event.getSlot(); if ( slot < 0 ) { event.setCursor(null); return; } boolean top = event.getView().convertSlot(event.getRawSlot()) == event.getRawSlot(); if ( top ) { if ( event.isShiftClick() ) { ((Player)event.getWhoClicked()).sendMessage(ChatColor.GOLD + "You can't shift click this, Sorry"); event.setCancelled(true); return; } if ( isManagementSlot(slot, 1) ) { if ( isWool(event.getCurrentItem(), itemsConfig.getItemManagement(7)) ) { switchInventory(TraderStatus.SELL); } else if ( isWool(event.getCurrentItem(), itemsConfig.getItemManagement(0)) ) { if ( !permissionsManager.has(player, "dtl.trader.options.sell") ) { locale.sendMessage(player, "error-nopermission"); } else { switchInventory(TraderStatus.SELL); } } else if ( isWool(event.getCurrentItem(), itemsConfig.getItemManagement(1)) ) { if ( !permissionsManager.has(player, "dtl.trader.options.buy") ) { locale.sendMessage(player, "error-nopermission"); } else { switchInventory(TraderStatus.BUY); } } } else if ( equalsTraderStatus(TraderStatus.SELL) ) { if ( selectItem(slot, TraderStatus.SELL).hasSelectedItem() ) { if ( getSelectedItem().hasMultipleAmounts() && permissionsManager.has(player, "dtl.trader.options.sell-amounts") ) { switchInventory(getSelectedItem()); setTraderStatus(TraderStatus.SELL_AMOUNT); } else { double price = getPrice(player, "sell"); //checks if ( !checkLimits() ) { Bukkit.getServer().getPluginManager().callEvent(new TraderTransactionEvent(this, this.getNpc(), player, this.getTraderStatus(), this.getSelectedItem(), price, TransactionResult.FAIL_LIMIT)); locale.sendMessage(player, "trader-transaction-failed-limit"); } else if ( !inventoryHasPlace(0) ) { locale.sendMessage(player, "trader-transaction-failed-inventory"); Bukkit.getServer().getPluginManager().callEvent(new TraderTransactionEvent(this, this.getNpc(), player, this.getTraderStatus(), this.getSelectedItem(), price, TransactionResult.FAIL_SPACE)); } else if ( !buyTransaction(price) ) { locale.sendMessage(player, "trader-transaction-failed-money"); Bukkit.getServer().getPluginManager().callEvent(new TraderTransactionEvent(this, this.getNpc(), player, this.getTraderStatus(), this.getSelectedItem(), price, TransactionResult.FAIL_MONEY)); } else { locale.sendMessage(player, "trader-transaction-success", "action", "#bought", "amount", String.valueOf(getSelectedItem().getAmount()), "price", f.format(price).replace("$", "")); addSelectedToInventory(0); updateLimits(); //call event Denizen Transaction Trigger Bukkit.getServer().getPluginManager().callEvent(new TraderTransactionEvent(this, this.getNpc(), player, this.getTraderStatus(), this.getSelectedItem(), price, TransactionResult.SUCCESS_SELL)); //logging log("buy", getSelectedItem().getItemStack().getTypeId(), getSelectedItem().getItemStack().getData().getData(), getSelectedItem().getAmount(), price ); } } } } else if ( equalsTraderStatus(TraderStatus.SELL_AMOUNT) ) { if ( !event.getCurrentItem().getType().equals(Material.AIR) ) { double price = getPrice(player, "sell", slot); if ( !checkLimits(slot) ) { Bukkit.getServer().getPluginManager().callEvent(new TraderTransactionEvent(this, this.getNpc(), player, this.getTraderStatus(), this.getSelectedItem(), price, TransactionResult.FAIL_LIMIT)); locale.sendMessage(player, "trader-transaction-failed-limit"); } else if ( !inventoryHasPlace(slot) ) { Bukkit.getServer().getPluginManager().callEvent(new TraderTransactionEvent(this, this.getNpc(), player, this.getTraderStatus(), this.getSelectedItem(), price, TransactionResult.FAIL_SPACE)); locale.sendMessage(player, "trader-transaction-failed-inventory"); } else if ( !buyTransaction(price) ) { Bukkit.getServer().getPluginManager().callEvent(new TraderTransactionEvent(this, this.getNpc(), player, this.getTraderStatus(), this.getSelectedItem(), price, TransactionResult.FAIL_MONEY)); locale.sendMessage(player, "trader-transaction-failed-money"); } else { locale.sendMessage(player, "trader-transaction-success", "action", "#bought", "amount", String.valueOf(getSelectedItem().getAmount()), "price", f.format(price).replace("$", "")); addSelectedToInventory(slot); Bukkit.getServer().getPluginManager().callEvent(new TraderTransactionEvent(this, this.getNpc(), event.getWhoClicked(), this.getTraderStatus(), this.getSelectedItem(), price, TransactionResult.SUCCESS_SELL)); updateLimits(slot); switchInventory(getSelectedItem()); //logging log("buy", getSelectedItem().getItemStack().getTypeId(), getSelectedItem().getItemStack().getData().getData(), getSelectedItem().getAmount(slot), price ); } } } } else { if ( equalsTraderStatus(TraderStatus.BUY) ) { if ( selectItem(event.getCurrentItem(),TraderStatus.BUY,true).hasSelectedItem() ) { double price = getPrice(player, "buy"); int scale = event.getCurrentItem().getAmount() / getSelectedItem().getAmount(); if ( !checkBuyLimits(scale) ) { Bukkit.getServer().getPluginManager().callEvent(new TraderTransactionEvent(this, this.getNpc(), player, this.getTraderStatus(), this.getSelectedItem(), price, TransactionResult.FAIL_LIMIT)); locale.sendMessage(player, "trader-transaction-failed-limit"); } else if ( !sellTransaction(price*scale, event.getCurrentItem()) ) { Bukkit.getServer().getPluginManager().callEvent(new TraderTransactionEvent(this, this.getNpc(), player, this.getTraderStatus(), this.getSelectedItem(), price, TransactionResult.FAIL_MONEY)); locale.sendMessage(player, "trader-transaction-failed-money"); } else { locale.sendMessage(player, "trader-transaction-success", "action", "#sold", "amount", String.valueOf(getSelectedItem().getAmount()*scale), "price", f.format(price*scale).replace("$", "")); //TODO updateBuyLimits(scale); MetaTools.removeDescription(event.getCurrentItem(), "player-inventory"); removeFromInventory(event.getCurrentItem(), event); Bukkit.getServer().getPluginManager().callEvent(new TraderTransactionEvent(this, this.getNpc(), event.getWhoClicked(), this.getTraderStatus(), this.getSelectedItem(), price, TransactionResult.SUCCESS_BUY)); //logging log("sell", getSelectedItem().getItemStack().getTypeId(), getSelectedItem().getItemStack().getData().getData(), getSelectedItem().getAmount()*scale, price*scale ); } } } else if ( equalsTraderStatus(TraderStatus.SELL_AMOUNT) ) { event.setCancelled(true); return; } else if ( selectItem(event.getCurrentItem(),TraderStatus.BUY,true).hasSelectedItem() ) { double price = getPrice(player, "buy"); int scale = event.getCurrentItem().getAmount() / getSelectedItem().getAmount(); if ( !permissionsManager.has(player, "dtl.trader.options.buy") ) { locale.sendMessage(player, "error-nopermission"); } else if ( !checkBuyLimits(scale) ) { Bukkit.getServer().getPluginManager().callEvent(new TraderTransactionEvent(this, this.getNpc(), event.getWhoClicked(), this.getTraderStatus(), this.getSelectedItem(), price, TransactionResult.FAIL_MONEY)); locale.sendMessage(player, "trader-transaction-failed-limit"); } else if ( !sellTransaction(price*scale, event.getCurrentItem()) ) { Bukkit.getServer().getPluginManager().callEvent(new TraderTransactionEvent(this, this.getNpc(), event.getWhoClicked(), this.getTraderStatus(), this.getSelectedItem(), price, TransactionResult.FAIL_MONEY)); locale.sendMessage(player, "trader-transaction-failed-money"); } else { locale.sendMessage(player, "trader-transaction-success", "action", "#sold", "amount", String.valueOf(getSelectedItem().getAmount()*scale), "price", f.format(price*scale).replace("$", "")); //limits update updateBuyLimits(scale); Bukkit.getServer().getPluginManager().callEvent(new TraderTransactionEvent(this, this.getNpc(), event.getWhoClicked(), this.getTraderStatus(), this.getSelectedItem(), price, TransactionResult.SUCCESS_BUY)); MetaTools.removeDescription(event.getCurrentItem(), "player-inventory"); //inventory cleanup removeFromInventory(event.getCurrentItem(),event); //logging log("sell", getSelectedItem().getItemStack().getTypeId(), getSelectedItem().getItemStack().getData().getData(), getSelectedItem().getAmount()*scale, price*scale ); } } } event.setCancelled(true); } @Override public void managerMode(InventoryClickEvent event) { boolean top = event.getView().convertSlot(event.getRawSlot()) == event.getRawSlot(); int slot = event.getSlot(); // System.out.print(this.getTraderStatus().name()); if ( slot < 0 ) { event.setCursor(null); switchInventory(getBasicManageModeByWool()); return; } NumberFormat f = NumberFormat.getCurrencyInstance(); //DecimalFormat f = new DecimalFormat("#.##"); if ( top ) { setInventoryClicked(true); // Wool checking, also removing a bug that allowed placing items for sell in the wool slots if ( isManagementSlot(slot, 3) ) { //price managing if ( isWool(event.getCurrentItem(), itemsConfig.getItemManagement(2)) ) { if ( !permissionsManager.has(player, "dtl.trader.managing.price") ) { locale.sendMessage(player, "error-nopermission"); //player.sendMessage( localeManager.getLocaleString("lacks-permissions-manage-xxx", "", "manage:price") ); } else { //switch to price setting mode setTraderStatus(TraderStatus.MANAGE_PRICE); switchInventory(getBasicManageModeByWool(), "price"); getInventory().setItem(getInventory().getSize() - 2, itemsConfig.getItemManagement(6)); getInventory().setItem(getInventory().getSize() - 3, new ItemStack(Material.AIR)); //send message locale.sendMessage(player, "trader-manage-toggle", "mode", "#manage-price"); - //player.sendMessage( localeManager.getLocaleString("xxx-managing-toggled", "entity:player", "manage:price") ); } } else //is any mode used? return to item adding if ( isWool(event.getCurrentItem(), itemsConfig.getItemManagement(6)) ) { //close any management mode, switch to the default buy/sell management if ( isSellModeByWool() ) this.setTraderStatus(TraderStatus.MANAGE_SELL); if ( isBuyModeByWool() ) this.setTraderStatus(TraderStatus.MANAGE_BUY); switchInventory(getBasicManageModeByWool(), "manage"); getInventory().setItem(getInventory().getSize() - 2, itemsConfig.getItemManagement(2) );//new ItemStack(Material.WOOL,1,(short)0,(byte)15)); getInventory().setItem(getInventory().getSize() - 3, itemsConfig.getItemManagement(4) );// ( getBasicManageModeByWool().equals(TraderStatus.MANAGE_SELL) ? : config.getItemManagement(3) ) );//new ItemStack(Material.WOOL,1,(short)0,(byte)( getBasicManageModeByWool().equals(TraderStatus.MANAGE_SELL) ? 11 : 12 ) )); //send message locale.sendMessage(player, "trader-manage-toggle", "mode", "#manage-stock"); } else //global limits management if ( isWool(event.getCurrentItem(), itemsConfig.getItemManagement(4)) ) { if ( !permissionsManager.has(player, "dtl.trader.managing.global-limits") ) { locale.sendMessage(player, "error-nopermission"); // player.sendMessage( localeManager.getLocaleString("lacks-permissions-manage-xxx", "", "manage:buy-limit") ); } else { //status update setTraderStatus(TraderStatus.MANAGE_LIMIT_GLOBAL); switchInventory(getBasicManageModeByWool(), "glimit"); //wool update getInventory().setItem(getInventory().getSize()-3, itemsConfig.getItemManagement(6)); getInventory().setItem(getInventory().getSize()-2, itemsConfig.getItemManagement(5)); locale.sendMessage(player, "trader-manage-toggle", "mode", "#manage-global-limit"); //send message - //player.sendMessage( localeManager.getLocaleString("xxx-managing-toggled", "entity:player", "manage:global-limit") ); } } else //player limits management if ( isWool(event.getCurrentItem(), itemsConfig.getItemManagement(5)) ) { if ( !permissionsManager.has(player, "dtl.trader.managing.player-limits") ) { locale.sendMessage(player, "error-nopermission"); - //player.sendMessage( localeManager.getLocaleString("lacks-permissions-manage-xxx", "", "manage:buy-limit") ); } else { //status update setTraderStatus(TraderStatus.MANAGE_LIMIT_PLAYER); switchInventory(getBasicManageModeByWool(), "plimit"); //wool update getInventory().setItem(getInventory().getSize()-3, itemsConfig.getItemManagement(6)); getInventory().setItem(getInventory().getSize()-2, itemsConfig.getItemManagement(4)); //send message locale.sendMessage(player, "trader-manage-toggle", "mode", "#manage-player-limit"); - // player.sendMessage( localeManager.getLocaleString("xxx-managing-toggled", "entity:player", "manage:player-limit") ); } } else // add a nice support to this system if ( isWool(event.getCurrentItem(), itemsConfig.getItemManagement(1)) ) { if ( !permissionsManager.has(player, "dtl.trader.options.buy") ) { locale.sendMessage(player, "error-nopermission"); - // player.sendMessage( localeManager.getLocaleString("lacks-permissions-manage-xxx", "", "manage:buy") ); } else { switchInventory(TraderStatus.MANAGE_BUY); //send message locale.sendMessage(player, "trader-manage-toggle", "mode", "#manage-stock"); - // player.sendMessage( localeManager.getLocaleString("xxx-managing-toggled", "entity:player", "manage:buy") ); } } else if ( isWool(event.getCurrentItem(), itemsConfig.getItemManagement(0)) ) { if ( !permissionsManager.has(player, "dtl.trader.options.sell") ) { locale.sendMessage(player, "error-nopermission"); - // player.sendMessage( localeManager.getLocaleString("lacks-permissions-manage-xxx", "", "manage:sell") ); } else { //switch to sell mode //status switching included in Inventory switch switchInventory(TraderStatus.MANAGE_SELL); //send message - locale.sendMessage(player, "error-nopermission"); - // player.sendMessage( localeManager.getLocaleString("xxx-managing-toggled", "entity:player", "manage:sell") ); + locale.sendMessage(player, "trader-manage-toggle", "mode", "#manage-stock"); } } else //leaving the amount managing if ( isWool(event.getCurrentItem(), itemsConfig.getItemManagement(7)) ) { //update amounts and status saveManagedAmounts(); switchInventory(TraderStatus.MANAGE_SELL); locale.sendMessage(player, "trader-manage-toggle", "mode", "#manage-stock"); - // player.sendMessage( localeManager.getLocaleString("xxx-managing-toggled", "entity:player", "manage:stock") ); } event.setCancelled(true); return; } else { //is shift clicked? //amount and limit timeout managing if ( event.isShiftClick() ) { //Managing global timeout limits for an item if ( equalsTraderStatus(TraderStatus.MANAGE_LIMIT_GLOBAL) ) { //show the current timeout if ( event.getCursor().getType().equals(Material.AIR) ) { if ( selectItem(slot, getBasicManageModeByWool()).hasSelectedItem() ) locale.sendMessage(player, "key-value", "key", "#global-timeout", "value", String.valueOf(getSelectedItem().getLimits().timeout("global"))); } //timeout changing else { if ( selectItem(slot, getBasicManageModeByWool()).hasSelectedItem() ) { if ( getSelectedItem().getLimits().get("global") == null ) getSelectedItem().getLimits().set("global", new Limit(0,-1)); if ( event.isRightClick() ) { getSelectedItem().getLimits().get("global").changeTimeout(-calculateTimeout(event.getCursor())); } else { getSelectedItem().getLimits().get("global").changeTimeout(calculateTimeout(event.getCursor())); } MetaTools.removeDescription(event.getCurrentItem()); TraderStockPart.setLore(event.getCurrentItem(), TraderStockPart.getLimitLore(getSelectedItem(), getTraderStatus().name(), player)); locale.sendMessage(player, "key-change", "key", "#global-timeout", "value", String.valueOf(getSelectedItem().getLimits().timeout("global"))); } } selectItem(null); event.setCancelled(true); return; } if ( equalsTraderStatus(TraderStatus.MANAGE_LIMIT_PLAYER) ) { //show the current limit if ( event.getCursor().getType().equals(Material.AIR) ) { if ( selectItem(slot, getBasicManageModeByWool()).hasSelectedItem() ) locale.sendMessage(player, "key-value", "key", "#player-limit", "value", String.valueOf(getSelectedItem().getLimits().timeout("player"))); } //limit changing else { if ( selectItem(slot, getBasicManageModeByWool()).hasSelectedItem() ) { if ( getSelectedItem().getLimits().get("player") == null ) getSelectedItem().getLimits().set("player", new Limit(0,-1)); if ( event.isRightClick() ) { getSelectedItem().getLimits().get("player").changeTimeout(-calculateTimeout(event.getCursor())); } else { getSelectedItem().getLimits().get("player").changeTimeout(calculateTimeout(event.getCursor())); } MetaTools.removeDescription(event.getCurrentItem()); TraderStockPart.setLore(event.getCurrentItem(), TraderStockPart.getPlayerLimitLore(getSelectedItem(), getTraderStatus().name(), player)); //add to config locale.sendMessage(player, "key-change", "key", "#player-limit", "value", String.valueOf(getSelectedItem().getLimits().timeout("player"))); } } //reset the selected item selectItem(null); event.setCancelled(true); return; } //amount managing if ( event.isLeftClick() ) { if ( equalsTraderStatus(TraderStatus.MANAGE_SELL) ) { //we got sell managing? if ( selectItem(slot,TraderStatus.MANAGE_SELL).hasSelectedItem() && permissionsManager.has(player, "dtl.trader.managing.multiple-amounts") ) { //inventory and status update switchInventory(getSelectedItem()); setTraderStatus(TraderStatus.MANAGE_SELL_AMOUNT); } } } //nothing to do with the shift r.click... else { } event.setCancelled(true); } else //manager handling { //items managing if ( equalsTraderStatus(getBasicManageModeByWool()) ) { if ( event.isRightClick() ) { if ( !permissionsManager.has(player, "dtl.trader.managing.stack-price") ) { locale.sendMessage(player, "error-nopermission"); selectItem(null); event.setCancelled(true); return; } if ( selectItem(slot, getBasicManageModeByWool()).hasSelectedItem() ) { //if it has the stack price change it back to "per-item" price if ( getSelectedItem().stackPrice() ) { getSelectedItem().setStackPrice(false); locale.sendMessage(player, "key-value", "key", "#stack-price", "value", "#disabled"); } //change the price to a stack-price else { getSelectedItem().setStackPrice(true); locale.sendMessage(player, "key-value", "key", "#stack-price", "value", "#enabled"); } MetaTools.removeDescription(event.getCurrentItem()); TraderStockPart.setLore(event.getCurrentItem(), TraderStockPart.getManageLore(getSelectedItem(), getTraderStatus().name(), player)); getSelectedItem().setAsPatternItem(false); } //reset the selection selectItem(null); //cancel the event event.setCancelled(true); return; } if ( hasSelectedItem() ) { //if we got an selected item (new or old) StockItem item = getSelectedItem(); //this item is new! if ( item.getSlot() == -1 ) { //get the real amount item.setAmount(event.getCursor().getAmount()); //set the item to the stock if ( this.isBuyModeByWool() ) { trait.getStock().addItem("buy", item); - getStock().addItem("buy", item); + // getStock().addItem("buy", item); } if ( this.isSellModeByWool() ) { trait.getStock().addItem("sell", item); - getStock().addItem("sell", item); + // getStock().addItem("sell", item); } locale.sendMessage(player, "trader-stock-item-add"); } //select an item if it exists in the traders inventory if ( selectItem(slot, getBasicManageModeByWool()).hasSelectedItem() ) { getSelectedItem().setSlot(-2); locale.sendMessage(player, "trader-stock-item-select"); } //set the managed items slot item.setSlot(slot); item.setAsPatternItem(false); locale.sendMessage(player, "trader-stock-item-update"); } else { //select an item if it exists in the traders inventory if ( selectItem(slot, getBasicManageModeByWool()).hasSelectedItem() ) { getSelectedItem().setSlot(-2); locale.sendMessage(player, "trader-stock-item-select"); // player.sendMessage( localeManager.getLocaleString("xxx-item", "action:selected") ); } } return; } else //managing multiple amounts if ( equalsTraderStatus(TraderStatus.MANAGE_SELL_AMOUNT) ) { //is item id and data equal? if ( !equalsSelected(event.getCursor(),false,false) && !event.getCursor().getType().equals(Material.AIR) ) { locale.sendMessage(player, "trader-stock-item-invalid"); event.setCancelled(true); } if ( !event.getCursor().getType().equals(Material.AIR) ) getSelectedItem().setAsPatternItem(false); return; } else //manage prices if ( equalsTraderStatus(TraderStatus.MANAGE_PRICE) ) { //show prices if ( event.getCursor().getType().equals(Material.AIR) ) { //select item if ( selectItem(slot, getBasicManageModeByWool()).hasSelectedItem() ) locale.sendMessage(player, "key-value", "key", "#price", "value", f.format(getSelectedItem().getRawPrice()).replace("$", "")); } else //change prices { //select item to change if ( selectItem(slot, getBasicManageModeByWool()).hasSelectedItem() ) { //change price if ( event.isRightClick() ) getSelectedItem().lowerPrice(calculatePrice(event.getCursor())); else getSelectedItem().increasePrice(calculatePrice(event.getCursor())); getSelectedItem().setAsPatternItem(false); getSelectedItem().setPatternPrice(false); MetaTools.removeDescription(event.getCurrentItem()); event.setCurrentItem(TraderStockPart.setLore(event.getCurrentItem(), TraderStockPart.getPriceLore(getSelectedItem(), 0, getBasicManageModeByWool().toString(), getStock().getPatterns(), player))); locale.sendMessage(player, "key-change", "key", "#price", "value", f.format(getSelectedItem().getRawPrice()).replace("$", "")); } } //reset the selected item selectItem(null); //cancel the event event.setCancelled(true); } else //limit managing if ( equalsTraderStatus(TraderStatus.MANAGE_LIMIT_GLOBAL) ) { //show limits if ( event.getCursor().getType().equals(Material.AIR) ) { //select item which limit will be shown up if ( selectItem(slot, getBasicManageModeByWool()).hasSelectedItem() ) { locale.sendMessage(player, "key-value", "key", "#global-limit", "value", String.valueOf(getSelectedItem().getLimits().get("global").getLimit())); // player.sendMessage( localeManager.getLocaleString("xxx-value", "manage:global-limit").replace("{value}", "" + getSelectedItem().getLimitSystem().getGlobalLimit()) ); } } //change limits else { //select the item if ( selectItem(slot, getBasicManageModeByWool()).hasSelectedItem() ) { if ( getSelectedItem().getLimits().get("global") == null ) getSelectedItem().getLimits().set("global", new Limit(0,-1)); if ( event.isRightClick() ) getSelectedItem().getLimits().get("global").changeLimit(-calculateLimit(event.getCursor())); else getSelectedItem().getLimits().get("global").changeLimit(calculateLimit(event.getCursor())); MetaTools.removeDescription(event.getCurrentItem()); TraderStockPart.setLore(event.getCurrentItem(), TraderStockPart.getLimitLore(getSelectedItem(), getTraderStatus().name(), player)); getSelectedItem().setAsPatternItem(false); locale.sendMessage(player, "key-change", "key", "#global-limit", "value", String.valueOf(getSelectedItem().getLimits().get("global").getLimit())); } } //reset the selected item selectItem(null); //cancel the event event.setCancelled(true); } else //player limits if ( equalsTraderStatus(TraderStatus.MANAGE_LIMIT_PLAYER) ) { //show limits if ( event.getCursor().getType().equals(Material.AIR) ) { //select item which limit will be shown up if ( selectItem(slot, getBasicManageModeByWool()).hasSelectedItem() ) { locale.sendMessage(player, "key-value", "key", "#player-limit", "value", String.valueOf(getSelectedItem().getLimits().get("player").getLimit())); } } //change limits else { //select the item if ( selectItem(slot, getBasicManageModeByWool()).hasSelectedItem() ) { if ( getSelectedItem().getLimits().get("player") == null ) getSelectedItem().getLimits().set("player", new Limit(0,-1)); if ( event.isRightClick() ) getSelectedItem().getLimits().get("player").changeLimit(-calculateLimit(event.getCursor())); else getSelectedItem().getLimits().get("player").changeLimit(calculateLimit(event.getCursor())); MetaTools.removeDescription(event.getCurrentItem()); TraderStockPart.setLore(event.getCurrentItem(), TraderStockPart.getPlayerLimitLore(getSelectedItem(), getTraderStatus().name(), player)); getSelectedItem().setAsPatternItem(false); locale.sendMessage(player, "key-value", "key", "#player-limit", "value", String.valueOf(getSelectedItem().getLimits().get("player").getLimit())); } } //reset the selected item selectItem(null); event.setCancelled(true); } } } } //bottom inventory click else {//System.out.print(equalsTraderStatus(getBasicManageModeByWool())); //is item managing if ( equalsTraderStatus(getBasicManageModeByWool()) ) { //is an item is selected if ( getInventoryClicked() && hasSelectedItem() ) { //remove it from the stock if ( equalsTraderStatus(TraderStatus.MANAGE_SELL) ) { trait.getStock().removeItem("sell", getSelectedItem().getSlot()); getStock().removeItem("sell", getSelectedItem().getSlot()); } if ( equalsTraderStatus(TraderStatus.MANAGE_BUY) ) { trait.getStock().removeItem("buy", getSelectedItem().getSlot()); getStock().removeItem("sell", getSelectedItem().getSlot()); } //reset the item selectItem(null); //send a message locale.sendMessage(player, "trader-stock-item-remove"); } else { if ( event.getCurrentItem().getTypeId() != 0 && !hasSelectedItem() ) { selectItem( toStockItem(event.getCurrentItem()) ); locale.sendMessage(player, "trader-stock-item-select"); } } } setInventoryClicked(false); } } @Override public boolean onRightClick(Player player, TraderTrait trait, NPC npc) { if ( player.getGameMode().equals(GameMode.CREATIVE) && !permissionsManager.has(player, "dtl.trader.bypass.creative") ) { locale.sendMessage(player, "error-nopermission-creative"); return false; } if ( player.getItemInHand().getTypeId() == itemsConfig.getManageWand().getTypeId() ) { if ( !permissionsManager.has(player, "dtl.trader.bypass.managing") && !player.isOp() ) { if ( !permissionsManager.has(player, "dtl.trader.options.manage") ) { locale.sendMessage(player, "error-nopermission"); return false; } if ( !trait.getConfig().getOwner().equals(player.getName()) ) { locale.sendMessage(player, "error-nopermission"); return false; } } if ( getTraderStatus().isManaging() ) { switchInventory( getStartStatus(player) ); locale.sendMessage(player, "managermode-disabled", "npc", npc.getFullName()); return true; } locale.sendMessage(player, "managermode-enabled", "npc", npc.getFullName()); switchInventory( getManageStartStatus(player) ); return true; } MetaTools.removeDescriptions(player.getInventory()); if ( !getTraderStatus().isManaging() ) loadDescriptions(player, player.getInventory()); // System.out.print('a'); player.openInventory(getInventory()); return true; } @Override public EType getType() { return EType.SERVER_TRADER; } }
false
true
public void managerMode(InventoryClickEvent event) { boolean top = event.getView().convertSlot(event.getRawSlot()) == event.getRawSlot(); int slot = event.getSlot(); // System.out.print(this.getTraderStatus().name()); if ( slot < 0 ) { event.setCursor(null); switchInventory(getBasicManageModeByWool()); return; } NumberFormat f = NumberFormat.getCurrencyInstance(); //DecimalFormat f = new DecimalFormat("#.##"); if ( top ) { setInventoryClicked(true); // Wool checking, also removing a bug that allowed placing items for sell in the wool slots if ( isManagementSlot(slot, 3) ) { //price managing if ( isWool(event.getCurrentItem(), itemsConfig.getItemManagement(2)) ) { if ( !permissionsManager.has(player, "dtl.trader.managing.price") ) { locale.sendMessage(player, "error-nopermission"); //player.sendMessage( localeManager.getLocaleString("lacks-permissions-manage-xxx", "", "manage:price") ); } else { //switch to price setting mode setTraderStatus(TraderStatus.MANAGE_PRICE); switchInventory(getBasicManageModeByWool(), "price"); getInventory().setItem(getInventory().getSize() - 2, itemsConfig.getItemManagement(6)); getInventory().setItem(getInventory().getSize() - 3, new ItemStack(Material.AIR)); //send message locale.sendMessage(player, "trader-manage-toggle", "mode", "#manage-price"); //player.sendMessage( localeManager.getLocaleString("xxx-managing-toggled", "entity:player", "manage:price") ); } } else //is any mode used? return to item adding if ( isWool(event.getCurrentItem(), itemsConfig.getItemManagement(6)) ) { //close any management mode, switch to the default buy/sell management if ( isSellModeByWool() ) this.setTraderStatus(TraderStatus.MANAGE_SELL); if ( isBuyModeByWool() ) this.setTraderStatus(TraderStatus.MANAGE_BUY); switchInventory(getBasicManageModeByWool(), "manage"); getInventory().setItem(getInventory().getSize() - 2, itemsConfig.getItemManagement(2) );//new ItemStack(Material.WOOL,1,(short)0,(byte)15)); getInventory().setItem(getInventory().getSize() - 3, itemsConfig.getItemManagement(4) );// ( getBasicManageModeByWool().equals(TraderStatus.MANAGE_SELL) ? : config.getItemManagement(3) ) );//new ItemStack(Material.WOOL,1,(short)0,(byte)( getBasicManageModeByWool().equals(TraderStatus.MANAGE_SELL) ? 11 : 12 ) )); //send message locale.sendMessage(player, "trader-manage-toggle", "mode", "#manage-stock"); } else //global limits management if ( isWool(event.getCurrentItem(), itemsConfig.getItemManagement(4)) ) { if ( !permissionsManager.has(player, "dtl.trader.managing.global-limits") ) { locale.sendMessage(player, "error-nopermission"); // player.sendMessage( localeManager.getLocaleString("lacks-permissions-manage-xxx", "", "manage:buy-limit") ); } else { //status update setTraderStatus(TraderStatus.MANAGE_LIMIT_GLOBAL); switchInventory(getBasicManageModeByWool(), "glimit"); //wool update getInventory().setItem(getInventory().getSize()-3, itemsConfig.getItemManagement(6)); getInventory().setItem(getInventory().getSize()-2, itemsConfig.getItemManagement(5)); locale.sendMessage(player, "trader-manage-toggle", "mode", "#manage-global-limit"); //send message //player.sendMessage( localeManager.getLocaleString("xxx-managing-toggled", "entity:player", "manage:global-limit") ); } } else //player limits management if ( isWool(event.getCurrentItem(), itemsConfig.getItemManagement(5)) ) { if ( !permissionsManager.has(player, "dtl.trader.managing.player-limits") ) { locale.sendMessage(player, "error-nopermission"); //player.sendMessage( localeManager.getLocaleString("lacks-permissions-manage-xxx", "", "manage:buy-limit") ); } else { //status update setTraderStatus(TraderStatus.MANAGE_LIMIT_PLAYER); switchInventory(getBasicManageModeByWool(), "plimit"); //wool update getInventory().setItem(getInventory().getSize()-3, itemsConfig.getItemManagement(6)); getInventory().setItem(getInventory().getSize()-2, itemsConfig.getItemManagement(4)); //send message locale.sendMessage(player, "trader-manage-toggle", "mode", "#manage-player-limit"); // player.sendMessage( localeManager.getLocaleString("xxx-managing-toggled", "entity:player", "manage:player-limit") ); } } else // add a nice support to this system if ( isWool(event.getCurrentItem(), itemsConfig.getItemManagement(1)) ) { if ( !permissionsManager.has(player, "dtl.trader.options.buy") ) { locale.sendMessage(player, "error-nopermission"); // player.sendMessage( localeManager.getLocaleString("lacks-permissions-manage-xxx", "", "manage:buy") ); } else { switchInventory(TraderStatus.MANAGE_BUY); //send message locale.sendMessage(player, "trader-manage-toggle", "mode", "#manage-stock"); // player.sendMessage( localeManager.getLocaleString("xxx-managing-toggled", "entity:player", "manage:buy") ); } } else if ( isWool(event.getCurrentItem(), itemsConfig.getItemManagement(0)) ) { if ( !permissionsManager.has(player, "dtl.trader.options.sell") ) { locale.sendMessage(player, "error-nopermission"); // player.sendMessage( localeManager.getLocaleString("lacks-permissions-manage-xxx", "", "manage:sell") ); } else { //switch to sell mode //status switching included in Inventory switch switchInventory(TraderStatus.MANAGE_SELL); //send message locale.sendMessage(player, "error-nopermission"); // player.sendMessage( localeManager.getLocaleString("xxx-managing-toggled", "entity:player", "manage:sell") ); } } else //leaving the amount managing if ( isWool(event.getCurrentItem(), itemsConfig.getItemManagement(7)) ) { //update amounts and status saveManagedAmounts(); switchInventory(TraderStatus.MANAGE_SELL); locale.sendMessage(player, "trader-manage-toggle", "mode", "#manage-stock"); // player.sendMessage( localeManager.getLocaleString("xxx-managing-toggled", "entity:player", "manage:stock") ); } event.setCancelled(true); return; } else { //is shift clicked? //amount and limit timeout managing if ( event.isShiftClick() ) { //Managing global timeout limits for an item if ( equalsTraderStatus(TraderStatus.MANAGE_LIMIT_GLOBAL) ) { //show the current timeout if ( event.getCursor().getType().equals(Material.AIR) ) { if ( selectItem(slot, getBasicManageModeByWool()).hasSelectedItem() ) locale.sendMessage(player, "key-value", "key", "#global-timeout", "value", String.valueOf(getSelectedItem().getLimits().timeout("global"))); } //timeout changing else { if ( selectItem(slot, getBasicManageModeByWool()).hasSelectedItem() ) { if ( getSelectedItem().getLimits().get("global") == null ) getSelectedItem().getLimits().set("global", new Limit(0,-1)); if ( event.isRightClick() ) { getSelectedItem().getLimits().get("global").changeTimeout(-calculateTimeout(event.getCursor())); } else { getSelectedItem().getLimits().get("global").changeTimeout(calculateTimeout(event.getCursor())); } MetaTools.removeDescription(event.getCurrentItem()); TraderStockPart.setLore(event.getCurrentItem(), TraderStockPart.getLimitLore(getSelectedItem(), getTraderStatus().name(), player)); locale.sendMessage(player, "key-change", "key", "#global-timeout", "value", String.valueOf(getSelectedItem().getLimits().timeout("global"))); } } selectItem(null); event.setCancelled(true); return; } if ( equalsTraderStatus(TraderStatus.MANAGE_LIMIT_PLAYER) ) { //show the current limit if ( event.getCursor().getType().equals(Material.AIR) ) { if ( selectItem(slot, getBasicManageModeByWool()).hasSelectedItem() ) locale.sendMessage(player, "key-value", "key", "#player-limit", "value", String.valueOf(getSelectedItem().getLimits().timeout("player"))); } //limit changing else { if ( selectItem(slot, getBasicManageModeByWool()).hasSelectedItem() ) { if ( getSelectedItem().getLimits().get("player") == null ) getSelectedItem().getLimits().set("player", new Limit(0,-1)); if ( event.isRightClick() ) { getSelectedItem().getLimits().get("player").changeTimeout(-calculateTimeout(event.getCursor())); } else { getSelectedItem().getLimits().get("player").changeTimeout(calculateTimeout(event.getCursor())); } MetaTools.removeDescription(event.getCurrentItem()); TraderStockPart.setLore(event.getCurrentItem(), TraderStockPart.getPlayerLimitLore(getSelectedItem(), getTraderStatus().name(), player)); //add to config locale.sendMessage(player, "key-change", "key", "#player-limit", "value", String.valueOf(getSelectedItem().getLimits().timeout("player"))); } } //reset the selected item selectItem(null); event.setCancelled(true); return; } //amount managing if ( event.isLeftClick() ) { if ( equalsTraderStatus(TraderStatus.MANAGE_SELL) ) { //we got sell managing? if ( selectItem(slot,TraderStatus.MANAGE_SELL).hasSelectedItem() && permissionsManager.has(player, "dtl.trader.managing.multiple-amounts") ) { //inventory and status update switchInventory(getSelectedItem()); setTraderStatus(TraderStatus.MANAGE_SELL_AMOUNT); } } } //nothing to do with the shift r.click... else { } event.setCancelled(true); } else //manager handling { //items managing if ( equalsTraderStatus(getBasicManageModeByWool()) ) { if ( event.isRightClick() ) { if ( !permissionsManager.has(player, "dtl.trader.managing.stack-price") ) { locale.sendMessage(player, "error-nopermission"); selectItem(null); event.setCancelled(true); return; } if ( selectItem(slot, getBasicManageModeByWool()).hasSelectedItem() ) { //if it has the stack price change it back to "per-item" price if ( getSelectedItem().stackPrice() ) { getSelectedItem().setStackPrice(false); locale.sendMessage(player, "key-value", "key", "#stack-price", "value", "#disabled"); } //change the price to a stack-price else { getSelectedItem().setStackPrice(true); locale.sendMessage(player, "key-value", "key", "#stack-price", "value", "#enabled"); } MetaTools.removeDescription(event.getCurrentItem()); TraderStockPart.setLore(event.getCurrentItem(), TraderStockPart.getManageLore(getSelectedItem(), getTraderStatus().name(), player)); getSelectedItem().setAsPatternItem(false); } //reset the selection selectItem(null); //cancel the event event.setCancelled(true); return; } if ( hasSelectedItem() ) { //if we got an selected item (new or old) StockItem item = getSelectedItem(); //this item is new! if ( item.getSlot() == -1 ) { //get the real amount item.setAmount(event.getCursor().getAmount()); //set the item to the stock if ( this.isBuyModeByWool() ) { trait.getStock().addItem("buy", item); getStock().addItem("buy", item); } if ( this.isSellModeByWool() ) { trait.getStock().addItem("sell", item); getStock().addItem("sell", item); } locale.sendMessage(player, "trader-stock-item-add"); } //select an item if it exists in the traders inventory if ( selectItem(slot, getBasicManageModeByWool()).hasSelectedItem() ) { getSelectedItem().setSlot(-2); locale.sendMessage(player, "trader-stock-item-select"); } //set the managed items slot item.setSlot(slot); item.setAsPatternItem(false); locale.sendMessage(player, "trader-stock-item-update"); } else { //select an item if it exists in the traders inventory if ( selectItem(slot, getBasicManageModeByWool()).hasSelectedItem() ) { getSelectedItem().setSlot(-2); locale.sendMessage(player, "trader-stock-item-select"); // player.sendMessage( localeManager.getLocaleString("xxx-item", "action:selected") ); } } return; } else //managing multiple amounts if ( equalsTraderStatus(TraderStatus.MANAGE_SELL_AMOUNT) ) { //is item id and data equal? if ( !equalsSelected(event.getCursor(),false,false) && !event.getCursor().getType().equals(Material.AIR) ) { locale.sendMessage(player, "trader-stock-item-invalid"); event.setCancelled(true); } if ( !event.getCursor().getType().equals(Material.AIR) ) getSelectedItem().setAsPatternItem(false); return; } else //manage prices if ( equalsTraderStatus(TraderStatus.MANAGE_PRICE) ) { //show prices if ( event.getCursor().getType().equals(Material.AIR) ) { //select item if ( selectItem(slot, getBasicManageModeByWool()).hasSelectedItem() ) locale.sendMessage(player, "key-value", "key", "#price", "value", f.format(getSelectedItem().getRawPrice()).replace("$", "")); } else //change prices { //select item to change if ( selectItem(slot, getBasicManageModeByWool()).hasSelectedItem() ) { //change price if ( event.isRightClick() ) getSelectedItem().lowerPrice(calculatePrice(event.getCursor())); else getSelectedItem().increasePrice(calculatePrice(event.getCursor())); getSelectedItem().setAsPatternItem(false); getSelectedItem().setPatternPrice(false); MetaTools.removeDescription(event.getCurrentItem()); event.setCurrentItem(TraderStockPart.setLore(event.getCurrentItem(), TraderStockPart.getPriceLore(getSelectedItem(), 0, getBasicManageModeByWool().toString(), getStock().getPatterns(), player))); locale.sendMessage(player, "key-change", "key", "#price", "value", f.format(getSelectedItem().getRawPrice()).replace("$", "")); } } //reset the selected item selectItem(null); //cancel the event event.setCancelled(true); } else //limit managing if ( equalsTraderStatus(TraderStatus.MANAGE_LIMIT_GLOBAL) ) { //show limits if ( event.getCursor().getType().equals(Material.AIR) ) { //select item which limit will be shown up if ( selectItem(slot, getBasicManageModeByWool()).hasSelectedItem() ) { locale.sendMessage(player, "key-value", "key", "#global-limit", "value", String.valueOf(getSelectedItem().getLimits().get("global").getLimit())); // player.sendMessage( localeManager.getLocaleString("xxx-value", "manage:global-limit").replace("{value}", "" + getSelectedItem().getLimitSystem().getGlobalLimit()) ); } } //change limits else { //select the item if ( selectItem(slot, getBasicManageModeByWool()).hasSelectedItem() ) { if ( getSelectedItem().getLimits().get("global") == null ) getSelectedItem().getLimits().set("global", new Limit(0,-1)); if ( event.isRightClick() ) getSelectedItem().getLimits().get("global").changeLimit(-calculateLimit(event.getCursor())); else getSelectedItem().getLimits().get("global").changeLimit(calculateLimit(event.getCursor())); MetaTools.removeDescription(event.getCurrentItem()); TraderStockPart.setLore(event.getCurrentItem(), TraderStockPart.getLimitLore(getSelectedItem(), getTraderStatus().name(), player)); getSelectedItem().setAsPatternItem(false); locale.sendMessage(player, "key-change", "key", "#global-limit", "value", String.valueOf(getSelectedItem().getLimits().get("global").getLimit())); } } //reset the selected item selectItem(null); //cancel the event event.setCancelled(true); } else //player limits if ( equalsTraderStatus(TraderStatus.MANAGE_LIMIT_PLAYER) ) { //show limits if ( event.getCursor().getType().equals(Material.AIR) ) { //select item which limit will be shown up if ( selectItem(slot, getBasicManageModeByWool()).hasSelectedItem() ) { locale.sendMessage(player, "key-value", "key", "#player-limit", "value", String.valueOf(getSelectedItem().getLimits().get("player").getLimit())); } } //change limits else { //select the item if ( selectItem(slot, getBasicManageModeByWool()).hasSelectedItem() ) { if ( getSelectedItem().getLimits().get("player") == null ) getSelectedItem().getLimits().set("player", new Limit(0,-1)); if ( event.isRightClick() ) getSelectedItem().getLimits().get("player").changeLimit(-calculateLimit(event.getCursor())); else getSelectedItem().getLimits().get("player").changeLimit(calculateLimit(event.getCursor())); MetaTools.removeDescription(event.getCurrentItem()); TraderStockPart.setLore(event.getCurrentItem(), TraderStockPart.getPlayerLimitLore(getSelectedItem(), getTraderStatus().name(), player)); getSelectedItem().setAsPatternItem(false); locale.sendMessage(player, "key-value", "key", "#player-limit", "value", String.valueOf(getSelectedItem().getLimits().get("player").getLimit())); } } //reset the selected item selectItem(null); event.setCancelled(true); } } } } //bottom inventory click else {//System.out.print(equalsTraderStatus(getBasicManageModeByWool())); //is item managing if ( equalsTraderStatus(getBasicManageModeByWool()) ) { //is an item is selected if ( getInventoryClicked() && hasSelectedItem() ) { //remove it from the stock if ( equalsTraderStatus(TraderStatus.MANAGE_SELL) ) { trait.getStock().removeItem("sell", getSelectedItem().getSlot()); getStock().removeItem("sell", getSelectedItem().getSlot()); } if ( equalsTraderStatus(TraderStatus.MANAGE_BUY) ) { trait.getStock().removeItem("buy", getSelectedItem().getSlot()); getStock().removeItem("sell", getSelectedItem().getSlot()); } //reset the item selectItem(null); //send a message locale.sendMessage(player, "trader-stock-item-remove"); } else { if ( event.getCurrentItem().getTypeId() != 0 && !hasSelectedItem() ) { selectItem( toStockItem(event.getCurrentItem()) ); locale.sendMessage(player, "trader-stock-item-select"); } } } setInventoryClicked(false); } }
public void managerMode(InventoryClickEvent event) { boolean top = event.getView().convertSlot(event.getRawSlot()) == event.getRawSlot(); int slot = event.getSlot(); // System.out.print(this.getTraderStatus().name()); if ( slot < 0 ) { event.setCursor(null); switchInventory(getBasicManageModeByWool()); return; } NumberFormat f = NumberFormat.getCurrencyInstance(); //DecimalFormat f = new DecimalFormat("#.##"); if ( top ) { setInventoryClicked(true); // Wool checking, also removing a bug that allowed placing items for sell in the wool slots if ( isManagementSlot(slot, 3) ) { //price managing if ( isWool(event.getCurrentItem(), itemsConfig.getItemManagement(2)) ) { if ( !permissionsManager.has(player, "dtl.trader.managing.price") ) { locale.sendMessage(player, "error-nopermission"); //player.sendMessage( localeManager.getLocaleString("lacks-permissions-manage-xxx", "", "manage:price") ); } else { //switch to price setting mode setTraderStatus(TraderStatus.MANAGE_PRICE); switchInventory(getBasicManageModeByWool(), "price"); getInventory().setItem(getInventory().getSize() - 2, itemsConfig.getItemManagement(6)); getInventory().setItem(getInventory().getSize() - 3, new ItemStack(Material.AIR)); //send message locale.sendMessage(player, "trader-manage-toggle", "mode", "#manage-price"); } } else //is any mode used? return to item adding if ( isWool(event.getCurrentItem(), itemsConfig.getItemManagement(6)) ) { //close any management mode, switch to the default buy/sell management if ( isSellModeByWool() ) this.setTraderStatus(TraderStatus.MANAGE_SELL); if ( isBuyModeByWool() ) this.setTraderStatus(TraderStatus.MANAGE_BUY); switchInventory(getBasicManageModeByWool(), "manage"); getInventory().setItem(getInventory().getSize() - 2, itemsConfig.getItemManagement(2) );//new ItemStack(Material.WOOL,1,(short)0,(byte)15)); getInventory().setItem(getInventory().getSize() - 3, itemsConfig.getItemManagement(4) );// ( getBasicManageModeByWool().equals(TraderStatus.MANAGE_SELL) ? : config.getItemManagement(3) ) );//new ItemStack(Material.WOOL,1,(short)0,(byte)( getBasicManageModeByWool().equals(TraderStatus.MANAGE_SELL) ? 11 : 12 ) )); //send message locale.sendMessage(player, "trader-manage-toggle", "mode", "#manage-stock"); } else //global limits management if ( isWool(event.getCurrentItem(), itemsConfig.getItemManagement(4)) ) { if ( !permissionsManager.has(player, "dtl.trader.managing.global-limits") ) { locale.sendMessage(player, "error-nopermission"); // player.sendMessage( localeManager.getLocaleString("lacks-permissions-manage-xxx", "", "manage:buy-limit") ); } else { //status update setTraderStatus(TraderStatus.MANAGE_LIMIT_GLOBAL); switchInventory(getBasicManageModeByWool(), "glimit"); //wool update getInventory().setItem(getInventory().getSize()-3, itemsConfig.getItemManagement(6)); getInventory().setItem(getInventory().getSize()-2, itemsConfig.getItemManagement(5)); locale.sendMessage(player, "trader-manage-toggle", "mode", "#manage-global-limit"); //send message } } else //player limits management if ( isWool(event.getCurrentItem(), itemsConfig.getItemManagement(5)) ) { if ( !permissionsManager.has(player, "dtl.trader.managing.player-limits") ) { locale.sendMessage(player, "error-nopermission"); } else { //status update setTraderStatus(TraderStatus.MANAGE_LIMIT_PLAYER); switchInventory(getBasicManageModeByWool(), "plimit"); //wool update getInventory().setItem(getInventory().getSize()-3, itemsConfig.getItemManagement(6)); getInventory().setItem(getInventory().getSize()-2, itemsConfig.getItemManagement(4)); //send message locale.sendMessage(player, "trader-manage-toggle", "mode", "#manage-player-limit"); } } else // add a nice support to this system if ( isWool(event.getCurrentItem(), itemsConfig.getItemManagement(1)) ) { if ( !permissionsManager.has(player, "dtl.trader.options.buy") ) { locale.sendMessage(player, "error-nopermission"); } else { switchInventory(TraderStatus.MANAGE_BUY); //send message locale.sendMessage(player, "trader-manage-toggle", "mode", "#manage-stock"); } } else if ( isWool(event.getCurrentItem(), itemsConfig.getItemManagement(0)) ) { if ( !permissionsManager.has(player, "dtl.trader.options.sell") ) { locale.sendMessage(player, "error-nopermission"); } else { //switch to sell mode //status switching included in Inventory switch switchInventory(TraderStatus.MANAGE_SELL); //send message locale.sendMessage(player, "trader-manage-toggle", "mode", "#manage-stock"); } } else //leaving the amount managing if ( isWool(event.getCurrentItem(), itemsConfig.getItemManagement(7)) ) { //update amounts and status saveManagedAmounts(); switchInventory(TraderStatus.MANAGE_SELL); locale.sendMessage(player, "trader-manage-toggle", "mode", "#manage-stock"); } event.setCancelled(true); return; } else { //is shift clicked? //amount and limit timeout managing if ( event.isShiftClick() ) { //Managing global timeout limits for an item if ( equalsTraderStatus(TraderStatus.MANAGE_LIMIT_GLOBAL) ) { //show the current timeout if ( event.getCursor().getType().equals(Material.AIR) ) { if ( selectItem(slot, getBasicManageModeByWool()).hasSelectedItem() ) locale.sendMessage(player, "key-value", "key", "#global-timeout", "value", String.valueOf(getSelectedItem().getLimits().timeout("global"))); } //timeout changing else { if ( selectItem(slot, getBasicManageModeByWool()).hasSelectedItem() ) { if ( getSelectedItem().getLimits().get("global") == null ) getSelectedItem().getLimits().set("global", new Limit(0,-1)); if ( event.isRightClick() ) { getSelectedItem().getLimits().get("global").changeTimeout(-calculateTimeout(event.getCursor())); } else { getSelectedItem().getLimits().get("global").changeTimeout(calculateTimeout(event.getCursor())); } MetaTools.removeDescription(event.getCurrentItem()); TraderStockPart.setLore(event.getCurrentItem(), TraderStockPart.getLimitLore(getSelectedItem(), getTraderStatus().name(), player)); locale.sendMessage(player, "key-change", "key", "#global-timeout", "value", String.valueOf(getSelectedItem().getLimits().timeout("global"))); } } selectItem(null); event.setCancelled(true); return; } if ( equalsTraderStatus(TraderStatus.MANAGE_LIMIT_PLAYER) ) { //show the current limit if ( event.getCursor().getType().equals(Material.AIR) ) { if ( selectItem(slot, getBasicManageModeByWool()).hasSelectedItem() ) locale.sendMessage(player, "key-value", "key", "#player-limit", "value", String.valueOf(getSelectedItem().getLimits().timeout("player"))); } //limit changing else { if ( selectItem(slot, getBasicManageModeByWool()).hasSelectedItem() ) { if ( getSelectedItem().getLimits().get("player") == null ) getSelectedItem().getLimits().set("player", new Limit(0,-1)); if ( event.isRightClick() ) { getSelectedItem().getLimits().get("player").changeTimeout(-calculateTimeout(event.getCursor())); } else { getSelectedItem().getLimits().get("player").changeTimeout(calculateTimeout(event.getCursor())); } MetaTools.removeDescription(event.getCurrentItem()); TraderStockPart.setLore(event.getCurrentItem(), TraderStockPart.getPlayerLimitLore(getSelectedItem(), getTraderStatus().name(), player)); //add to config locale.sendMessage(player, "key-change", "key", "#player-limit", "value", String.valueOf(getSelectedItem().getLimits().timeout("player"))); } } //reset the selected item selectItem(null); event.setCancelled(true); return; } //amount managing if ( event.isLeftClick() ) { if ( equalsTraderStatus(TraderStatus.MANAGE_SELL) ) { //we got sell managing? if ( selectItem(slot,TraderStatus.MANAGE_SELL).hasSelectedItem() && permissionsManager.has(player, "dtl.trader.managing.multiple-amounts") ) { //inventory and status update switchInventory(getSelectedItem()); setTraderStatus(TraderStatus.MANAGE_SELL_AMOUNT); } } } //nothing to do with the shift r.click... else { } event.setCancelled(true); } else //manager handling { //items managing if ( equalsTraderStatus(getBasicManageModeByWool()) ) { if ( event.isRightClick() ) { if ( !permissionsManager.has(player, "dtl.trader.managing.stack-price") ) { locale.sendMessage(player, "error-nopermission"); selectItem(null); event.setCancelled(true); return; } if ( selectItem(slot, getBasicManageModeByWool()).hasSelectedItem() ) { //if it has the stack price change it back to "per-item" price if ( getSelectedItem().stackPrice() ) { getSelectedItem().setStackPrice(false); locale.sendMessage(player, "key-value", "key", "#stack-price", "value", "#disabled"); } //change the price to a stack-price else { getSelectedItem().setStackPrice(true); locale.sendMessage(player, "key-value", "key", "#stack-price", "value", "#enabled"); } MetaTools.removeDescription(event.getCurrentItem()); TraderStockPart.setLore(event.getCurrentItem(), TraderStockPart.getManageLore(getSelectedItem(), getTraderStatus().name(), player)); getSelectedItem().setAsPatternItem(false); } //reset the selection selectItem(null); //cancel the event event.setCancelled(true); return; } if ( hasSelectedItem() ) { //if we got an selected item (new or old) StockItem item = getSelectedItem(); //this item is new! if ( item.getSlot() == -1 ) { //get the real amount item.setAmount(event.getCursor().getAmount()); //set the item to the stock if ( this.isBuyModeByWool() ) { trait.getStock().addItem("buy", item); // getStock().addItem("buy", item); } if ( this.isSellModeByWool() ) { trait.getStock().addItem("sell", item); // getStock().addItem("sell", item); } locale.sendMessage(player, "trader-stock-item-add"); } //select an item if it exists in the traders inventory if ( selectItem(slot, getBasicManageModeByWool()).hasSelectedItem() ) { getSelectedItem().setSlot(-2); locale.sendMessage(player, "trader-stock-item-select"); } //set the managed items slot item.setSlot(slot); item.setAsPatternItem(false); locale.sendMessage(player, "trader-stock-item-update"); } else { //select an item if it exists in the traders inventory if ( selectItem(slot, getBasicManageModeByWool()).hasSelectedItem() ) { getSelectedItem().setSlot(-2); locale.sendMessage(player, "trader-stock-item-select"); // player.sendMessage( localeManager.getLocaleString("xxx-item", "action:selected") ); } } return; } else //managing multiple amounts if ( equalsTraderStatus(TraderStatus.MANAGE_SELL_AMOUNT) ) { //is item id and data equal? if ( !equalsSelected(event.getCursor(),false,false) && !event.getCursor().getType().equals(Material.AIR) ) { locale.sendMessage(player, "trader-stock-item-invalid"); event.setCancelled(true); } if ( !event.getCursor().getType().equals(Material.AIR) ) getSelectedItem().setAsPatternItem(false); return; } else //manage prices if ( equalsTraderStatus(TraderStatus.MANAGE_PRICE) ) { //show prices if ( event.getCursor().getType().equals(Material.AIR) ) { //select item if ( selectItem(slot, getBasicManageModeByWool()).hasSelectedItem() ) locale.sendMessage(player, "key-value", "key", "#price", "value", f.format(getSelectedItem().getRawPrice()).replace("$", "")); } else //change prices { //select item to change if ( selectItem(slot, getBasicManageModeByWool()).hasSelectedItem() ) { //change price if ( event.isRightClick() ) getSelectedItem().lowerPrice(calculatePrice(event.getCursor())); else getSelectedItem().increasePrice(calculatePrice(event.getCursor())); getSelectedItem().setAsPatternItem(false); getSelectedItem().setPatternPrice(false); MetaTools.removeDescription(event.getCurrentItem()); event.setCurrentItem(TraderStockPart.setLore(event.getCurrentItem(), TraderStockPart.getPriceLore(getSelectedItem(), 0, getBasicManageModeByWool().toString(), getStock().getPatterns(), player))); locale.sendMessage(player, "key-change", "key", "#price", "value", f.format(getSelectedItem().getRawPrice()).replace("$", "")); } } //reset the selected item selectItem(null); //cancel the event event.setCancelled(true); } else //limit managing if ( equalsTraderStatus(TraderStatus.MANAGE_LIMIT_GLOBAL) ) { //show limits if ( event.getCursor().getType().equals(Material.AIR) ) { //select item which limit will be shown up if ( selectItem(slot, getBasicManageModeByWool()).hasSelectedItem() ) { locale.sendMessage(player, "key-value", "key", "#global-limit", "value", String.valueOf(getSelectedItem().getLimits().get("global").getLimit())); // player.sendMessage( localeManager.getLocaleString("xxx-value", "manage:global-limit").replace("{value}", "" + getSelectedItem().getLimitSystem().getGlobalLimit()) ); } } //change limits else { //select the item if ( selectItem(slot, getBasicManageModeByWool()).hasSelectedItem() ) { if ( getSelectedItem().getLimits().get("global") == null ) getSelectedItem().getLimits().set("global", new Limit(0,-1)); if ( event.isRightClick() ) getSelectedItem().getLimits().get("global").changeLimit(-calculateLimit(event.getCursor())); else getSelectedItem().getLimits().get("global").changeLimit(calculateLimit(event.getCursor())); MetaTools.removeDescription(event.getCurrentItem()); TraderStockPart.setLore(event.getCurrentItem(), TraderStockPart.getLimitLore(getSelectedItem(), getTraderStatus().name(), player)); getSelectedItem().setAsPatternItem(false); locale.sendMessage(player, "key-change", "key", "#global-limit", "value", String.valueOf(getSelectedItem().getLimits().get("global").getLimit())); } } //reset the selected item selectItem(null); //cancel the event event.setCancelled(true); } else //player limits if ( equalsTraderStatus(TraderStatus.MANAGE_LIMIT_PLAYER) ) { //show limits if ( event.getCursor().getType().equals(Material.AIR) ) { //select item which limit will be shown up if ( selectItem(slot, getBasicManageModeByWool()).hasSelectedItem() ) { locale.sendMessage(player, "key-value", "key", "#player-limit", "value", String.valueOf(getSelectedItem().getLimits().get("player").getLimit())); } } //change limits else { //select the item if ( selectItem(slot, getBasicManageModeByWool()).hasSelectedItem() ) { if ( getSelectedItem().getLimits().get("player") == null ) getSelectedItem().getLimits().set("player", new Limit(0,-1)); if ( event.isRightClick() ) getSelectedItem().getLimits().get("player").changeLimit(-calculateLimit(event.getCursor())); else getSelectedItem().getLimits().get("player").changeLimit(calculateLimit(event.getCursor())); MetaTools.removeDescription(event.getCurrentItem()); TraderStockPart.setLore(event.getCurrentItem(), TraderStockPart.getPlayerLimitLore(getSelectedItem(), getTraderStatus().name(), player)); getSelectedItem().setAsPatternItem(false); locale.sendMessage(player, "key-value", "key", "#player-limit", "value", String.valueOf(getSelectedItem().getLimits().get("player").getLimit())); } } //reset the selected item selectItem(null); event.setCancelled(true); } } } } //bottom inventory click else {//System.out.print(equalsTraderStatus(getBasicManageModeByWool())); //is item managing if ( equalsTraderStatus(getBasicManageModeByWool()) ) { //is an item is selected if ( getInventoryClicked() && hasSelectedItem() ) { //remove it from the stock if ( equalsTraderStatus(TraderStatus.MANAGE_SELL) ) { trait.getStock().removeItem("sell", getSelectedItem().getSlot()); getStock().removeItem("sell", getSelectedItem().getSlot()); } if ( equalsTraderStatus(TraderStatus.MANAGE_BUY) ) { trait.getStock().removeItem("buy", getSelectedItem().getSlot()); getStock().removeItem("sell", getSelectedItem().getSlot()); } //reset the item selectItem(null); //send a message locale.sendMessage(player, "trader-stock-item-remove"); } else { if ( event.getCurrentItem().getTypeId() != 0 && !hasSelectedItem() ) { selectItem( toStockItem(event.getCurrentItem()) ); locale.sendMessage(player, "trader-stock-item-select"); } } } setInventoryClicked(false); } }
diff --git a/qcadoo-model/src/main/java/com/qcadoo/model/internal/NumberServiceImpl.java b/qcadoo-model/src/main/java/com/qcadoo/model/internal/NumberServiceImpl.java index 3ab41551d..8c01ce0e7 100644 --- a/qcadoo-model/src/main/java/com/qcadoo/model/internal/NumberServiceImpl.java +++ b/qcadoo-model/src/main/java/com/qcadoo/model/internal/NumberServiceImpl.java @@ -1,30 +1,30 @@ package com.qcadoo.model.internal; import java.math.MathContext; import java.text.DecimalFormat; import java.util.Locale; import org.springframework.stereotype.Component; import com.qcadoo.model.api.NumberService; @Component public class NumberServiceImpl implements NumberService { private static DecimalFormat decimalFormat = null; @Override public MathContext getMathContext() { return MathContext.DECIMAL64; } @Override - public DecimalFormat getDecimalFormat(final Locale locale) { + public synchronized DecimalFormat getDecimalFormat(final Locale locale) { if (decimalFormat == null) { decimalFormat = (DecimalFormat) DecimalFormat.getInstance(locale); decimalFormat.setMaximumFractionDigits(3); decimalFormat.setMinimumFractionDigits(3); } return decimalFormat; } }
true
true
public DecimalFormat getDecimalFormat(final Locale locale) { if (decimalFormat == null) { decimalFormat = (DecimalFormat) DecimalFormat.getInstance(locale); decimalFormat.setMaximumFractionDigits(3); decimalFormat.setMinimumFractionDigits(3); } return decimalFormat; }
public synchronized DecimalFormat getDecimalFormat(final Locale locale) { if (decimalFormat == null) { decimalFormat = (DecimalFormat) DecimalFormat.getInstance(locale); decimalFormat.setMaximumFractionDigits(3); decimalFormat.setMinimumFractionDigits(3); } return decimalFormat; }
diff --git a/poem-jvm/src/java/org/b3mn/poem/handler/NewModelHandler.java b/poem-jvm/src/java/org/b3mn/poem/handler/NewModelHandler.java index e69d2f13..9a282531 100644 --- a/poem-jvm/src/java/org/b3mn/poem/handler/NewModelHandler.java +++ b/poem-jvm/src/java/org/b3mn/poem/handler/NewModelHandler.java @@ -1,84 +1,84 @@ /*************************************** * Copyright (c) 2008 * Bjoern Wagner * * 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.b3mn.poem.handler; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.b3mn.poem.Identity; import org.b3mn.poem.util.HandlerWithoutModelContext; @HandlerWithoutModelContext(uri="/new") public class NewModelHandler extends HandlerBase { @Override public void doGet(HttpServletRequest request, HttpServletResponse response, Identity subject, Identity object) throws IOException { String stencilset = "/stencilsets/bpmn/bpmn.json"; if (request.getParameter("stencilset") != null) { stencilset = request.getParameter("stencilset"); } String content = "<div id=\"oryx-canvas123\" class=\"-oryx-canvas\">" + "<span class=\"oryx-mode\">writeable</span>" + "<span class=\"oryx-mode\">fullscreen</span>" + "<a href=\"" + "/oryx" + stencilset + "\" rel=\"oryx-stencilset\"></a>\n" + "</div>\n"; response.getWriter().print(this.getOryxModel("New Process Model", content, this.getLanguageCode(request), this.getCountryCode(request))); response.setStatus(200); response.setContentType("application/xhtml+xml"); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response, Identity subject, Identity object) throws IOException { // Check whether the user is public if (subject.getUri().equals(getPublicUser())) { response.getWriter().println("The public user is not allowed to create new models. Please login first."); response.setStatus(403); return; } // Check whether the request contains at least the data and svg parameters if ((request.getParameter("data") != null) && (request.getParameter("svg") != null)) { + response.setStatus(201); String title = request.getParameter("title"); if (title == null) title = "New Process"; String type = request.getParameter("type"); if (type == null) type = "/stencilsets/bpmn/bpmn.json"; String summary = request.getParameter("summary"); if (summary == null) summary = "This is a new process."; Identity identity = Identity.newModel(subject, title, type, summary, request.getParameter("svg"), request.getParameter("data")); response.setHeader("location", this.getServerPath(request) + identity.getUri() + "/self"); - response.setStatus(201); } else { response.setStatus(400); response.getWriter().println("Data and/or SVG missing"); } } }
false
true
public void doPost(HttpServletRequest request, HttpServletResponse response, Identity subject, Identity object) throws IOException { // Check whether the user is public if (subject.getUri().equals(getPublicUser())) { response.getWriter().println("The public user is not allowed to create new models. Please login first."); response.setStatus(403); return; } // Check whether the request contains at least the data and svg parameters if ((request.getParameter("data") != null) && (request.getParameter("svg") != null)) { String title = request.getParameter("title"); if (title == null) title = "New Process"; String type = request.getParameter("type"); if (type == null) type = "/stencilsets/bpmn/bpmn.json"; String summary = request.getParameter("summary"); if (summary == null) summary = "This is a new process."; Identity identity = Identity.newModel(subject, title, type, summary, request.getParameter("svg"), request.getParameter("data")); response.setHeader("location", this.getServerPath(request) + identity.getUri() + "/self"); response.setStatus(201); } else { response.setStatus(400); response.getWriter().println("Data and/or SVG missing"); } }
public void doPost(HttpServletRequest request, HttpServletResponse response, Identity subject, Identity object) throws IOException { // Check whether the user is public if (subject.getUri().equals(getPublicUser())) { response.getWriter().println("The public user is not allowed to create new models. Please login first."); response.setStatus(403); return; } // Check whether the request contains at least the data and svg parameters if ((request.getParameter("data") != null) && (request.getParameter("svg") != null)) { response.setStatus(201); String title = request.getParameter("title"); if (title == null) title = "New Process"; String type = request.getParameter("type"); if (type == null) type = "/stencilsets/bpmn/bpmn.json"; String summary = request.getParameter("summary"); if (summary == null) summary = "This is a new process."; Identity identity = Identity.newModel(subject, title, type, summary, request.getParameter("svg"), request.getParameter("data")); response.setHeader("location", this.getServerPath(request) + identity.getUri() + "/self"); } else { response.setStatus(400); response.getWriter().println("Data and/or SVG missing"); } }
diff --git a/src/main/java/me/arno/blocklog/schedules/UpdatesSchedule.java b/src/main/java/me/arno/blocklog/schedules/UpdatesSchedule.java index 08e148b..d8c763a 100644 --- a/src/main/java/me/arno/blocklog/schedules/UpdatesSchedule.java +++ b/src/main/java/me/arno/blocklog/schedules/UpdatesSchedule.java @@ -1,56 +1,66 @@ package me.arno.blocklog.schedules; import java.net.URL; import javax.xml.parsers.DocumentBuilderFactory; import me.arno.blocklog.util.Util; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class UpdatesSchedule implements Runnable { private String current; private String latest; public UpdatesSchedule(String currentVersion) { this.current = currentVersion; } @Override public void run() { try { URL url = new URL("http://dev.bukkit.org/server-mods/block-log/files.rss"); Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(url.openConnection().getInputStream()); doc.getDocumentElement().normalize(); NodeList nodes = doc.getElementsByTagName("item"); Node firstNode = nodes.item(0); if (firstNode.getNodeType() == 1) { Element firstElement = (Element) firstNode; NodeList firstElementTagName = firstElement.getElementsByTagName("title"); Element firstNameElement = (Element) firstElementTagName.item(0); NodeList firstNodes = firstNameElement.getChildNodes(); latest = firstNodes.item(0).getNodeValue().replace("BlockLog", "").trim(); } String[] currentVersion = current.split("\\."); String[] latestVersion = latest.split("\\."); boolean updateAvailable = false; - for(int i=0;i<currentVersion.length;i++) { - if(Integer.valueOf(latestVersion[i]) > Integer.valueOf(currentVersion[i])) - updateAvailable = true; + for(int i=0;i<latestVersion.length;i++) { + if (currentVersion.length < latestVersion.length && Integer.valueOf(latestVersion[0]) >= Integer.valueOf(currentVersion[0]) && Integer.valueOf(latestVersion[1]) >= Integer.valueOf(currentVersion[1])) + { + updateAvailable = true; + break; + } + else if(Integer.valueOf(latestVersion[i]) > Integer.valueOf(currentVersion[i])) + { + updateAvailable = true; + break; + } + else if(Integer.valueOf(latestVersion[i]) < Integer.valueOf(currentVersion[i])) + break; } if(updateAvailable) { Util.sendNotice("BlockLog v" + latest + " is released! You're using BlockLog v" + current); Util.sendNotice("Update BlockLog at http://dev.bukkit.org/server-mods/block-log/"); } } catch (Exception e) { // This happens when dev.bukkit.org is offline } } }
true
true
public void run() { try { URL url = new URL("http://dev.bukkit.org/server-mods/block-log/files.rss"); Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(url.openConnection().getInputStream()); doc.getDocumentElement().normalize(); NodeList nodes = doc.getElementsByTagName("item"); Node firstNode = nodes.item(0); if (firstNode.getNodeType() == 1) { Element firstElement = (Element) firstNode; NodeList firstElementTagName = firstElement.getElementsByTagName("title"); Element firstNameElement = (Element) firstElementTagName.item(0); NodeList firstNodes = firstNameElement.getChildNodes(); latest = firstNodes.item(0).getNodeValue().replace("BlockLog", "").trim(); } String[] currentVersion = current.split("\\."); String[] latestVersion = latest.split("\\."); boolean updateAvailable = false; for(int i=0;i<currentVersion.length;i++) { if(Integer.valueOf(latestVersion[i]) > Integer.valueOf(currentVersion[i])) updateAvailable = true; } if(updateAvailable) { Util.sendNotice("BlockLog v" + latest + " is released! You're using BlockLog v" + current); Util.sendNotice("Update BlockLog at http://dev.bukkit.org/server-mods/block-log/"); } } catch (Exception e) { // This happens when dev.bukkit.org is offline } }
public void run() { try { URL url = new URL("http://dev.bukkit.org/server-mods/block-log/files.rss"); Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(url.openConnection().getInputStream()); doc.getDocumentElement().normalize(); NodeList nodes = doc.getElementsByTagName("item"); Node firstNode = nodes.item(0); if (firstNode.getNodeType() == 1) { Element firstElement = (Element) firstNode; NodeList firstElementTagName = firstElement.getElementsByTagName("title"); Element firstNameElement = (Element) firstElementTagName.item(0); NodeList firstNodes = firstNameElement.getChildNodes(); latest = firstNodes.item(0).getNodeValue().replace("BlockLog", "").trim(); } String[] currentVersion = current.split("\\."); String[] latestVersion = latest.split("\\."); boolean updateAvailable = false; for(int i=0;i<latestVersion.length;i++) { if (currentVersion.length < latestVersion.length && Integer.valueOf(latestVersion[0]) >= Integer.valueOf(currentVersion[0]) && Integer.valueOf(latestVersion[1]) >= Integer.valueOf(currentVersion[1])) { updateAvailable = true; break; } else if(Integer.valueOf(latestVersion[i]) > Integer.valueOf(currentVersion[i])) { updateAvailable = true; break; } else if(Integer.valueOf(latestVersion[i]) < Integer.valueOf(currentVersion[i])) break; } if(updateAvailable) { Util.sendNotice("BlockLog v" + latest + " is released! You're using BlockLog v" + current); Util.sendNotice("Update BlockLog at http://dev.bukkit.org/server-mods/block-log/"); } } catch (Exception e) { // This happens when dev.bukkit.org is offline } }
diff --git a/src/com/tulskiy/musique/gui/playlist/ProgressDialog.java b/src/com/tulskiy/musique/gui/playlist/ProgressDialog.java index 1d69fa8..4bac93f 100644 --- a/src/com/tulskiy/musique/gui/playlist/ProgressDialog.java +++ b/src/com/tulskiy/musique/gui/playlist/ProgressDialog.java @@ -1,130 +1,132 @@ /* * Copyright (c) 2008, 2009, 2010 Denis Tulskiy * * 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 * version 3 along with this work. If not, see <http://www.gnu.org/licenses/>. */ package com.tulskiy.musique.gui.playlist; import com.tulskiy.musique.playlist.Playlist; import com.tulskiy.musique.playlist.TagProcessor; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.util.LinkedList; /** * Author: Denis Tulskiy * Date: Jun 10, 2010 */ public class ProgressDialog extends JDialog { private JProgressBar progress; private JLabel status; private boolean stopLoading = false; private TagProcessor tagProcessor; public ProgressDialog(Frame owner, String message) { super(owner, message, true); setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); setSize(400, 100); setLocationRelativeTo(owner); progress = new JProgressBar(0, 100); status = new JLabel("Scanning folders..."); status.setBorder(BorderFactory.createMatteBorder(2, 0, 0, 0, Color.gray)); JButton cancel = new JButton("Cancel"); cancel.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { stopLoading = true; if (tagProcessor != null) { tagProcessor.cancel(); } } }); Box box = Box.createHorizontalBox(); box.add(progress); box.add(Box.createHorizontalStrut(10)); box.add(cancel); box.setBorder(BorderFactory.createEmptyBorder(10, 10, 0, 10)); add(box, BorderLayout.NORTH); add(status, BorderLayout.SOUTH); } public void addFiles(final Playlist playlist, final File[] files) { Thread t = new Thread(new Runnable() { @Override public void run() { stopLoading = false; progress.setIndeterminate(true); LinkedList<File> list = new LinkedList<File>(); for (File f : files) { if (f.isDirectory()) { loadDirectory(f, list); } else if (f.isFile()) { list.add(f); } } progress.setIndeterminate(false); progress.setMinimum(0); progress.setMaximum(list.size()); tagProcessor = new TagProcessor(list, playlist); Timer timer = new Timer(100, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { progress.setValue(progress.getMaximum() - tagProcessor.getFilesLeft()); - status.setText(tagProcessor.getCurrentFile().getPath()); + File currentFile = tagProcessor.getCurrentFile(); + if (currentFile != null) + status.setText(currentFile.getPath()); } }); timer.start(); tagProcessor.start(); setVisible(false); } }); t.start(); setVisible(true); } private void loadDirectory(File dir, LinkedList<File> list) { if (stopLoading) { return; } if (dir.isDirectory()) { File[] files = dir.listFiles(); for (File file : files) { if (stopLoading) { break; } if (file.isFile()) { list.add(file); } else { loadDirectory(file, list); } } } } }
true
true
public void addFiles(final Playlist playlist, final File[] files) { Thread t = new Thread(new Runnable() { @Override public void run() { stopLoading = false; progress.setIndeterminate(true); LinkedList<File> list = new LinkedList<File>(); for (File f : files) { if (f.isDirectory()) { loadDirectory(f, list); } else if (f.isFile()) { list.add(f); } } progress.setIndeterminate(false); progress.setMinimum(0); progress.setMaximum(list.size()); tagProcessor = new TagProcessor(list, playlist); Timer timer = new Timer(100, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { progress.setValue(progress.getMaximum() - tagProcessor.getFilesLeft()); status.setText(tagProcessor.getCurrentFile().getPath()); } }); timer.start(); tagProcessor.start(); setVisible(false); } }); t.start(); setVisible(true); }
public void addFiles(final Playlist playlist, final File[] files) { Thread t = new Thread(new Runnable() { @Override public void run() { stopLoading = false; progress.setIndeterminate(true); LinkedList<File> list = new LinkedList<File>(); for (File f : files) { if (f.isDirectory()) { loadDirectory(f, list); } else if (f.isFile()) { list.add(f); } } progress.setIndeterminate(false); progress.setMinimum(0); progress.setMaximum(list.size()); tagProcessor = new TagProcessor(list, playlist); Timer timer = new Timer(100, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { progress.setValue(progress.getMaximum() - tagProcessor.getFilesLeft()); File currentFile = tagProcessor.getCurrentFile(); if (currentFile != null) status.setText(currentFile.getPath()); } }); timer.start(); tagProcessor.start(); setVisible(false); } }); t.start(); setVisible(true); }
diff --git a/src/org/osgcc/osgcc5/soapydroid/levels/LevelData.java b/src/org/osgcc/osgcc5/soapydroid/levels/LevelData.java index 9d5b77b..16949f3 100644 --- a/src/org/osgcc/osgcc5/soapydroid/levels/LevelData.java +++ b/src/org/osgcc/osgcc5/soapydroid/levels/LevelData.java @@ -1,73 +1,77 @@ package org.osgcc.osgcc5.soapydroid.levels; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.InputStream; import java.util.List; import java.util.Scanner; import org.osgcc.osgcc5.soapydroid.things.CollidableCow; import org.osgcc.osgcc5.soapydroid.things.CollidableEinstein; import org.osgcc.osgcc5.soapydroid.things.CollidableIceberg; import org.osgcc.osgcc5.soapydroid.things.CollidableRock; import org.osgcc.osgcc5.soapydroid.things.CollidableThing; import org.osgcc.osgcc5.soapydroid.things.CollidableTree; import android.content.res.Resources; import android.util.Log; import org.osgcc.osgcc5.soapydroid.EinsteinDefenseActivity; import org.osgcc.osgcc5.soapydroid.R; public class LevelData extends LevelInitializer{ Scanner scanner; public LevelData(List<CollidableThing> invaders, List<CollidableThing> projectilesActive, List<CollidableThing> projectilesInactive) throws FileNotFoundException { super(invaders, projectilesActive, projectilesInactive); // TODO Auto-generated constructor stub InputStream reader = EinsteinDefenseActivity.getTextCache().get(R.raw.leveldata); scanner = new Scanner(reader); } @Override public void initializeLists(int level) { int numberOfThings = scanner.nextInt(); CollidableThing[] thingsArray = new CollidableThing[numberOfThings]; String thingType = ""; for(int k = 0; k < thingsArray.length; k++ ) { thingType = scanner.next(); if(thingType.equals("Tree")) thingsArray[k] = new CollidableTree(); else if(thingType.equals("Rock")) thingsArray[k] = new CollidableRock(); else if(thingType.equals("Cow")) thingsArray[k] = new CollidableCow(); else thingsArray[k] = new CollidableEinstein(); thingsArray[k].setX(scanner.nextInt()); thingsArray[k].setY(scanner.nextInt()); thingsArray[k].setMass(scanner.nextInt()); Log.v("EinsteinDefenseActivity", "Type: " + thingType + "\n" + "x: " + thingsArray[k].getX() + "\n " + "y: " + thingsArray[k].getY() + "\n " + "Dx: " + thingsArray[k].getDx() + "\n " + "Dy: " + thingsArray[k].getDy() + "\n " + "mass: " + thingsArray[k].getMass() + "\n "); if(thingType.equals("Einstein")) + { thingsArray[k].setDy(scanner.nextInt()); + invaders.add(thingsArray[k]); + } + else projectilesInactive.add(thingsArray[k]); } } }
false
true
public void initializeLists(int level) { int numberOfThings = scanner.nextInt(); CollidableThing[] thingsArray = new CollidableThing[numberOfThings]; String thingType = ""; for(int k = 0; k < thingsArray.length; k++ ) { thingType = scanner.next(); if(thingType.equals("Tree")) thingsArray[k] = new CollidableTree(); else if(thingType.equals("Rock")) thingsArray[k] = new CollidableRock(); else if(thingType.equals("Cow")) thingsArray[k] = new CollidableCow(); else thingsArray[k] = new CollidableEinstein(); thingsArray[k].setX(scanner.nextInt()); thingsArray[k].setY(scanner.nextInt()); thingsArray[k].setMass(scanner.nextInt()); Log.v("EinsteinDefenseActivity", "Type: " + thingType + "\n" + "x: " + thingsArray[k].getX() + "\n " + "y: " + thingsArray[k].getY() + "\n " + "Dx: " + thingsArray[k].getDx() + "\n " + "Dy: " + thingsArray[k].getDy() + "\n " + "mass: " + thingsArray[k].getMass() + "\n "); if(thingType.equals("Einstein")) thingsArray[k].setDy(scanner.nextInt()); projectilesInactive.add(thingsArray[k]); } }
public void initializeLists(int level) { int numberOfThings = scanner.nextInt(); CollidableThing[] thingsArray = new CollidableThing[numberOfThings]; String thingType = ""; for(int k = 0; k < thingsArray.length; k++ ) { thingType = scanner.next(); if(thingType.equals("Tree")) thingsArray[k] = new CollidableTree(); else if(thingType.equals("Rock")) thingsArray[k] = new CollidableRock(); else if(thingType.equals("Cow")) thingsArray[k] = new CollidableCow(); else thingsArray[k] = new CollidableEinstein(); thingsArray[k].setX(scanner.nextInt()); thingsArray[k].setY(scanner.nextInt()); thingsArray[k].setMass(scanner.nextInt()); Log.v("EinsteinDefenseActivity", "Type: " + thingType + "\n" + "x: " + thingsArray[k].getX() + "\n " + "y: " + thingsArray[k].getY() + "\n " + "Dx: " + thingsArray[k].getDx() + "\n " + "Dy: " + thingsArray[k].getDy() + "\n " + "mass: " + thingsArray[k].getMass() + "\n "); if(thingType.equals("Einstein")) { thingsArray[k].setDy(scanner.nextInt()); invaders.add(thingsArray[k]); } else projectilesInactive.add(thingsArray[k]); } }
diff --git a/java/src/org/jruby/jubilee/impl/DefaultRackEnvironment.java b/java/src/org/jruby/jubilee/impl/DefaultRackEnvironment.java index ffaaae7..1bf2a3e 100644 --- a/java/src/org/jruby/jubilee/impl/DefaultRackEnvironment.java +++ b/java/src/org/jruby/jubilee/impl/DefaultRackEnvironment.java @@ -1,99 +1,99 @@ package org.jruby.jubilee.impl; import org.jruby.RubyArray; import org.jruby.RubyString; import org.jruby.jubilee.RackEnvironment; import org.jruby.jubilee.Const; import org.jruby.Ruby; import org.jruby.RubyHash; import org.jruby.jubilee.RackInput; import org.vertx.java.core.MultiMap; import org.vertx.java.core.http.HttpServerRequest; import java.util.Map; /** * Created with IntelliJ IDEA. * User: isaiah * Date: 11/26/12 * Time: 11:40 AM */ public class DefaultRackEnvironment implements RackEnvironment { private RubyHash env; private MultiMap headers; private Ruby runtime; public DefaultRackEnvironment(final Ruby runtime, final HttpServerRequest request, RackInput input, boolean isSSL) { this.runtime = runtime; // DEFAULT env = RubyHash.newHash(runtime); env.put(Const.RACK_VERSION, Const.RackVersion(runtime)); env.put(Const.RACK_ERRORS, new RubyIORackErrors(runtime)); env.put(Const.RACK_MULTITHREAD, true); env.put(Const.RACK_MULTIPROCESS, false); env.put(Const.RACK_RUNONCE, true); if (isSSL) env.put(Const.URL_SCHEME, Const.HTTPS); else env.put(Const.URL_SCHEME, Const.HTTP); env.put(Const.SCRIPT_NAME, ""); env.put(Const.SERVER_PROTOCOL, Const.HTTP_11); env.put(Const.SERVER_SOFTWARE, Const.JUBILEE_VERSION); env.put(Const.GATEWAY_INTERFACE, Const.CGI_VER); // Parse request headers headers = request.headers(); String host; if ((host = headers.get(Const.Vertx.HOST)) != null) { int colon = host.indexOf(":"); if (colon > 0) { env.put(Const.SERVER_NAME, host.substring(0, colon)); env.put(Const.SERVER_PORT, host.substring(colon + 1)); } else { env.put(Const.SERVER_NAME, host); env.put(Const.SERVER_PORT, Const.PORT_80); } } else { env.put(Const.SERVER_NAME, Const.LOCALHOST); env.put(Const.SERVER_PORT, Const.PORT_80); } env.put(Const.RACK_INPUT, input); env.put(Const.REQUEST_METHOD, request.method()); env.put(Const.REQUEST_PATH, request.path()); env.put(Const.REQUEST_URI, request.uri()); env.put(Const.QUERY_STRING, orEmpty(request.query())); - env.put(Const.REMOTE_ADDR, request.remoteAddress()); + env.put(Const.REMOTE_ADDR, request.remoteAddress().getHostString()); env.put(Const.HTTP_HOST, host); env.put(Const.HTTP_COOKIE, orEmpty(headers.get(Const.Vertx.COOKIE))); env.put(Const.HTTP_USER_AGENT, headers.get(Const.Vertx.USER_AGENT)); env.put(Const.HTTP_ACCEPT, headers.get(Const.Vertx.ACCEPT)); env.put(Const.HTTP_ACCEPT_LANGUAGE, orEmpty(headers.get(Const.Vertx.ACCEPT_LANGUAGE))); env.put(Const.HTTP_ACCEPT_ENCODING, orEmpty(headers.get(Const.Vertx.ACCEPT_ENCODING))); env.put(Const.HTTP_CONNECTION, orEmpty(headers.get(Const.Vertx.CONNECTION))); env.put(Const.HTTP_CONTENT_TYPE, orEmpty(headers.get(Const.Vertx.CONTENT_TYPE))); String contentLength; if ((contentLength = headers.get(Const.Vertx.CONTENT_LENGTH)) != null) env.put(Const.HTTP_CONTENT_LENGTH, contentLength); env.put(Const.PATH_INFO, request.path()); // Additional headers for (Map.Entry<String, String> var : Const.ADDITIONAL_HEADERS.entrySet()) setRackHeader(var.getKey(), var.getValue()); } public RubyHash getEnv() { return env; } private RubyString orEmpty(String jString) { return jString == null ? RubyString.newEmptyString(runtime) : RubyString.newString(runtime, jString); } private void setRackHeader(String vertxHeader, String rackHeader) { if (headers.contains(vertxHeader)) env.put(rackHeader, headers.get(vertxHeader)); } }
true
true
public DefaultRackEnvironment(final Ruby runtime, final HttpServerRequest request, RackInput input, boolean isSSL) { this.runtime = runtime; // DEFAULT env = RubyHash.newHash(runtime); env.put(Const.RACK_VERSION, Const.RackVersion(runtime)); env.put(Const.RACK_ERRORS, new RubyIORackErrors(runtime)); env.put(Const.RACK_MULTITHREAD, true); env.put(Const.RACK_MULTIPROCESS, false); env.put(Const.RACK_RUNONCE, true); if (isSSL) env.put(Const.URL_SCHEME, Const.HTTPS); else env.put(Const.URL_SCHEME, Const.HTTP); env.put(Const.SCRIPT_NAME, ""); env.put(Const.SERVER_PROTOCOL, Const.HTTP_11); env.put(Const.SERVER_SOFTWARE, Const.JUBILEE_VERSION); env.put(Const.GATEWAY_INTERFACE, Const.CGI_VER); // Parse request headers headers = request.headers(); String host; if ((host = headers.get(Const.Vertx.HOST)) != null) { int colon = host.indexOf(":"); if (colon > 0) { env.put(Const.SERVER_NAME, host.substring(0, colon)); env.put(Const.SERVER_PORT, host.substring(colon + 1)); } else { env.put(Const.SERVER_NAME, host); env.put(Const.SERVER_PORT, Const.PORT_80); } } else { env.put(Const.SERVER_NAME, Const.LOCALHOST); env.put(Const.SERVER_PORT, Const.PORT_80); } env.put(Const.RACK_INPUT, input); env.put(Const.REQUEST_METHOD, request.method()); env.put(Const.REQUEST_PATH, request.path()); env.put(Const.REQUEST_URI, request.uri()); env.put(Const.QUERY_STRING, orEmpty(request.query())); env.put(Const.REMOTE_ADDR, request.remoteAddress()); env.put(Const.HTTP_HOST, host); env.put(Const.HTTP_COOKIE, orEmpty(headers.get(Const.Vertx.COOKIE))); env.put(Const.HTTP_USER_AGENT, headers.get(Const.Vertx.USER_AGENT)); env.put(Const.HTTP_ACCEPT, headers.get(Const.Vertx.ACCEPT)); env.put(Const.HTTP_ACCEPT_LANGUAGE, orEmpty(headers.get(Const.Vertx.ACCEPT_LANGUAGE))); env.put(Const.HTTP_ACCEPT_ENCODING, orEmpty(headers.get(Const.Vertx.ACCEPT_ENCODING))); env.put(Const.HTTP_CONNECTION, orEmpty(headers.get(Const.Vertx.CONNECTION))); env.put(Const.HTTP_CONTENT_TYPE, orEmpty(headers.get(Const.Vertx.CONTENT_TYPE))); String contentLength; if ((contentLength = headers.get(Const.Vertx.CONTENT_LENGTH)) != null) env.put(Const.HTTP_CONTENT_LENGTH, contentLength); env.put(Const.PATH_INFO, request.path()); // Additional headers for (Map.Entry<String, String> var : Const.ADDITIONAL_HEADERS.entrySet()) setRackHeader(var.getKey(), var.getValue()); }
public DefaultRackEnvironment(final Ruby runtime, final HttpServerRequest request, RackInput input, boolean isSSL) { this.runtime = runtime; // DEFAULT env = RubyHash.newHash(runtime); env.put(Const.RACK_VERSION, Const.RackVersion(runtime)); env.put(Const.RACK_ERRORS, new RubyIORackErrors(runtime)); env.put(Const.RACK_MULTITHREAD, true); env.put(Const.RACK_MULTIPROCESS, false); env.put(Const.RACK_RUNONCE, true); if (isSSL) env.put(Const.URL_SCHEME, Const.HTTPS); else env.put(Const.URL_SCHEME, Const.HTTP); env.put(Const.SCRIPT_NAME, ""); env.put(Const.SERVER_PROTOCOL, Const.HTTP_11); env.put(Const.SERVER_SOFTWARE, Const.JUBILEE_VERSION); env.put(Const.GATEWAY_INTERFACE, Const.CGI_VER); // Parse request headers headers = request.headers(); String host; if ((host = headers.get(Const.Vertx.HOST)) != null) { int colon = host.indexOf(":"); if (colon > 0) { env.put(Const.SERVER_NAME, host.substring(0, colon)); env.put(Const.SERVER_PORT, host.substring(colon + 1)); } else { env.put(Const.SERVER_NAME, host); env.put(Const.SERVER_PORT, Const.PORT_80); } } else { env.put(Const.SERVER_NAME, Const.LOCALHOST); env.put(Const.SERVER_PORT, Const.PORT_80); } env.put(Const.RACK_INPUT, input); env.put(Const.REQUEST_METHOD, request.method()); env.put(Const.REQUEST_PATH, request.path()); env.put(Const.REQUEST_URI, request.uri()); env.put(Const.QUERY_STRING, orEmpty(request.query())); env.put(Const.REMOTE_ADDR, request.remoteAddress().getHostString()); env.put(Const.HTTP_HOST, host); env.put(Const.HTTP_COOKIE, orEmpty(headers.get(Const.Vertx.COOKIE))); env.put(Const.HTTP_USER_AGENT, headers.get(Const.Vertx.USER_AGENT)); env.put(Const.HTTP_ACCEPT, headers.get(Const.Vertx.ACCEPT)); env.put(Const.HTTP_ACCEPT_LANGUAGE, orEmpty(headers.get(Const.Vertx.ACCEPT_LANGUAGE))); env.put(Const.HTTP_ACCEPT_ENCODING, orEmpty(headers.get(Const.Vertx.ACCEPT_ENCODING))); env.put(Const.HTTP_CONNECTION, orEmpty(headers.get(Const.Vertx.CONNECTION))); env.put(Const.HTTP_CONTENT_TYPE, orEmpty(headers.get(Const.Vertx.CONTENT_TYPE))); String contentLength; if ((contentLength = headers.get(Const.Vertx.CONTENT_LENGTH)) != null) env.put(Const.HTTP_CONTENT_LENGTH, contentLength); env.put(Const.PATH_INFO, request.path()); // Additional headers for (Map.Entry<String, String> var : Const.ADDITIONAL_HEADERS.entrySet()) setRackHeader(var.getKey(), var.getValue()); }
diff --git a/activemq-amqp/src/main/java/org/apache/activemq/transport/amqp/AmqpProtocolConverter.java b/activemq-amqp/src/main/java/org/apache/activemq/transport/amqp/AmqpProtocolConverter.java index a3453f31f..8cc545e22 100644 --- a/activemq-amqp/src/main/java/org/apache/activemq/transport/amqp/AmqpProtocolConverter.java +++ b/activemq-amqp/src/main/java/org/apache/activemq/transport/amqp/AmqpProtocolConverter.java @@ -1,1148 +1,1148 @@ /** * 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.activemq.transport.amqp; import org.apache.activemq.broker.BrokerContext; import org.apache.activemq.command.*; import org.apache.activemq.transport.amqp.transform.*; import org.apache.activemq.util.IOExceptionSupport; import org.apache.activemq.util.IdGenerator; import org.apache.activemq.util.LongSequenceGenerator; import org.apache.qpid.proton.engine.*; import org.apache.qpid.proton.engine.impl.*; import org.apache.qpid.proton.framing.TransportFrame; import org.apache.qpid.proton.type.Binary; import org.apache.qpid.proton.type.DescribedType; import org.apache.qpid.proton.type.Symbol; import org.apache.qpid.proton.type.messaging.*; import org.apache.qpid.proton.type.messaging.Modified; import org.apache.qpid.proton.type.messaging.Rejected; import org.apache.qpid.proton.type.messaging.Released; import org.apache.qpid.proton.type.transaction.*; import org.apache.qpid.proton.type.transport.DeliveryState; import org.apache.qpid.proton.type.transport.SenderSettleMode; import org.apache.qpid.proton.type.transport.Source; import org.fusesource.hawtbuf.Buffer; import org.fusesource.hawtbuf.ByteArrayOutputStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.jms.InvalidSelectorException; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.ReentrantLock; class AmqpProtocolConverter { public static final EnumSet<EndpointState> UNINITIALIZED_SET = EnumSet.of(EndpointState.UNINITIALIZED); public static final EnumSet<EndpointState> INITIALIZED_SET = EnumSet.complementOf(UNINITIALIZED_SET); public static final EnumSet<EndpointState> ACTIVE_STATE = EnumSet.of(EndpointState.ACTIVE); public static final EnumSet<EndpointState> CLOSED_STATE = EnumSet.of(EndpointState.CLOSED); public static final EnumSet<EndpointState> ALL_STATES = EnumSet.of(EndpointState.CLOSED, EndpointState.ACTIVE, EndpointState.UNINITIALIZED); private static final Logger LOG = LoggerFactory.getLogger(AmqpProtocolConverter.class); static final public byte[] EMPTY_BYTE_ARRAY = new byte[]{}; private final AmqpTransport amqpTransport; private static final Symbol COPY = Symbol.getSymbol("copy"); private static final Symbol JMS_SELECTOR = Symbol.valueOf("jms-selector"); public AmqpProtocolConverter(AmqpTransport amqpTransport, BrokerContext brokerContext) { this.amqpTransport = amqpTransport; } ReentrantLock lock = new ReentrantLock(); // // private static final Buffer PING_RESP_FRAME = new PINGRESP().encode(); // // // private final LongSequenceGenerator messageIdGenerator = new LongSequenceGenerator(); // private final LongSequenceGenerator consumerIdGenerator = new LongSequenceGenerator(); // // private final ConcurrentHashMap<ConsumerId, AmqpSubscription> subscriptionsByConsumerId = new ConcurrentHashMap<ConsumerId, AmqpSubscription>(); // private final ConcurrentHashMap<UTF8Buffer, AmqpSubscription> amqpSubscriptionByTopic = new ConcurrentHashMap<UTF8Buffer, AmqpSubscription>(); // private final Map<UTF8Buffer, ActiveMQTopic> activeMQTopicMap = new LRUCache<UTF8Buffer, ActiveMQTopic>(); // private final Map<Destination, UTF8Buffer> amqpTopicMap = new LRUCache<Destination, UTF8Buffer>(); // private final Map<Short, MessageAck> consumerAcks = new LRUCache<Short, MessageAck>(); // private final Map<Short, PUBREC> publisherRecs = new LRUCache<Short, PUBREC>(); // // private final AtomicBoolean connected = new AtomicBoolean(false); // private CONNECT connect; // private String clientId; // private final String QOS_PROPERTY_NAME = "QoSPropertyName"; TransportImpl protonTransport = new TransportImpl(); ConnectionImpl protonConnection = new ConnectionImpl(); { this.protonTransport.bind(this.protonConnection); this.protonTransport.setProtocolTracer(new ProtocolTracer() { @Override public void receivedFrame(TransportFrame transportFrame) { System.out.println(String.format("RECV: %05d | %s", transportFrame.getChannel(), transportFrame.getBody())); } @Override public void sentFrame(TransportFrame transportFrame) { System.out.println(String.format("SENT: %05d | %s", transportFrame.getChannel(), transportFrame.getBody())); } }); } void pumpProtonToSocket() { try { int size = 1024 * 64; byte data[] = new byte[size]; boolean done = false; while (!done) { int count = protonTransport.output(data, 0, size); if (count > 0) { final Buffer buffer; buffer = new Buffer(data, 0, count); // System.out.println("writing: " + buffer.toString().substring(5).replaceAll("(..)", "$1 ")); amqpTransport.sendToAmqp(buffer); } else { done = true; } } // System.out.println("write done"); } catch (IOException e) { amqpTransport.onException(e); } } static class AmqpSessionContext { private final SessionId sessionId; long nextProducerId = 0; long nextConsumerId = 0; public AmqpSessionContext(ConnectionId connectionId, long id) { sessionId = new SessionId(connectionId, id); } } Sasl sasl; /** * Convert a AMQP command */ public void onAMQPData(Object command) throws Exception { Buffer frame; if( command.getClass() == AmqpHeader.class ) { AmqpHeader header = (AmqpHeader)command; switch( header.getProtocolId() ) { case 0: // amqpTransport.sendToAmqp(new AmqpHeader()); break; // nothing to do.. case 3: // Client will be using SASL for auth.. sasl = protonTransport.sasl(); sasl.setMechanisms(new String[]{"ANONYMOUS", "PLAIN"}); sasl.server(); break; default: } frame = header.getBuffer(); } else { frame = (Buffer)command; } onFrame(frame); } public void onFrame(Buffer frame) throws Exception { // System.out.println("read: " + frame.toString().substring(5).replaceAll("(..)", "$1 ")); while( frame.length > 0 ) { try { int count = protonTransport.input(frame.data, frame.offset, frame.length); frame.moveHead(count); } catch (Throwable e) { handleException(new AmqpProtocolException("Could not decode AMQP frame: " + frame, true, e)); } try { if( sasl!=null ) { // Lets try to complete the sasl handshake. if( sasl.getRemoteMechanisms().length > 0 ) { if( "PLAIN".equals(sasl.getRemoteMechanisms()[0]) ) { byte[] data = new byte[sasl.pending()]; sasl.recv(data, 0, data.length); Buffer[] parts = new Buffer(data).split((byte) 0); if( parts.length > 0 ) { connectionInfo.setUserName(parts[0].utf8().toString()); } if( parts.length > 1 ) { connectionInfo.setPassword(parts[1].utf8().toString()); } // We can't really auth at this point since we don't know the client id yet.. :( sasl.done(Sasl.SaslOutcome.PN_SASL_OK); amqpTransport.getWireFormat().magicRead = false; sasl = null; } else if( "ANONYMOUS".equals(sasl.getRemoteMechanisms()[0]) ) { sasl.done(Sasl.SaslOutcome.PN_SASL_OK); amqpTransport.getWireFormat().magicRead = false; sasl = null; } } } // Handle the amqp open.. if (protonConnection.getLocalState() == EndpointState.UNINITIALIZED && protonConnection.getRemoteState() != EndpointState.UNINITIALIZED) { onConnectionOpen(); } // Lets map amqp sessions to openwire sessions.. Session session = protonConnection.sessionHead(UNINITIALIZED_SET, INITIALIZED_SET); while (session != null) { onSessionOpen(session); session = protonConnection.sessionHead(UNINITIALIZED_SET, INITIALIZED_SET); } Link link = protonConnection.linkHead(UNINITIALIZED_SET, INITIALIZED_SET); while (link != null) { onLinkOpen(link); link = protonConnection.linkHead(UNINITIALIZED_SET, INITIALIZED_SET); } Delivery delivery = protonConnection.getWorkHead(); while (delivery != null) { AmqpDeliveryListener listener = (AmqpDeliveryListener) delivery.getLink().getContext(); if (listener != null) { listener.onDelivery(delivery); } delivery = delivery.getWorkNext(); } link = protonConnection.linkHead(ACTIVE_STATE, CLOSED_STATE); while (link != null) { ((AmqpDeliveryListener)link.getContext()).onClose(); link.close(); link = link.next(ACTIVE_STATE, CLOSED_STATE); } link = protonConnection.linkHead(ACTIVE_STATE, ALL_STATES); while (link != null) { ((AmqpDeliveryListener)link.getContext()).drainCheck(); - link = link.next(ACTIVE_STATE, CLOSED_STATE); + link = link.next(ACTIVE_STATE, ALL_STATES); } session = protonConnection.sessionHead(ACTIVE_STATE, CLOSED_STATE); while (session != null) { //TODO - close links? onSessionClose(session); session = session.next(ACTIVE_STATE, CLOSED_STATE); } if (protonConnection.getLocalState() == EndpointState.ACTIVE && protonConnection.getRemoteState() == EndpointState.CLOSED) { doClose(); } } catch (Throwable e) { handleException(new AmqpProtocolException("Could not process AMQP commands", true, e)); } pumpProtonToSocket(); } } boolean closing = false; boolean closedSocket = false; private void doClose() { if( !closing ) { closing = true; sendToActiveMQ(new RemoveInfo(connectionId), new ResponseHandler() { @Override public void onResponse(AmqpProtocolConverter converter, Response response) throws IOException { protonConnection.close(); if( !closedSocket) { pumpProtonToSocket(); } } }); } } public void onAMQPException(IOException error) { closedSocket = true; if( !closing) { System.out.println("AMQP client disconnected"); error.printStackTrace(); } else { doClose(); } } public void onActiveMQCommand(Command command) throws Exception { if (command.isResponse()) { Response response = (Response) command; ResponseHandler rh = resposeHandlers.remove(Integer.valueOf(response.getCorrelationId())); if (rh != null) { rh.onResponse(this, response); } else { // Pass down any unexpected errors. Should this close the connection? if (response.isException()) { Throwable exception = ((ExceptionResponse) response).getException(); handleException(exception); } } } else if (command.isMessageDispatch()) { MessageDispatch md = (MessageDispatch) command; ConsumerContext consumerContext = subscriptionsByConsumerId.get(md.getConsumerId()); if (consumerContext != null) { consumerContext.onMessageDispatch(md); } } else if (command.getDataStructureType() == ConnectionError.DATA_STRUCTURE_TYPE) { // Pass down any unexpected async errors. Should this close the connection? Throwable exception = ((ConnectionError) command).getException(); handleException(exception); } else if (command.isBrokerInfo()) { //ignore } else { LOG.debug("Do not know how to process ActiveMQ Command " + command); } } private static final IdGenerator CONNECTION_ID_GENERATOR = new IdGenerator(); private final ConnectionId connectionId = new ConnectionId(CONNECTION_ID_GENERATOR.generateId()); private ConnectionInfo connectionInfo = new ConnectionInfo(); private long nextSessionId = 0; private long nextTempDestinationId = 0; static abstract class AmqpDeliveryListener { abstract public void onDelivery(Delivery delivery) throws Exception; public void onClose() throws Exception {} public void drainCheck() {} } private void onConnectionOpen() throws AmqpProtocolException { connectionInfo.setResponseRequired(true); connectionInfo.setConnectionId(connectionId); // configureInactivityMonitor(connect.keepAlive()); String clientId = protonConnection.getRemoteContainer(); if (clientId != null && !clientId.isEmpty()) { connectionInfo.setClientId(clientId); } else { connectionInfo.setClientId("" + connectionInfo.getConnectionId().toString()); } // String userName = ""; // if (connect.userName() != null) { // userName = connect.userName().toString(); // } // String passswd = ""; // if (connect.password() != null) { // passswd = connect.password().toString(); // } // connectionInfo.setUserName(userName); // connectionInfo.setPassword(passswd); connectionInfo.setTransportContext(amqpTransport.getPeerCertificates()); sendToActiveMQ(connectionInfo, new ResponseHandler() { public void onResponse(AmqpProtocolConverter converter, Response response) throws IOException { protonConnection.open(); pumpProtonToSocket(); if (response.isException()) { Throwable exception = ((ExceptionResponse) response).getException(); // TODO: figure out how to close /w an error. // protonConnection.setLocalError(new EndpointError(exception.getClass().getName(), exception.getMessage())); protonConnection.close(); pumpProtonToSocket(); amqpTransport.onException(IOExceptionSupport.create(exception)); return; } } }); } private void onSessionOpen(Session session) { AmqpSessionContext sessionContext = new AmqpSessionContext(connectionId, nextSessionId++); session.setContext(sessionContext); sendToActiveMQ(new SessionInfo(sessionContext.sessionId), null); session.open(); } private void onSessionClose(Session session) { AmqpSessionContext sessionContext = (AmqpSessionContext)session.getContext(); if( sessionContext!=null ) { System.out.println(sessionContext.sessionId); sendToActiveMQ(new RemoveInfo(sessionContext.sessionId), null); session.setContext(null); } session.close(); } private void onLinkOpen(Link link) { link.setSource(link.getRemoteSource()); link.setTarget(link.getRemoteTarget()); AmqpSessionContext sessionContext = (AmqpSessionContext) link.getSession().getContext(); if (link instanceof Receiver) { onReceiverOpen((Receiver) link, sessionContext); } else { onSenderOpen((Sender) link, sessionContext); } } InboundTransformer inboundTransformer; protected InboundTransformer getInboundTransformer() { if (inboundTransformer == null) { String transformer = amqpTransport.getTransformer(); if (transformer.equals(InboundTransformer.TRANSFORMER_JMS)) { inboundTransformer = new JMSMappingInboundTransformer(ActiveMQJMSVendor.INSTANCE); } else if (transformer.equals(InboundTransformer.TRANSFORMER_NATIVE)) { inboundTransformer = new AMQPNativeInboundTransformer(ActiveMQJMSVendor.INSTANCE); } else if (transformer.equals(InboundTransformer.TRANSFORMER_RAW)) { inboundTransformer = new AMQPRawInboundTransformer(ActiveMQJMSVendor.INSTANCE); } else { LOG.warn("Unknown transformer type " + transformer + ", using native one instead"); inboundTransformer = new AMQPNativeInboundTransformer(ActiveMQJMSVendor.INSTANCE); } } return inboundTransformer; } abstract class BaseProducerContext extends AmqpDeliveryListener { ByteArrayOutputStream current = new ByteArrayOutputStream(); @Override public void onDelivery(Delivery delivery) throws Exception { Receiver receiver = ((Receiver)delivery.getLink()); if( !delivery.isReadable() ) { System.out.println("it was not readable!"); // delivery.settle(); // receiver.advance(); return; } if( current==null ) { current = new ByteArrayOutputStream(); } int count; byte data[] = new byte[1024*4]; while( (count = receiver.recv(data, 0, data.length)) > 0 ) { current.write(data, 0, count); } // Expecting more deliveries.. if( count == 0 ) { return; } receiver.advance(); delivery.settle(); Buffer buffer = current.toBuffer(); current = null; onMessage(receiver, delivery, buffer); } abstract protected void onMessage(Receiver receiver, Delivery delivery, Buffer buffer) throws Exception; } class ProducerContext extends BaseProducerContext { private final ProducerId producerId; private final LongSequenceGenerator messageIdGenerator = new LongSequenceGenerator(); private final ActiveMQDestination destination; public ProducerContext(ProducerId producerId, ActiveMQDestination destination) { this.producerId = producerId; this.destination = destination; } @Override protected void onMessage(Receiver receiver, Delivery delivery, Buffer buffer) throws Exception { EncodedMessage em = new EncodedMessage(delivery.getMessageFormat(), buffer.data, buffer.offset, buffer.length); final ActiveMQMessage message = (ActiveMQMessage) getInboundTransformer().transform(em); current = null; if( destination!=null ) { message.setJMSDestination(destination); } message.setProducerId(producerId); if( message.getMessageId()==null ) { message.setMessageId(new MessageId(producerId, messageIdGenerator.getNextSequenceId())); } DeliveryState remoteState = delivery.getRemoteState(); if( remoteState!=null && remoteState instanceof TransactionalState) { TransactionalState s = (TransactionalState) remoteState; long txid = toLong(s.getTxnId()); message.setTransactionId(new LocalTransactionId(connectionId, txid)); } message.onSend(); // sendToActiveMQ(message, createResponseHandler(command)); sendToActiveMQ(message, null); } } long nextTransactionId = 0; class Transaction { } HashMap<Long, Transaction> transactions = new HashMap<Long, Transaction>(); public byte[] toBytes(long value) { Buffer buffer = new Buffer(8); buffer.bigEndianEditor().writeLong(value); return buffer.data; } private long toLong(Binary value) { Buffer buffer = new Buffer(value.getArray(), value.getArrayOffset(), value.getLength()); return buffer.bigEndianEditor().readLong(); } AmqpDeliveryListener coordinatorContext = new BaseProducerContext() { @Override protected void onMessage(Receiver receiver, final Delivery delivery, Buffer buffer) throws Exception { org.apache.qpid.proton.message.Message msg = new org.apache.qpid.proton.message.Message(); int offset = buffer.offset; int len = buffer.length; while( len > 0 ) { final int decoded = msg.decode(buffer.data, offset, len); assert decoded > 0: "Make progress decoding the message"; offset += decoded; len -= decoded; } Object action = ((AmqpValue)msg.getBody()).getValue(); System.out.println("COORDINATOR received: "+action+", ["+buffer+"]"); if( action instanceof Declare ) { Declare declare = (Declare) action; if( declare.getGlobalId()!=null ) { throw new Exception("don't know how to handle a declare /w a set GlobalId"); } long txid = nextTransactionId++; TransactionInfo txinfo = new TransactionInfo(connectionId, new LocalTransactionId(connectionId, txid), TransactionInfo.BEGIN); sendToActiveMQ(txinfo, null); System.out.println("started transaction "+txid); Declared declared = new Declared(); declared.setTxnId(new Binary(toBytes(txid))); delivery.disposition(declared); delivery.settle(); } else if( action instanceof Discharge) { Discharge discharge = (Discharge) action; long txid = toLong(discharge.getTxnId()); byte operation; if( discharge.getFail() ) { System.out.println("rollback transaction "+txid); operation = TransactionInfo.ROLLBACK ; } else { System.out.println("commit transaction "+txid); operation = TransactionInfo.COMMIT_ONE_PHASE; } TransactionInfo txinfo = new TransactionInfo(connectionId, new LocalTransactionId(connectionId, txid), operation); sendToActiveMQ(txinfo, new ResponseHandler() { @Override public void onResponse(AmqpProtocolConverter converter, Response response) throws IOException { if( response.isException() ) { ExceptionResponse er = (ExceptionResponse)response; Rejected rejected = new Rejected(); ArrayList errors = new ArrayList(); errors.add(er.getException().getMessage()); rejected.setError(errors); delivery.disposition(rejected); } delivery.settle(); pumpProtonToSocket(); } }); receiver.advance(); } else { throw new Exception("Expected coordinator message type: "+action.getClass()); } } }; void onReceiverOpen(final Receiver receiver, AmqpSessionContext sessionContext) { // Client is producing to this receiver object org.apache.qpid.proton.type.transport.Target remoteTarget = receiver.getRemoteTarget(); if( remoteTarget instanceof Coordinator ) { pumpProtonToSocket(); receiver.setContext(coordinatorContext); receiver.flow(1024 * 64); receiver.open(); pumpProtonToSocket(); } else { org.apache.qpid.proton.type.messaging.Target target = (Target) remoteTarget; ProducerId producerId = new ProducerId(sessionContext.sessionId, sessionContext.nextProducerId++); ActiveMQDestination dest; if( target.getDynamic() ) { dest = createTempQueue(); org.apache.qpid.proton.type.messaging.Target actualTarget = new org.apache.qpid.proton.type.messaging.Target(); actualTarget.setAddress(dest.getQualifiedName()); actualTarget.setDynamic(true); receiver.setTarget(actualTarget); } else { dest = createDestination(remoteTarget); } ProducerContext producerContext = new ProducerContext(producerId, dest); receiver.setContext(producerContext); receiver.flow(1024 * 64); ProducerInfo producerInfo = new ProducerInfo(producerId); producerInfo.setDestination(dest); sendToActiveMQ(producerInfo, new ResponseHandler() { public void onResponse(AmqpProtocolConverter converter, Response response) throws IOException { if (response.isException()) { receiver.setTarget(null); Throwable exception = ((ExceptionResponse) response).getException(); ((LinkImpl)receiver).setLocalError(new EndpointError(exception.getClass().getName(), exception.getMessage())); receiver.close(); } else { receiver.open(); } pumpProtonToSocket(); } }); } } private ActiveMQDestination createDestination(Object terminus) { if( terminus == null ) { return null; } else if( terminus instanceof org.apache.qpid.proton.type.messaging.Source) { org.apache.qpid.proton.type.messaging.Source source = (org.apache.qpid.proton.type.messaging.Source)terminus; return ActiveMQDestination.createDestination(source.getAddress(), ActiveMQDestination.QUEUE_TYPE); } else if( terminus instanceof org.apache.qpid.proton.type.messaging.Target) { org.apache.qpid.proton.type.messaging.Target target = (org.apache.qpid.proton.type.messaging.Target)terminus; return ActiveMQDestination.createDestination(target.getAddress(), ActiveMQDestination.QUEUE_TYPE); } else if( terminus instanceof Coordinator ) { Coordinator target = (Coordinator)terminus; return null; } else { throw new RuntimeException("Unexpected terminus type: "+terminus); } } OutboundTransformer outboundTransformer = new AutoOutboundTransformer(ActiveMQJMSVendor.INSTANCE); class ConsumerContext extends AmqpDeliveryListener { private final ConsumerId consumerId; private final Sender sender; private boolean presettle; public ConsumerContext(ConsumerId consumerId, Sender sender) { this.consumerId = consumerId; this.sender = sender; this.presettle = sender.getRemoteSenderSettleMode() == SenderSettleMode.SETTLED; } long nextTagId = 0; HashSet<byte[]> tagCache = new HashSet<byte[]>(); byte[] nextTag() { byte[] rc; if (tagCache != null && !tagCache.isEmpty()) { final Iterator<byte[]> iterator = tagCache.iterator(); rc = iterator.next(); iterator.remove(); } else { try { rc = Long.toHexString(nextTagId++).getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } return rc; } void checkinTag(byte[] data) { if( tagCache.size() < 1024 ) { tagCache.add(data); } } @Override public void onClose() throws Exception { sendToActiveMQ(new RemoveInfo(consumerId), null); } LinkedList<MessageDispatch> outbound = new LinkedList<MessageDispatch>(); // called when the connection receives a JMS message from ActiveMQ public void onMessageDispatch(MessageDispatch md) throws Exception { outbound.addLast(md); pumpOutbound(); pumpProtonToSocket(); } Buffer currentBuffer; Delivery currentDelivery; public void pumpOutbound() throws Exception { while(true) { while( currentBuffer !=null ) { int sent = sender.send(currentBuffer.data, currentBuffer.offset, currentBuffer.length); if( sent > 0 ) { currentBuffer.moveHead(sent); if( currentBuffer.length == 0 ) { if( presettle ) { settle(currentDelivery, MessageAck.INDIVIDUAL_ACK_TYPE); } else { sender.advance(); } currentBuffer = null; currentDelivery = null; } } else { return; } } if( outbound.isEmpty() ) { return; } final MessageDispatch md = outbound.removeFirst(); try { final ActiveMQMessage jms = (ActiveMQMessage) md.getMessage(); if( jms==null ) { // It's the end of browse signal. sender.drained(); } else { jms.setRedeliveryCounter(md.getRedeliveryCounter()); final EncodedMessage amqp = outboundTransformer.transform(jms); if( amqp!=null && amqp.getLength() > 0 ) { currentBuffer = new Buffer(amqp.getArray(), amqp.getArrayOffset(), amqp.getLength()); if( presettle ) { currentDelivery = sender.delivery(EMPTY_BYTE_ARRAY, 0, 0); } else { final byte[] tag = nextTag(); currentDelivery = sender.delivery(tag, 0, tag.length); } currentDelivery.setContext(md); } else { // TODO: message could not be generated what now? } } } catch (Exception e) { e.printStackTrace(); } } } private void settle(final Delivery delivery, int ackType) throws Exception { byte[] tag = delivery.getTag(); if( tag !=null && tag.length>0 ) { checkinTag(tag); } if( ackType == -1) { // we are going to settle, but redeliver.. we we won't yet ack to ActiveMQ delivery.settle(); onMessageDispatch((MessageDispatch) delivery.getContext()); } else { MessageDispatch md = (MessageDispatch) delivery.getContext(); MessageAck ack = new MessageAck(); ack.setConsumerId(consumerId); ack.setFirstMessageId(md.getMessage().getMessageId()); ack.setLastMessageId(md.getMessage().getMessageId()); ack.setMessageCount(1); ack.setAckType((byte)ackType); ack.setDestination(md.getDestination()); DeliveryState remoteState = delivery.getRemoteState(); if( remoteState!=null && remoteState instanceof TransactionalState) { TransactionalState s = (TransactionalState) remoteState; long txid = toLong(s.getTxnId()); ack.setTransactionId(new LocalTransactionId(connectionId, txid)); } sendToActiveMQ(ack, new ResponseHandler() { @Override public void onResponse(AmqpProtocolConverter converter, Response response) throws IOException { if( response.isException() ) { if (response.isException()) { Throwable exception = ((ExceptionResponse) response).getException(); exception.printStackTrace(); sender.close(); } } else { delivery.settle(); } pumpProtonToSocket(); } }); } } @Override public void drainCheck() { if( outbound.isEmpty() ) { sender.drained(); } } @Override public void onDelivery(Delivery delivery) throws Exception { MessageDispatch md = (MessageDispatch) delivery.getContext(); final DeliveryState state = delivery.getRemoteState(); if( state instanceof Accepted ) { if( !delivery.remotelySettled() ) { delivery.disposition(new Accepted()); } settle(delivery, MessageAck.INDIVIDUAL_ACK_TYPE); } else if( state instanceof Rejected) { // re-deliver /w incremented delivery counter. md.setRedeliveryCounter(md.getRedeliveryCounter() + 1); settle(delivery, -1); } else if( state instanceof Released) { // re-deliver && don't increment the counter. settle(delivery, -1); } else if( state instanceof Modified) { Modified modified = (Modified) state; if ( modified.getDeliveryFailed() ) { // increment delivery counter.. md.setRedeliveryCounter(md.getRedeliveryCounter() + 1); } byte ackType = -1; Boolean undeliverableHere = modified.getUndeliverableHere(); if( undeliverableHere !=null && undeliverableHere ) { // receiver does not want the message.. // perhaps we should DLQ it? ackType = MessageAck.POSION_ACK_TYPE; } settle(delivery, ackType); } pumpOutbound(); } } private final ConcurrentHashMap<ConsumerId, ConsumerContext> subscriptionsByConsumerId = new ConcurrentHashMap<ConsumerId, ConsumerContext>(); void onSenderOpen(final Sender sender, AmqpSessionContext sessionContext) { // sender.get ConsumerId id = new ConsumerId(sessionContext.sessionId, sessionContext.nextConsumerId++); ConsumerContext consumerContext = new ConsumerContext(id, sender); subscriptionsByConsumerId.put(id, consumerContext); ActiveMQDestination dest; org.apache.qpid.proton.type.messaging.Source source = (org.apache.qpid.proton.type.messaging.Source)sender.getRemoteSource(); if( source != null && !source.getDynamic() ) { dest = createDestination(source); } else { // lets create a temp dest. dest = createTempQueue(); source = new org.apache.qpid.proton.type.messaging.Source(); source.setAddress(dest.getQualifiedName()); source.setDynamic(true); sender.setSource(source); } sender.setContext(consumerContext); ConsumerInfo consumerInfo = new ConsumerInfo(id); consumerInfo.setDestination(dest); consumerInfo.setPrefetchSize(100); consumerInfo.setDispatchAsync(true); if( source.getDistributionMode() == COPY) { consumerInfo.setBrowser(true); } Map filter = source.getFilter(); if (filter != null) { DescribedType value = (DescribedType)filter.get(JMS_SELECTOR); if( value!=null ) { consumerInfo.setSelector(value.getDescribed().toString()); } } sendToActiveMQ(consumerInfo, new ResponseHandler() { public void onResponse(AmqpProtocolConverter converter, Response response) throws IOException { if (response.isException()) { sender.setSource(null); Throwable exception = ((ExceptionResponse) response).getException(); String name = exception.getClass().getName(); if( exception instanceof InvalidSelectorException ) { name = "amqp:invalid-field"; } ((LinkImpl)sender).setLocalError(new EndpointError(name, exception.getMessage())); sender.close(); } else { sender.open(); } pumpProtonToSocket(); } }); } private ActiveMQDestination createTempQueue() { ActiveMQDestination rc; rc = new ActiveMQTempQueue(connectionId, nextTempDestinationId++); DestinationInfo info = new DestinationInfo(); info.setConnectionId(connectionId); info.setOperationType(DestinationInfo.ADD_OPERATION_TYPE); info.setDestination(rc); sendToActiveMQ(info, null); return rc; } // void onUnSubscribe(UNSUBSCRIBE command) { // UTF8Buffer[] topics = command.topics(); // if (topics != null) { // for (int i = 0; i < topics.length; i++) { // onUnSubscribe(topics[i]); // } // } // UNSUBACK ack = new UNSUBACK(); // ack.messageId(command.messageId()); // pumpOut(ack.encode()); // // } // // void onUnSubscribe(UTF8Buffer topicName) { // AmqpSubscription subs = amqpSubscriptionByTopic.remove(topicName); // if (subs != null) { // ConsumerInfo info = subs.getConsumerInfo(); // if (info != null) { // subscriptionsByConsumerId.remove(info.getConsumerId()); // } // RemoveInfo removeInfo = info.createRemoveCommand(); // sendToActiveMQ(removeInfo, null); // } // } // // // /** // * Dispatch a ActiveMQ command // */ // // // // void onAMQPPublish(PUBLISH command) throws IOException, JMSException { // checkConnected(); // } // // void onAMQPPubAck(PUBACK command) { // short messageId = command.messageId(); // MessageAck ack; // synchronized (consumerAcks) { // ack = consumerAcks.remove(messageId); // } // if (ack != null) { // amqpTransport.sendToActiveMQ(ack); // } // } // // void onAMQPPubRec(PUBREC commnand) { // //from a subscriber - send a PUBREL in response // PUBREL pubrel = new PUBREL(); // pubrel.messageId(commnand.messageId()); // pumpOut(pubrel.encode()); // } // // void onAMQPPubRel(PUBREL command) { // PUBREC ack; // synchronized (publisherRecs) { // ack = publisherRecs.remove(command.messageId()); // } // if (ack == null) { // LOG.warn("Unknown PUBREL: " + command.messageId() + " received"); // } // PUBCOMP pubcomp = new PUBCOMP(); // pubcomp.messageId(command.messageId()); // pumpOut(pubcomp.encode()); // } // // void onAMQPPubComp(PUBCOMP command) { // short messageId = command.messageId(); // MessageAck ack; // synchronized (consumerAcks) { // ack = consumerAcks.remove(messageId); // } // if (ack != null) { // amqpTransport.sendToActiveMQ(ack); // } // } // // // // // public AmqpTransport amqpTransport { // return amqpTransport; // } // // // // void configureInactivityMonitor(short heartBeat) { // try { // // int heartBeatMS = heartBeat * 1000; // AmqpInactivityMonitor monitor = amqpTransport.getInactivityMonitor(); // monitor.setProtocolConverter(this); // monitor.setReadCheckTime(heartBeatMS); // monitor.setInitialDelayTime(heartBeatMS); // monitor.startMonitorThread(); // // } catch (Exception ex) { // LOG.warn("Failed to start AMQP InactivityMonitor ", ex); // } // // LOG.debug(getClientId() + " AMQP Connection using heart beat of " + heartBeat + " secs"); // } // // // // void checkConnected() throws AmqpProtocolException { // if (!connected.get()) { // throw new AmqpProtocolException("Not connected."); // } // } // // private String getClientId() { // if (clientId == null) { // if (connect != null && connect.clientId() != null) { // clientId = connect.clientId().toString(); // } // } else { // clientId = ""; // } // return clientId; // } // // private void stopTransport() { // try { // amqpTransport.stop(); // } catch (Throwable e) { // LOG.debug("Failed to stop AMQP transport ", e); // } // } // // ResponseHandler createResponseHandler(final PUBLISH command) { // // if (command != null) { // switch (command.qos()) { // case AT_LEAST_ONCE: // return new ResponseHandler() { // public void onResponse(AmqpProtocolConverter converter, Response response) throws IOException { // if (response.isException()) { // LOG.warn("Failed to send AMQP Publish: ", command, ((ExceptionResponse) response).getException()); // } else { // PUBACK ack = new PUBACK(); // ack.messageId(command.messageId()); // converter.amqpTransport.sendToAmqp(ack.encode()); // } // } // }; // case EXACTLY_ONCE: // return new ResponseHandler() { // public void onResponse(AmqpProtocolConverter converter, Response response) throws IOException { // if (response.isException()) { // LOG.warn("Failed to send AMQP Publish: ", command, ((ExceptionResponse) response).getException()); // } else { // PUBREC ack = new PUBREC(); // ack.messageId(command.messageId()); // synchronized (publisherRecs) { // publisherRecs.put(command.messageId(), ack); // } // converter.amqpTransport.sendToAmqp(ack.encode()); // } // } // }; // case AT_MOST_ONCE: // break; // } // } // return null; // } // // private String convertAMQPToActiveMQ(String name) { // String result = name.replace('#', '>'); // result = result.replace('+', '*'); // result = result.replace('/', '.'); // return result; // } //////////////////////////////////////////////////////////////////////////// // // Implementation methods // //////////////////////////////////////////////////////////////////////////// private final Object commnadIdMutex = new Object(); private int lastCommandId; int generateCommandId() { synchronized (commnadIdMutex) { return lastCommandId++; } } private final ConcurrentHashMap<Integer, ResponseHandler> resposeHandlers = new ConcurrentHashMap<Integer, ResponseHandler>(); void sendToActiveMQ(Command command, ResponseHandler handler) { command.setCommandId(generateCommandId()); if (handler != null) { command.setResponseRequired(true); resposeHandlers.put(Integer.valueOf(command.getCommandId()), handler); } amqpTransport.sendToActiveMQ(command); } void handleException(Throwable exception) { exception.printStackTrace(); if (LOG.isDebugEnabled()) { LOG.debug("Exception detail", exception); } try { amqpTransport.stop(); } catch (Throwable e) { LOG.error("Failed to stop AMQP Transport ", e); } } }
true
true
public void onFrame(Buffer frame) throws Exception { // System.out.println("read: " + frame.toString().substring(5).replaceAll("(..)", "$1 ")); while( frame.length > 0 ) { try { int count = protonTransport.input(frame.data, frame.offset, frame.length); frame.moveHead(count); } catch (Throwable e) { handleException(new AmqpProtocolException("Could not decode AMQP frame: " + frame, true, e)); } try { if( sasl!=null ) { // Lets try to complete the sasl handshake. if( sasl.getRemoteMechanisms().length > 0 ) { if( "PLAIN".equals(sasl.getRemoteMechanisms()[0]) ) { byte[] data = new byte[sasl.pending()]; sasl.recv(data, 0, data.length); Buffer[] parts = new Buffer(data).split((byte) 0); if( parts.length > 0 ) { connectionInfo.setUserName(parts[0].utf8().toString()); } if( parts.length > 1 ) { connectionInfo.setPassword(parts[1].utf8().toString()); } // We can't really auth at this point since we don't know the client id yet.. :( sasl.done(Sasl.SaslOutcome.PN_SASL_OK); amqpTransport.getWireFormat().magicRead = false; sasl = null; } else if( "ANONYMOUS".equals(sasl.getRemoteMechanisms()[0]) ) { sasl.done(Sasl.SaslOutcome.PN_SASL_OK); amqpTransport.getWireFormat().magicRead = false; sasl = null; } } } // Handle the amqp open.. if (protonConnection.getLocalState() == EndpointState.UNINITIALIZED && protonConnection.getRemoteState() != EndpointState.UNINITIALIZED) { onConnectionOpen(); } // Lets map amqp sessions to openwire sessions.. Session session = protonConnection.sessionHead(UNINITIALIZED_SET, INITIALIZED_SET); while (session != null) { onSessionOpen(session); session = protonConnection.sessionHead(UNINITIALIZED_SET, INITIALIZED_SET); } Link link = protonConnection.linkHead(UNINITIALIZED_SET, INITIALIZED_SET); while (link != null) { onLinkOpen(link); link = protonConnection.linkHead(UNINITIALIZED_SET, INITIALIZED_SET); } Delivery delivery = protonConnection.getWorkHead(); while (delivery != null) { AmqpDeliveryListener listener = (AmqpDeliveryListener) delivery.getLink().getContext(); if (listener != null) { listener.onDelivery(delivery); } delivery = delivery.getWorkNext(); } link = protonConnection.linkHead(ACTIVE_STATE, CLOSED_STATE); while (link != null) { ((AmqpDeliveryListener)link.getContext()).onClose(); link.close(); link = link.next(ACTIVE_STATE, CLOSED_STATE); } link = protonConnection.linkHead(ACTIVE_STATE, ALL_STATES); while (link != null) { ((AmqpDeliveryListener)link.getContext()).drainCheck(); link = link.next(ACTIVE_STATE, CLOSED_STATE); } session = protonConnection.sessionHead(ACTIVE_STATE, CLOSED_STATE); while (session != null) { //TODO - close links? onSessionClose(session); session = session.next(ACTIVE_STATE, CLOSED_STATE); } if (protonConnection.getLocalState() == EndpointState.ACTIVE && protonConnection.getRemoteState() == EndpointState.CLOSED) { doClose(); } } catch (Throwable e) { handleException(new AmqpProtocolException("Could not process AMQP commands", true, e)); } pumpProtonToSocket(); } }
public void onFrame(Buffer frame) throws Exception { // System.out.println("read: " + frame.toString().substring(5).replaceAll("(..)", "$1 ")); while( frame.length > 0 ) { try { int count = protonTransport.input(frame.data, frame.offset, frame.length); frame.moveHead(count); } catch (Throwable e) { handleException(new AmqpProtocolException("Could not decode AMQP frame: " + frame, true, e)); } try { if( sasl!=null ) { // Lets try to complete the sasl handshake. if( sasl.getRemoteMechanisms().length > 0 ) { if( "PLAIN".equals(sasl.getRemoteMechanisms()[0]) ) { byte[] data = new byte[sasl.pending()]; sasl.recv(data, 0, data.length); Buffer[] parts = new Buffer(data).split((byte) 0); if( parts.length > 0 ) { connectionInfo.setUserName(parts[0].utf8().toString()); } if( parts.length > 1 ) { connectionInfo.setPassword(parts[1].utf8().toString()); } // We can't really auth at this point since we don't know the client id yet.. :( sasl.done(Sasl.SaslOutcome.PN_SASL_OK); amqpTransport.getWireFormat().magicRead = false; sasl = null; } else if( "ANONYMOUS".equals(sasl.getRemoteMechanisms()[0]) ) { sasl.done(Sasl.SaslOutcome.PN_SASL_OK); amqpTransport.getWireFormat().magicRead = false; sasl = null; } } } // Handle the amqp open.. if (protonConnection.getLocalState() == EndpointState.UNINITIALIZED && protonConnection.getRemoteState() != EndpointState.UNINITIALIZED) { onConnectionOpen(); } // Lets map amqp sessions to openwire sessions.. Session session = protonConnection.sessionHead(UNINITIALIZED_SET, INITIALIZED_SET); while (session != null) { onSessionOpen(session); session = protonConnection.sessionHead(UNINITIALIZED_SET, INITIALIZED_SET); } Link link = protonConnection.linkHead(UNINITIALIZED_SET, INITIALIZED_SET); while (link != null) { onLinkOpen(link); link = protonConnection.linkHead(UNINITIALIZED_SET, INITIALIZED_SET); } Delivery delivery = protonConnection.getWorkHead(); while (delivery != null) { AmqpDeliveryListener listener = (AmqpDeliveryListener) delivery.getLink().getContext(); if (listener != null) { listener.onDelivery(delivery); } delivery = delivery.getWorkNext(); } link = protonConnection.linkHead(ACTIVE_STATE, CLOSED_STATE); while (link != null) { ((AmqpDeliveryListener)link.getContext()).onClose(); link.close(); link = link.next(ACTIVE_STATE, CLOSED_STATE); } link = protonConnection.linkHead(ACTIVE_STATE, ALL_STATES); while (link != null) { ((AmqpDeliveryListener)link.getContext()).drainCheck(); link = link.next(ACTIVE_STATE, ALL_STATES); } session = protonConnection.sessionHead(ACTIVE_STATE, CLOSED_STATE); while (session != null) { //TODO - close links? onSessionClose(session); session = session.next(ACTIVE_STATE, CLOSED_STATE); } if (protonConnection.getLocalState() == EndpointState.ACTIVE && protonConnection.getRemoteState() == EndpointState.CLOSED) { doClose(); } } catch (Throwable e) { handleException(new AmqpProtocolException("Could not process AMQP commands", true, e)); } pumpProtonToSocket(); } }
diff --git a/src/com/ensifera/animosity/craftirc/RelayedMessage.java b/src/com/ensifera/animosity/craftirc/RelayedMessage.java index ca0e4e5..c943230 100644 --- a/src/com/ensifera/animosity/craftirc/RelayedMessage.java +++ b/src/com/ensifera/animosity/craftirc/RelayedMessage.java @@ -1,199 +1,199 @@ package com.ensifera.animosity.craftirc; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RelayedMessage { enum DeliveryMethod { STANDARD, ADMINS, COMMAND } static String typeString = "MSG"; private CraftIRC plugin; private EndPoint source; //Origin endpoint of the message private EndPoint target; //Target endpoint of the message private String eventType; //Event type private LinkedList<EndPoint> cc; //Multiple extra targets for the message private String template; //Formatting string private Map<String,String> fields; //All message attributes RelayedMessage(CraftIRC plugin, EndPoint source) { this(plugin, source, null, ""); } RelayedMessage(CraftIRC plugin, EndPoint source, EndPoint target) { this(plugin, source, target, ""); } RelayedMessage(CraftIRC plugin, EndPoint source, EndPoint target, String eventType) { this.plugin = plugin; this.source = source; this.target = target; if (eventType.equals("")) eventType = "generic"; this.eventType = eventType; this.template = "%message%"; if (eventType != null && eventType != "" && target != null) this.template = plugin.cFormatting(eventType, this); fields = new HashMap<String,String>(); } public CraftIRC getPlugin() { return this.plugin; } EndPoint getSource() { return source; } EndPoint getTarget() { return target; } public String getEvent() { return eventType; } public void setField(String key, String value) { fields.put(key, value); } public String getField(String key) { return fields.get(key); } public Set<String> setFields() { return fields.keySet(); } public void copyFields(RelayedMessage msg) { if (msg == null) return; for (String key : msg.setFields()) setField(key, msg.getField(key)); } public boolean addExtraTarget(EndPoint ep) { if (cc.contains(ep)) return false; cc.add(ep); return true; } public String getMessage() { return getMessage(null); } public String getMessage(EndPoint currentTarget) { String result = template; EndPoint realTarget; //Resolve target realTarget = target; if (realTarget == null) { if (currentTarget == null) return result; realTarget = currentTarget; result = plugin.cFormatting(eventType, this, realTarget); if (result == null) result = template; } //IRC color code aliases (actually not recommended) if (realTarget.getType() == EndPoint.Type.IRC) { result = result.replaceAll("%k([0-9]{1,2})%", Character.toString((char) 3) + "$1"); result = result.replaceAll("%k([0-9]{1,2}),([0-9]{1,2})%", Character.toString((char) 3) + "$1,$2"); result = result.replace("%k%", Character.toString((char) 3)); result = result.replace("%o%", Character.toString((char) 15)); result = result.replace("%b%", Character.toString((char) 2)); result = result.replace("%u%", Character.toString((char) 31)); result = result.replace("%r%", Character.toString((char) 22)); } else if (realTarget.getType() == EndPoint.Type.MINECRAFT) { result = result.replaceAll("%k([0-9]{1,2})%", ""); result = result.replaceAll("%k([0-9]{1,2}),([0-9]{1,2})%", ""); result = result.replace("%k%", plugin.cColorGameFromName("foreground")); result = result.replace("%o%", plugin.cColorGameFromName("foreground")); result = result.replace("%b%", ""); result = result.replace("%u%", ""); result = result.replace("%r%", ""); } else { result = result.replaceAll("%k([0-9]{1,2})%", ""); result = result.replaceAll("%k([0-9]{1,2}),([0-9]{1,2})%", ""); result = result.replace("%k%", ""); result = result.replace("%o%", ""); result = result.replace("%b%", ""); result = result.replace("%u%", ""); result = result.replace("%r%", ""); } //Fields and named colors (all the important stuff is here actually) Pattern other_vars = Pattern.compile("%([A-Za-z0-9]+)%"); Matcher find_vars = other_vars.matcher(result); while (find_vars.find()) { if (fields.get(find_vars.group(1)) != null) result = find_vars.replaceFirst(Matcher.quoteReplacement(fields.get(find_vars.group(1)))); else if (realTarget.getType() == EndPoint.Type.IRC) result = find_vars.replaceFirst(Character.toString((char) 3) + String.format("%02d", this.plugin.cColorIrcFromName(find_vars.group(1)))); else if (realTarget.getType() == EndPoint.Type.MINECRAFT) result = find_vars.replaceFirst(this.plugin.cColorGameFromName(find_vars.group(1))); else result = find_vars.replaceFirst(""); find_vars = other_vars.matcher(result); } //Convert colors boolean colors = plugin.cPathAttribute(fields.get("source"), fields.get("target"), "attributes.colors"); if (source.getType() == EndPoint.Type.MINECRAFT) { if (realTarget.getType() == EndPoint.Type.IRC && colors) { - Pattern color_codes = Pattern.compile("\u00C2\u00A7([A-Fa-f0-9])?"); + Pattern color_codes = Pattern.compile("\u00A7([A-Fa-f0-9])?"); Matcher find_colors = color_codes.matcher(result); while (find_colors.find()) { - result = find_colors.replaceFirst("\u0003" + Integer.toString(this.plugin.cColorIrcFromGame("\u00C2\u00A7" + find_colors.group(1)))); + result = find_colors.replaceFirst("\u0003" + Integer.toString(this.plugin.cColorIrcFromGame("\u00A7" + find_colors.group(1)))); find_colors = color_codes.matcher(result); } } else if (realTarget.getType() != EndPoint.Type.MINECRAFT || !colors) { //Strip colors - result = result.replaceAll("(\u00C2\u00A7([A-Fa-f0-9])?)", ""); + result = result.replaceAll("(\u00A7([A-Fa-f0-9])?)", ""); } } if (source.getType() == EndPoint.Type.IRC) { if (realTarget.getType() == EndPoint.Type.MINECRAFT && colors) { result = result.replaceAll("(" + Character.toString((char) 2) + "|" + Character.toString((char) 22) + "|" + Character.toString((char) 31) + ")", ""); Pattern color_codes = Pattern.compile(Character.toString((char) 3) + "([01]?[0-9])(,[0-9]{0,2})?"); Matcher find_colors = color_codes.matcher(result); while (find_colors.find()) { result = find_colors.replaceFirst(this.plugin.cColorGameFromIrc(Integer.parseInt(find_colors.group(1)))); find_colors = color_codes.matcher(result); } result = result.replaceAll(Character.toString((char) 15) + "|" + Character.toString((char) 3), this.plugin.cColorGameFromName("foreground")); } else if (realTarget.getType() != EndPoint.Type.IRC || !colors) { //Strip colors result = result.replaceAll( "(" + Character.toString((char) 2) + "|" + Character.toString((char) 15) + "|" + Character.toString((char) 22) + Character.toString((char) 31) + "|" + Character.toString((char) 3) + "[0-9]{0,2}(,[0-9]{0,2})?)", ""); } } return result; } public boolean post() { return post(DeliveryMethod.STANDARD, null); } public boolean post(boolean admin) { return post(admin ? DeliveryMethod.ADMINS : DeliveryMethod.STANDARD, null); } boolean post(DeliveryMethod dm, String username) { List<EndPoint> destinations; if (cc != null) destinations = new LinkedList<EndPoint>(cc); else destinations = new LinkedList<EndPoint>(); if (target != null) destinations.add(target); Collections.reverse(destinations); return plugin.delivery(this, destinations, username, dm); } public boolean postToUser(String username) { return post(DeliveryMethod.STANDARD, username); } public String toString() { String rep = "{" + eventType + " " + typeString + "}"; for(String key : fields.keySet()) rep = rep + " (" + key + ": " + fields.get(key) + ")"; return rep; } }
false
true
public String getMessage(EndPoint currentTarget) { String result = template; EndPoint realTarget; //Resolve target realTarget = target; if (realTarget == null) { if (currentTarget == null) return result; realTarget = currentTarget; result = plugin.cFormatting(eventType, this, realTarget); if (result == null) result = template; } //IRC color code aliases (actually not recommended) if (realTarget.getType() == EndPoint.Type.IRC) { result = result.replaceAll("%k([0-9]{1,2})%", Character.toString((char) 3) + "$1"); result = result.replaceAll("%k([0-9]{1,2}),([0-9]{1,2})%", Character.toString((char) 3) + "$1,$2"); result = result.replace("%k%", Character.toString((char) 3)); result = result.replace("%o%", Character.toString((char) 15)); result = result.replace("%b%", Character.toString((char) 2)); result = result.replace("%u%", Character.toString((char) 31)); result = result.replace("%r%", Character.toString((char) 22)); } else if (realTarget.getType() == EndPoint.Type.MINECRAFT) { result = result.replaceAll("%k([0-9]{1,2})%", ""); result = result.replaceAll("%k([0-9]{1,2}),([0-9]{1,2})%", ""); result = result.replace("%k%", plugin.cColorGameFromName("foreground")); result = result.replace("%o%", plugin.cColorGameFromName("foreground")); result = result.replace("%b%", ""); result = result.replace("%u%", ""); result = result.replace("%r%", ""); } else { result = result.replaceAll("%k([0-9]{1,2})%", ""); result = result.replaceAll("%k([0-9]{1,2}),([0-9]{1,2})%", ""); result = result.replace("%k%", ""); result = result.replace("%o%", ""); result = result.replace("%b%", ""); result = result.replace("%u%", ""); result = result.replace("%r%", ""); } //Fields and named colors (all the important stuff is here actually) Pattern other_vars = Pattern.compile("%([A-Za-z0-9]+)%"); Matcher find_vars = other_vars.matcher(result); while (find_vars.find()) { if (fields.get(find_vars.group(1)) != null) result = find_vars.replaceFirst(Matcher.quoteReplacement(fields.get(find_vars.group(1)))); else if (realTarget.getType() == EndPoint.Type.IRC) result = find_vars.replaceFirst(Character.toString((char) 3) + String.format("%02d", this.plugin.cColorIrcFromName(find_vars.group(1)))); else if (realTarget.getType() == EndPoint.Type.MINECRAFT) result = find_vars.replaceFirst(this.plugin.cColorGameFromName(find_vars.group(1))); else result = find_vars.replaceFirst(""); find_vars = other_vars.matcher(result); } //Convert colors boolean colors = plugin.cPathAttribute(fields.get("source"), fields.get("target"), "attributes.colors"); if (source.getType() == EndPoint.Type.MINECRAFT) { if (realTarget.getType() == EndPoint.Type.IRC && colors) { Pattern color_codes = Pattern.compile("\u00C2\u00A7([A-Fa-f0-9])?"); Matcher find_colors = color_codes.matcher(result); while (find_colors.find()) { result = find_colors.replaceFirst("\u0003" + Integer.toString(this.plugin.cColorIrcFromGame("\u00C2\u00A7" + find_colors.group(1)))); find_colors = color_codes.matcher(result); } } else if (realTarget.getType() != EndPoint.Type.MINECRAFT || !colors) { //Strip colors result = result.replaceAll("(\u00C2\u00A7([A-Fa-f0-9])?)", ""); } } if (source.getType() == EndPoint.Type.IRC) { if (realTarget.getType() == EndPoint.Type.MINECRAFT && colors) { result = result.replaceAll("(" + Character.toString((char) 2) + "|" + Character.toString((char) 22) + "|" + Character.toString((char) 31) + ")", ""); Pattern color_codes = Pattern.compile(Character.toString((char) 3) + "([01]?[0-9])(,[0-9]{0,2})?"); Matcher find_colors = color_codes.matcher(result); while (find_colors.find()) { result = find_colors.replaceFirst(this.plugin.cColorGameFromIrc(Integer.parseInt(find_colors.group(1)))); find_colors = color_codes.matcher(result); } result = result.replaceAll(Character.toString((char) 15) + "|" + Character.toString((char) 3), this.plugin.cColorGameFromName("foreground")); } else if (realTarget.getType() != EndPoint.Type.IRC || !colors) { //Strip colors result = result.replaceAll( "(" + Character.toString((char) 2) + "|" + Character.toString((char) 15) + "|" + Character.toString((char) 22) + Character.toString((char) 31) + "|" + Character.toString((char) 3) + "[0-9]{0,2}(,[0-9]{0,2})?)", ""); } } return result; }
public String getMessage(EndPoint currentTarget) { String result = template; EndPoint realTarget; //Resolve target realTarget = target; if (realTarget == null) { if (currentTarget == null) return result; realTarget = currentTarget; result = plugin.cFormatting(eventType, this, realTarget); if (result == null) result = template; } //IRC color code aliases (actually not recommended) if (realTarget.getType() == EndPoint.Type.IRC) { result = result.replaceAll("%k([0-9]{1,2})%", Character.toString((char) 3) + "$1"); result = result.replaceAll("%k([0-9]{1,2}),([0-9]{1,2})%", Character.toString((char) 3) + "$1,$2"); result = result.replace("%k%", Character.toString((char) 3)); result = result.replace("%o%", Character.toString((char) 15)); result = result.replace("%b%", Character.toString((char) 2)); result = result.replace("%u%", Character.toString((char) 31)); result = result.replace("%r%", Character.toString((char) 22)); } else if (realTarget.getType() == EndPoint.Type.MINECRAFT) { result = result.replaceAll("%k([0-9]{1,2})%", ""); result = result.replaceAll("%k([0-9]{1,2}),([0-9]{1,2})%", ""); result = result.replace("%k%", plugin.cColorGameFromName("foreground")); result = result.replace("%o%", plugin.cColorGameFromName("foreground")); result = result.replace("%b%", ""); result = result.replace("%u%", ""); result = result.replace("%r%", ""); } else { result = result.replaceAll("%k([0-9]{1,2})%", ""); result = result.replaceAll("%k([0-9]{1,2}),([0-9]{1,2})%", ""); result = result.replace("%k%", ""); result = result.replace("%o%", ""); result = result.replace("%b%", ""); result = result.replace("%u%", ""); result = result.replace("%r%", ""); } //Fields and named colors (all the important stuff is here actually) Pattern other_vars = Pattern.compile("%([A-Za-z0-9]+)%"); Matcher find_vars = other_vars.matcher(result); while (find_vars.find()) { if (fields.get(find_vars.group(1)) != null) result = find_vars.replaceFirst(Matcher.quoteReplacement(fields.get(find_vars.group(1)))); else if (realTarget.getType() == EndPoint.Type.IRC) result = find_vars.replaceFirst(Character.toString((char) 3) + String.format("%02d", this.plugin.cColorIrcFromName(find_vars.group(1)))); else if (realTarget.getType() == EndPoint.Type.MINECRAFT) result = find_vars.replaceFirst(this.plugin.cColorGameFromName(find_vars.group(1))); else result = find_vars.replaceFirst(""); find_vars = other_vars.matcher(result); } //Convert colors boolean colors = plugin.cPathAttribute(fields.get("source"), fields.get("target"), "attributes.colors"); if (source.getType() == EndPoint.Type.MINECRAFT) { if (realTarget.getType() == EndPoint.Type.IRC && colors) { Pattern color_codes = Pattern.compile("\u00A7([A-Fa-f0-9])?"); Matcher find_colors = color_codes.matcher(result); while (find_colors.find()) { result = find_colors.replaceFirst("\u0003" + Integer.toString(this.plugin.cColorIrcFromGame("\u00A7" + find_colors.group(1)))); find_colors = color_codes.matcher(result); } } else if (realTarget.getType() != EndPoint.Type.MINECRAFT || !colors) { //Strip colors result = result.replaceAll("(\u00A7([A-Fa-f0-9])?)", ""); } } if (source.getType() == EndPoint.Type.IRC) { if (realTarget.getType() == EndPoint.Type.MINECRAFT && colors) { result = result.replaceAll("(" + Character.toString((char) 2) + "|" + Character.toString((char) 22) + "|" + Character.toString((char) 31) + ")", ""); Pattern color_codes = Pattern.compile(Character.toString((char) 3) + "([01]?[0-9])(,[0-9]{0,2})?"); Matcher find_colors = color_codes.matcher(result); while (find_colors.find()) { result = find_colors.replaceFirst(this.plugin.cColorGameFromIrc(Integer.parseInt(find_colors.group(1)))); find_colors = color_codes.matcher(result); } result = result.replaceAll(Character.toString((char) 15) + "|" + Character.toString((char) 3), this.plugin.cColorGameFromName("foreground")); } else if (realTarget.getType() != EndPoint.Type.IRC || !colors) { //Strip colors result = result.replaceAll( "(" + Character.toString((char) 2) + "|" + Character.toString((char) 15) + "|" + Character.toString((char) 22) + Character.toString((char) 31) + "|" + Character.toString((char) 3) + "[0-9]{0,2}(,[0-9]{0,2})?)", ""); } } return result; }
diff --git a/java/org.ejs.coffee.core/src/org/ejs/coffee/core/sound/AlsaSoundListener.java b/java/org.ejs.coffee.core/src/org/ejs/coffee/core/sound/AlsaSoundListener.java index ec70dc982..20bcc3329 100644 --- a/java/org.ejs.coffee.core/src/org/ejs/coffee/core/sound/AlsaSoundListener.java +++ b/java/org.ejs.coffee.core/src/org/ejs/coffee/core/sound/AlsaSoundListener.java @@ -1,305 +1,307 @@ package org.ejs.coffee.core.sound; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.AudioFormat.Encoding; import org.ejs.coffee.core.sound.AlsaLibrary.snd_pcm_sw_params_t; import com.sun.jna.ptr.IntByReference; import static org.ejs.coffee.core.sound.AlsaLibrary.INSTANCE; /** * ALSA sound output handler. * * This blocks on {@link #played(SoundChunk)} if data is coming too fast. * @author ejs * */ public class AlsaSoundListener implements ISoundListener { private AlsaLibrary.snd_pcm_t handle; private boolean stopped; private AudioFormat soundFormat; private Thread soundWritingThread; private BlockingQueue<AudioChunk> soundQueue; private final String device; private boolean blocking; private double volume; public AlsaSoundListener(String device) { // init outside locks AlsaLibrary.INSTANCE.hashCode(); this.device = device != null ? device : "default"; volume = 1.0; } public void setBlockMode(boolean blocking) { this.blocking = blocking; } /* (non-Javadoc) * @see org.ejs.coffee.core.sound.ISoundListener#setVolume(double) */ public void setVolume(double loudness) { this.volume = Math.max(0.0, Math.min(1.0, loudness)); } /* (non-Javadoc) * @see org.ejs.chiprocksynth.SoundListener#stopped() */ public synchronized void stopped() { stopped = true; waitUntilSilent(); if (handle != null) { INSTANCE.snd_pcm_close(handle); handle = null; } if (soundWritingThread != null) { soundWritingThread.interrupt(); try { soundWritingThread.join(); } catch (InterruptedException e) { } soundWritingThread = null; } } /* (non-Javadoc) * @see org.ejs.chiprocksynth.SoundListener#started(javax.sound.sampled.AudioFormat) */ public synchronized void started(AudioFormat format) { if (handle != null) { if (soundFormat.equals(format)) return; stopped(); } soundQueue = new LinkedBlockingQueue<AudioChunk>(20); soundFormat = format; int pcmFormat; switch (format.getSampleSizeInBits()) { case 8: if (format.getEncoding() == Encoding.PCM_UNSIGNED) pcmFormat = AlsaLibrary.SND_PCM_FORMAT_U8; else pcmFormat = AlsaLibrary.SND_PCM_FORMAT_S8; break; case 16: if (format.getEncoding() == Encoding.PCM_UNSIGNED) if (format.isBigEndian()) pcmFormat = AlsaLibrary.SND_PCM_FORMAT_U16_BE; else pcmFormat = AlsaLibrary.SND_PCM_FORMAT_U16_LE; else if (format.isBigEndian()) pcmFormat = AlsaLibrary.SND_PCM_FORMAT_S16_BE; else pcmFormat = AlsaLibrary.SND_PCM_FORMAT_S16_LE; break; default: throw new IllegalArgumentException("Cannot handle format " + format); } AlsaLibrary.snd_pcm_t.Ref pcmref = new AlsaLibrary.snd_pcm_t.Ref(); int err = AlsaLibrary.INSTANCE.snd_pcm_open( pcmref, device, AlsaLibrary.SND_PCM_STREAM_PLAYBACK, AlsaLibrary.SND_PCM_NONBLOCK); if (err < 0) { System.err.println("Error creating ALSA PCM: " + INSTANCE.snd_strerror(err)); handle = null; return; } handle = pcmref.get(); System.out.println("Sound format: " + soundFormat); /* snd_pcm_hw_params_t.Ref hwparamsRef = new snd_pcm_hw_params_t.Ref(); AlsaLibrary.INSTANCE.snd_pcm_hw_params_malloc(hwparamsRef); snd_pcm_hw_params_t hwparams = hwparamsRef.get(); if (hwparams != null) { IntByReference size = new IntByReference(); IntByReference dir = new IntByReference(); err = AlsaLibrary.INSTANCE.snd_pcm_hw_params_get_period_size(hwparams, size, dir); System.out.println("Period size: " + size.getValue() + "; err = " + err); AlsaLibrary.INSTANCE.snd_pcm_hw_params_free(hwparams); } */ int rate = format.getFrameRate() != AudioSystem.NOT_SPECIFIED ? (int) format.getFrameRate() : 48000; err = AlsaLibrary.INSTANCE.snd_pcm_set_params( handle, pcmFormat, AlsaLibrary.SND_PCM_ACCESS_RW_INTERLEAVED, format.getChannels(), rate, 1, 1000000000); if (err < 0) { System.err.println(AlsaLibrary.INSTANCE.snd_strerror(err)); System.exit(1); } snd_pcm_sw_params_t.Ref paramsRef = new snd_pcm_sw_params_t.Ref(); AlsaLibrary.INSTANCE.snd_pcm_sw_params_malloc(paramsRef); snd_pcm_sw_params_t params = paramsRef.get(); if (params != null) { if (AlsaLibrary.INSTANCE.snd_pcm_sw_params_current(handle, params) == 0) { IntByReference boundary = new IntByReference(); err = AlsaLibrary.INSTANCE.snd_pcm_sw_params_get_boundary(params, boundary); if (err == 0) { int frames = (int) (soundFormat.getSampleRate() * 0.1); //int frames = boundary.getValue() / 10; //err = AlsaLibrary.INSTANCE.snd_pcm_sw_params_set_start_threshold(handle, params, frames); //err = AlsaLibrary.INSTANCE.snd_pcm_sw_params_set_silence_threshold(handle, params, boundary.getValue()); //err = AlsaLibrary.INSTANCE.snd_pcm_sw_params_set_silence_threshold(handle, params, 0); //err = AlsaLibrary.INSTANCE.snd_pcm_sw_params_set_stop_threshold(handle, params, boundary.getValue()); err = AlsaLibrary.INSTANCE.snd_pcm_sw_params_set_avail_min(handle, params, frames); if (err == 0) { err = AlsaLibrary.INSTANCE.snd_pcm_sw_params(handle, params); } } if (err < 0) { System.err.println("Error setting up ALSA PCM: " + INSTANCE.snd_strerror(err)); } } AlsaLibrary.INSTANCE.snd_pcm_sw_params_free(params); } soundWritingThread = new Thread(new Runnable() { public void run() { while (true) { AudioChunk chunk = null; try { chunk = soundQueue.take(); } catch (InterruptedException e2) { return; } //if (chunk != null) dft(chunk.soundToWrite); // toss extra chunks if too many arrive if (false) { while (chunk != null && soundQueue.size() > 2) { chunk = soundQueue.poll(); } } if (handle == null || stopped) return; if (chunk.soundData != null) { //System.out.println("Wrt chunk " + chunk + " at " + System.currentTimeMillis()); int size = chunk.soundData.length / soundFormat.getFrameSize(); do { if (stopped) return; int err = INSTANCE.snd_pcm_writei( handle, chunk.soundData, size); if (err < 0 ) { if (err == -32) /* EPIPE */ { // underrun /*try { soundQueue.add(chunk); } catch (IllegalStateException e) { }*/ err = AlsaLibrary.INSTANCE.snd_pcm_recover(handle, err, 0); } else { err = AlsaLibrary.INSTANCE.snd_pcm_recover(handle, err, 0); } if (err == 0) continue; if (err == -11) /* EAGAIN */ { // going too fast - while (chunk != null && soundQueue.size() > 2) { - chunk = soundQueue.poll(); + if (!blocking) { + while (chunk != null && soundQueue.size() > 2) { + chunk = soundQueue.poll(); + } } try { Thread.sleep(100); } catch (InterruptedException e) { } continue; } if (err < 0) { System.err.println("snd_pcm_writei failed: " + AlsaLibrary.INSTANCE.snd_strerror(err)); err = AlsaLibrary.INSTANCE.snd_pcm_prepare(handle); err = AlsaLibrary.INSTANCE.snd_pcm_start(handle); } } break; } while (true); } } } }, "Sound Writing"); stopped = false; soundWritingThread.start(); //soundGeneratorLine.start(); //soundSamplesPerTick = soundFormat.getFrameSize() * soundFramesPerTick / 2; } /* (non-Javadoc) * @see org.ejs.chiprocksynth.SoundListener#played(org.ejs.chiprocksynth.AudioChunk) */ public synchronized void played(SoundChunk chunk) { try { if (!blocking && soundQueue.remainingCapacity() == 0) soundQueue.remove(); // will block if sound is too fast AudioChunk o = new AudioChunk(chunk, volume); soundQueue.put(o); } catch (InterruptedException e) { } } /** * */ public void waitUntilEmpty() { if (handle != null) { soundQueue.clear(); while (!soundQueue.isEmpty()) { try { Thread.sleep(100); } catch (InterruptedException e) { break; } } } } /** * */ public void waitUntilSilent() { if (handle == null) return; INSTANCE.snd_pcm_drain(handle); } }
true
true
public synchronized void started(AudioFormat format) { if (handle != null) { if (soundFormat.equals(format)) return; stopped(); } soundQueue = new LinkedBlockingQueue<AudioChunk>(20); soundFormat = format; int pcmFormat; switch (format.getSampleSizeInBits()) { case 8: if (format.getEncoding() == Encoding.PCM_UNSIGNED) pcmFormat = AlsaLibrary.SND_PCM_FORMAT_U8; else pcmFormat = AlsaLibrary.SND_PCM_FORMAT_S8; break; case 16: if (format.getEncoding() == Encoding.PCM_UNSIGNED) if (format.isBigEndian()) pcmFormat = AlsaLibrary.SND_PCM_FORMAT_U16_BE; else pcmFormat = AlsaLibrary.SND_PCM_FORMAT_U16_LE; else if (format.isBigEndian()) pcmFormat = AlsaLibrary.SND_PCM_FORMAT_S16_BE; else pcmFormat = AlsaLibrary.SND_PCM_FORMAT_S16_LE; break; default: throw new IllegalArgumentException("Cannot handle format " + format); } AlsaLibrary.snd_pcm_t.Ref pcmref = new AlsaLibrary.snd_pcm_t.Ref(); int err = AlsaLibrary.INSTANCE.snd_pcm_open( pcmref, device, AlsaLibrary.SND_PCM_STREAM_PLAYBACK, AlsaLibrary.SND_PCM_NONBLOCK); if (err < 0) { System.err.println("Error creating ALSA PCM: " + INSTANCE.snd_strerror(err)); handle = null; return; } handle = pcmref.get(); System.out.println("Sound format: " + soundFormat); /* snd_pcm_hw_params_t.Ref hwparamsRef = new snd_pcm_hw_params_t.Ref(); AlsaLibrary.INSTANCE.snd_pcm_hw_params_malloc(hwparamsRef); snd_pcm_hw_params_t hwparams = hwparamsRef.get(); if (hwparams != null) { IntByReference size = new IntByReference(); IntByReference dir = new IntByReference(); err = AlsaLibrary.INSTANCE.snd_pcm_hw_params_get_period_size(hwparams, size, dir); System.out.println("Period size: " + size.getValue() + "; err = " + err); AlsaLibrary.INSTANCE.snd_pcm_hw_params_free(hwparams); } */ int rate = format.getFrameRate() != AudioSystem.NOT_SPECIFIED ? (int) format.getFrameRate() : 48000; err = AlsaLibrary.INSTANCE.snd_pcm_set_params( handle, pcmFormat, AlsaLibrary.SND_PCM_ACCESS_RW_INTERLEAVED, format.getChannels(), rate, 1, 1000000000); if (err < 0) { System.err.println(AlsaLibrary.INSTANCE.snd_strerror(err)); System.exit(1); } snd_pcm_sw_params_t.Ref paramsRef = new snd_pcm_sw_params_t.Ref(); AlsaLibrary.INSTANCE.snd_pcm_sw_params_malloc(paramsRef); snd_pcm_sw_params_t params = paramsRef.get(); if (params != null) { if (AlsaLibrary.INSTANCE.snd_pcm_sw_params_current(handle, params) == 0) { IntByReference boundary = new IntByReference(); err = AlsaLibrary.INSTANCE.snd_pcm_sw_params_get_boundary(params, boundary); if (err == 0) { int frames = (int) (soundFormat.getSampleRate() * 0.1); //int frames = boundary.getValue() / 10; //err = AlsaLibrary.INSTANCE.snd_pcm_sw_params_set_start_threshold(handle, params, frames); //err = AlsaLibrary.INSTANCE.snd_pcm_sw_params_set_silence_threshold(handle, params, boundary.getValue()); //err = AlsaLibrary.INSTANCE.snd_pcm_sw_params_set_silence_threshold(handle, params, 0); //err = AlsaLibrary.INSTANCE.snd_pcm_sw_params_set_stop_threshold(handle, params, boundary.getValue()); err = AlsaLibrary.INSTANCE.snd_pcm_sw_params_set_avail_min(handle, params, frames); if (err == 0) { err = AlsaLibrary.INSTANCE.snd_pcm_sw_params(handle, params); } } if (err < 0) { System.err.println("Error setting up ALSA PCM: " + INSTANCE.snd_strerror(err)); } } AlsaLibrary.INSTANCE.snd_pcm_sw_params_free(params); } soundWritingThread = new Thread(new Runnable() { public void run() { while (true) { AudioChunk chunk = null; try { chunk = soundQueue.take(); } catch (InterruptedException e2) { return; } //if (chunk != null) dft(chunk.soundToWrite); // toss extra chunks if too many arrive if (false) { while (chunk != null && soundQueue.size() > 2) { chunk = soundQueue.poll(); } } if (handle == null || stopped) return; if (chunk.soundData != null) { //System.out.println("Wrt chunk " + chunk + " at " + System.currentTimeMillis()); int size = chunk.soundData.length / soundFormat.getFrameSize(); do { if (stopped) return; int err = INSTANCE.snd_pcm_writei( handle, chunk.soundData, size); if (err < 0 ) { if (err == -32) /* EPIPE */ { // underrun /*try { soundQueue.add(chunk); } catch (IllegalStateException e) { }*/ err = AlsaLibrary.INSTANCE.snd_pcm_recover(handle, err, 0); } else { err = AlsaLibrary.INSTANCE.snd_pcm_recover(handle, err, 0); } if (err == 0) continue; if (err == -11) /* EAGAIN */ { // going too fast while (chunk != null && soundQueue.size() > 2) { chunk = soundQueue.poll(); } try { Thread.sleep(100); } catch (InterruptedException e) { } continue; } if (err < 0) { System.err.println("snd_pcm_writei failed: " + AlsaLibrary.INSTANCE.snd_strerror(err)); err = AlsaLibrary.INSTANCE.snd_pcm_prepare(handle); err = AlsaLibrary.INSTANCE.snd_pcm_start(handle); } } break; } while (true); } } } }, "Sound Writing");
public synchronized void started(AudioFormat format) { if (handle != null) { if (soundFormat.equals(format)) return; stopped(); } soundQueue = new LinkedBlockingQueue<AudioChunk>(20); soundFormat = format; int pcmFormat; switch (format.getSampleSizeInBits()) { case 8: if (format.getEncoding() == Encoding.PCM_UNSIGNED) pcmFormat = AlsaLibrary.SND_PCM_FORMAT_U8; else pcmFormat = AlsaLibrary.SND_PCM_FORMAT_S8; break; case 16: if (format.getEncoding() == Encoding.PCM_UNSIGNED) if (format.isBigEndian()) pcmFormat = AlsaLibrary.SND_PCM_FORMAT_U16_BE; else pcmFormat = AlsaLibrary.SND_PCM_FORMAT_U16_LE; else if (format.isBigEndian()) pcmFormat = AlsaLibrary.SND_PCM_FORMAT_S16_BE; else pcmFormat = AlsaLibrary.SND_PCM_FORMAT_S16_LE; break; default: throw new IllegalArgumentException("Cannot handle format " + format); } AlsaLibrary.snd_pcm_t.Ref pcmref = new AlsaLibrary.snd_pcm_t.Ref(); int err = AlsaLibrary.INSTANCE.snd_pcm_open( pcmref, device, AlsaLibrary.SND_PCM_STREAM_PLAYBACK, AlsaLibrary.SND_PCM_NONBLOCK); if (err < 0) { System.err.println("Error creating ALSA PCM: " + INSTANCE.snd_strerror(err)); handle = null; return; } handle = pcmref.get(); System.out.println("Sound format: " + soundFormat); /* snd_pcm_hw_params_t.Ref hwparamsRef = new snd_pcm_hw_params_t.Ref(); AlsaLibrary.INSTANCE.snd_pcm_hw_params_malloc(hwparamsRef); snd_pcm_hw_params_t hwparams = hwparamsRef.get(); if (hwparams != null) { IntByReference size = new IntByReference(); IntByReference dir = new IntByReference(); err = AlsaLibrary.INSTANCE.snd_pcm_hw_params_get_period_size(hwparams, size, dir); System.out.println("Period size: " + size.getValue() + "; err = " + err); AlsaLibrary.INSTANCE.snd_pcm_hw_params_free(hwparams); } */ int rate = format.getFrameRate() != AudioSystem.NOT_SPECIFIED ? (int) format.getFrameRate() : 48000; err = AlsaLibrary.INSTANCE.snd_pcm_set_params( handle, pcmFormat, AlsaLibrary.SND_PCM_ACCESS_RW_INTERLEAVED, format.getChannels(), rate, 1, 1000000000); if (err < 0) { System.err.println(AlsaLibrary.INSTANCE.snd_strerror(err)); System.exit(1); } snd_pcm_sw_params_t.Ref paramsRef = new snd_pcm_sw_params_t.Ref(); AlsaLibrary.INSTANCE.snd_pcm_sw_params_malloc(paramsRef); snd_pcm_sw_params_t params = paramsRef.get(); if (params != null) { if (AlsaLibrary.INSTANCE.snd_pcm_sw_params_current(handle, params) == 0) { IntByReference boundary = new IntByReference(); err = AlsaLibrary.INSTANCE.snd_pcm_sw_params_get_boundary(params, boundary); if (err == 0) { int frames = (int) (soundFormat.getSampleRate() * 0.1); //int frames = boundary.getValue() / 10; //err = AlsaLibrary.INSTANCE.snd_pcm_sw_params_set_start_threshold(handle, params, frames); //err = AlsaLibrary.INSTANCE.snd_pcm_sw_params_set_silence_threshold(handle, params, boundary.getValue()); //err = AlsaLibrary.INSTANCE.snd_pcm_sw_params_set_silence_threshold(handle, params, 0); //err = AlsaLibrary.INSTANCE.snd_pcm_sw_params_set_stop_threshold(handle, params, boundary.getValue()); err = AlsaLibrary.INSTANCE.snd_pcm_sw_params_set_avail_min(handle, params, frames); if (err == 0) { err = AlsaLibrary.INSTANCE.snd_pcm_sw_params(handle, params); } } if (err < 0) { System.err.println("Error setting up ALSA PCM: " + INSTANCE.snd_strerror(err)); } } AlsaLibrary.INSTANCE.snd_pcm_sw_params_free(params); } soundWritingThread = new Thread(new Runnable() { public void run() { while (true) { AudioChunk chunk = null; try { chunk = soundQueue.take(); } catch (InterruptedException e2) { return; } //if (chunk != null) dft(chunk.soundToWrite); // toss extra chunks if too many arrive if (false) { while (chunk != null && soundQueue.size() > 2) { chunk = soundQueue.poll(); } } if (handle == null || stopped) return; if (chunk.soundData != null) { //System.out.println("Wrt chunk " + chunk + " at " + System.currentTimeMillis()); int size = chunk.soundData.length / soundFormat.getFrameSize(); do { if (stopped) return; int err = INSTANCE.snd_pcm_writei( handle, chunk.soundData, size); if (err < 0 ) { if (err == -32) /* EPIPE */ { // underrun /*try { soundQueue.add(chunk); } catch (IllegalStateException e) { }*/ err = AlsaLibrary.INSTANCE.snd_pcm_recover(handle, err, 0); } else { err = AlsaLibrary.INSTANCE.snd_pcm_recover(handle, err, 0); } if (err == 0) continue; if (err == -11) /* EAGAIN */ { // going too fast if (!blocking) { while (chunk != null && soundQueue.size() > 2) { chunk = soundQueue.poll(); } } try { Thread.sleep(100); } catch (InterruptedException e) { } continue; } if (err < 0) { System.err.println("snd_pcm_writei failed: " + AlsaLibrary.INSTANCE.snd_strerror(err)); err = AlsaLibrary.INSTANCE.snd_pcm_prepare(handle); err = AlsaLibrary.INSTANCE.snd_pcm_start(handle); } } break; } while (true); } } } }, "Sound Writing");
diff --git a/classpath/avian/Assembler.java b/classpath/avian/Assembler.java index 57cd605d..3e1eae27 100644 --- a/classpath/avian/Assembler.java +++ b/classpath/avian/Assembler.java @@ -1,116 +1,116 @@ /* Copyright (c) 2011, Avian Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. There is NO WARRANTY for this software. See license.txt for details. */ package avian; import static avian.Stream.write1; import static avian.Stream.write2; import static avian.Stream.write4; import avian.ConstantPool.PoolEntry; import java.util.List; import java.io.OutputStream; import java.io.IOException; public class Assembler { public static final int ACC_PUBLIC = 1 << 0; public static final int ACC_STATIC = 1 << 3; public static final int aaload = 0x32; public static final int aastore = 0x53; public static final int aload = 0x19; public static final int aload_0 = 0x2a; public static final int aload_1 = 0x2b; public static final int astore_0 = 0x4b; public static final int anewarray = 0xbd; public static final int areturn = 0xb0; public static final int dload = 0x18; public static final int dreturn = 0xaf; public static final int dup = 0x59; public static final int fload = 0x17; public static final int freturn = 0xae; public static final int getfield = 0xb4; public static final int goto_ = 0xa7; public static final int iload = 0x15; public static final int invokeinterface = 0xb9; public static final int invokespecial = 0xb7; public static final int invokestatic = 0xb8; public static final int invokevirtual = 0xb6; public static final int ireturn = 0xac; public static final int jsr = 0xa8; public static final int ldc_w = 0x13; public static final int lload = 0x16; public static final int lreturn = 0xad; public static final int new_ = 0xbb; public static final int pop = 0x57; public static final int putfield = 0xb5; public static final int ret = 0xa9; public static final int return_ = 0xb1; public static void writeClass(OutputStream out, List<PoolEntry> pool, int name, int super_, int[] interfaces, MethodData[] methods) throws IOException { int codeAttributeName = ConstantPool.addUtf8(pool, "Code"); write4(out, 0xCAFEBABE); write2(out, 0); // minor version write2(out, 0); // major version write2(out, pool.size() + 1); for (PoolEntry e: pool) { e.writeTo(out); } - write2(out, 0); // flags + write2(out, ACC_PUBLIC); // flags write2(out, name + 1); write2(out, super_ + 1); write2(out, interfaces.length); for (int i: interfaces) { write2(out, i + 1); } write2(out, 0); // field count write2(out, methods.length); for (MethodData m: methods) { write2(out, m.flags); write2(out, m.nameIndex + 1); write2(out, m.specIndex + 1); write2(out, 1); // attribute count write2(out, codeAttributeName + 1); write4(out, m.code.length); out.write(m.code); } write2(out, 0); // attribute count } public static class MethodData { public final int flags; public final int nameIndex; public final int specIndex; public final byte[] code; public MethodData(int flags, int nameIndex, int specIndex, byte[] code) { this.flags = flags; this.nameIndex = nameIndex; this.specIndex = specIndex; this.code = code; } } }
true
true
public static void writeClass(OutputStream out, List<PoolEntry> pool, int name, int super_, int[] interfaces, MethodData[] methods) throws IOException { int codeAttributeName = ConstantPool.addUtf8(pool, "Code"); write4(out, 0xCAFEBABE); write2(out, 0); // minor version write2(out, 0); // major version write2(out, pool.size() + 1); for (PoolEntry e: pool) { e.writeTo(out); } write2(out, 0); // flags write2(out, name + 1); write2(out, super_ + 1); write2(out, interfaces.length); for (int i: interfaces) { write2(out, i + 1); } write2(out, 0); // field count write2(out, methods.length); for (MethodData m: methods) { write2(out, m.flags); write2(out, m.nameIndex + 1); write2(out, m.specIndex + 1); write2(out, 1); // attribute count write2(out, codeAttributeName + 1); write4(out, m.code.length); out.write(m.code); } write2(out, 0); // attribute count }
public static void writeClass(OutputStream out, List<PoolEntry> pool, int name, int super_, int[] interfaces, MethodData[] methods) throws IOException { int codeAttributeName = ConstantPool.addUtf8(pool, "Code"); write4(out, 0xCAFEBABE); write2(out, 0); // minor version write2(out, 0); // major version write2(out, pool.size() + 1); for (PoolEntry e: pool) { e.writeTo(out); } write2(out, ACC_PUBLIC); // flags write2(out, name + 1); write2(out, super_ + 1); write2(out, interfaces.length); for (int i: interfaces) { write2(out, i + 1); } write2(out, 0); // field count write2(out, methods.length); for (MethodData m: methods) { write2(out, m.flags); write2(out, m.nameIndex + 1); write2(out, m.specIndex + 1); write2(out, 1); // attribute count write2(out, codeAttributeName + 1); write4(out, m.code.length); out.write(m.code); } write2(out, 0); // attribute count }
diff --git a/javasrc/src/org/ccnx/ccn/impl/repo/PolicyXML.java b/javasrc/src/org/ccnx/ccn/impl/repo/PolicyXML.java index a2677ecc2..80fcacaa4 100644 --- a/javasrc/src/org/ccnx/ccn/impl/repo/PolicyXML.java +++ b/javasrc/src/org/ccnx/ccn/impl/repo/PolicyXML.java @@ -1,157 +1,158 @@ package org.ccnx.ccn.impl.repo; import java.io.IOException; import java.util.ArrayList; import org.ccnx.ccn.CCNHandle; import org.ccnx.ccn.impl.encoding.GenericXMLEncodable; import org.ccnx.ccn.impl.encoding.XMLDecoder; import org.ccnx.ccn.impl.encoding.XMLEncodable; import org.ccnx.ccn.impl.encoding.XMLEncoder; import org.ccnx.ccn.impl.support.Log; import org.ccnx.ccn.io.content.CCNEncodableObject; import org.ccnx.ccn.io.content.ContentDecodingException; import org.ccnx.ccn.io.content.ContentEncodingException; import org.ccnx.ccn.io.content.ContentGoneException; import org.ccnx.ccn.io.content.ContentNotReadyException; import org.ccnx.ccn.protocol.ContentName; import org.ccnx.ccn.protocol.PublisherPublicKeyDigest; /** * Represents repo policy data */ public class PolicyXML extends GenericXMLEncodable implements XMLEncodable { public static class PolicyObject extends CCNEncodableObject<PolicyXML> { protected RepositoryStore _repo = null; // Non null if we are saving from within a repository public PolicyObject(ContentName name, PolicyXML data, CCNHandle handle, RepositoryStore repo) throws IOException { super(PolicyXML.class, true, name, data, handle); _repo = repo; } public PolicyObject(ContentName name, CCNHandle handle) throws ContentDecodingException, IOException { super(PolicyXML.class, true, name, (PublisherPublicKeyDigest)null, handle); } public PolicyXML policyXML() throws ContentNotReadyException, ContentGoneException { return data(); } protected synchronized void createFlowController() throws IOException { if (null != _repo) _flowControl = new RepositoryInternalFlowControl(_repo, _handle); super.createFlowController(); } } protected static final String POLICY_OBJECT_ELEMENT = "Policy"; private interface ElementPutter { public void put(PolicyXML pxml, String value); } private enum PolicyElement { VERSION (POLICY_VERSION, new VersionPutter()), NAMESPACE (POLICY_NAMESPACE, new NameSpacePutter()), LOCALNAME (POLICY_LOCALNAME, new LocalNamePutter()), GLOBALPREFIX (POLICY_GLOBALPREFIX, new GlobalPrefixPutter()); private String _stringValue; private ElementPutter _putter; PolicyElement(String stringValue, ElementPutter putter) { _stringValue = stringValue; _putter = putter; } } private static class VersionPutter implements ElementPutter { public void put(PolicyXML pxml, String value) { pxml._version = value.trim(); } } private static class GlobalPrefixPutter implements ElementPutter { public void put(PolicyXML pxml, String value) { pxml._globalPrefix = value.trim(); } } private static class LocalNamePutter implements ElementPutter { public void put(PolicyXML pxml, String value) { pxml._localName = value.trim(); } } private static class NameSpacePutter implements ElementPutter { public void put(PolicyXML pxml, String value) { if (null == pxml._nameSpace) pxml._nameSpace = new ArrayList<String>(); pxml._nameSpace.add(value.trim()); } } protected static final String POLICY_VERSION = "PolicyVersion"; protected static final String POLICY_NAMESPACE = "Namespace"; protected static final String POLICY_GLOBALPREFIX = "GlobalPrefix"; protected static final String POLICY_LOCALNAME = "LocalName"; protected String _version = null; protected String _globalPrefix = null; protected String _localName = null; protected ArrayList<String> _nameSpace = new ArrayList<String>(0); @Override public void decode(XMLDecoder decoder) throws ContentDecodingException { decoder.readStartElement(getElementLabel()); PolicyElement foundElement; do { foundElement = null; for (PolicyElement element : PolicyElement.values()) { if (decoder.peekStartElement(element._stringValue)) { foundElement = element; break; } } if (null != foundElement) { - foundElement._putter.put(this, decoder.readUTF8Element(foundElement._stringValue)); - Log.fine("Found policy element {0} with value {1}", foundElement._stringValue, decoder.readUTF8Element(foundElement._stringValue)); + String value = decoder.readUTF8Element(foundElement._stringValue); + foundElement._putter.put(this, value); + Log.fine("Found policy element {0} with value {1}", foundElement._stringValue, value); } } while (null != foundElement); decoder.readEndElement(); } @Override public void encode(XMLEncoder encoder) throws ContentEncodingException { if (!validate()) { throw new ContentEncodingException("Cannot encode " + this.getClass().getName() + ": field values missing."); } encoder.writeStartElement(getElementLabel()); encoder.writeElement(POLICY_VERSION, _version); encoder.writeElement(POLICY_LOCALNAME, _localName); encoder.writeElement(POLICY_GLOBALPREFIX, _globalPrefix); if (null != _nameSpace) { synchronized (_nameSpace) { for (String name : _nameSpace) encoder.writeElement(POLICY_NAMESPACE, name); } } encoder.writeEndElement(); } @Override public String getElementLabel() { return POLICY_OBJECT_ELEMENT; } @Override public boolean validate() { return null != _version; } }
true
true
public void decode(XMLDecoder decoder) throws ContentDecodingException { decoder.readStartElement(getElementLabel()); PolicyElement foundElement; do { foundElement = null; for (PolicyElement element : PolicyElement.values()) { if (decoder.peekStartElement(element._stringValue)) { foundElement = element; break; } } if (null != foundElement) { foundElement._putter.put(this, decoder.readUTF8Element(foundElement._stringValue)); Log.fine("Found policy element {0} with value {1}", foundElement._stringValue, decoder.readUTF8Element(foundElement._stringValue)); } } while (null != foundElement); decoder.readEndElement(); }
public void decode(XMLDecoder decoder) throws ContentDecodingException { decoder.readStartElement(getElementLabel()); PolicyElement foundElement; do { foundElement = null; for (PolicyElement element : PolicyElement.values()) { if (decoder.peekStartElement(element._stringValue)) { foundElement = element; break; } } if (null != foundElement) { String value = decoder.readUTF8Element(foundElement._stringValue); foundElement._putter.put(this, value); Log.fine("Found policy element {0} with value {1}", foundElement._stringValue, value); } } while (null != foundElement); decoder.readEndElement(); }
diff --git a/example/com/opower/util/powerpool/ConnectionPoolExample.java b/example/com/opower/util/powerpool/ConnectionPoolExample.java index 8175f05..48fae75 100644 --- a/example/com/opower/util/powerpool/ConnectionPoolExample.java +++ b/example/com/opower/util/powerpool/ConnectionPoolExample.java @@ -1,60 +1,60 @@ package com.opower.util.powerpool; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import org.junit.Assert; public class ConnectionPoolExample { public static void doSomethingWithDatabase(Connection connection) throws SQLException { Statement stmt = connection.createStatement(); stmt.addBatch("CREATE TABLE world (hello VARCHAR(100))"); stmt.addBatch("INSERT INTO world (hello) VALUES ('hello world')"); stmt.executeBatch(); ResultSet set = stmt.executeQuery("SELECT hello FROM world"); while (set.next()) { System.out.println(set.getString("hello")); } stmt.execute("DROP TABLE world"); } /** * @param args * @throws SQLException * @throws ClassNotFoundException */ public static void main(String[] args) throws ClassNotFoundException, SQLException { SimpleConnectionPool pool = (args != null && args.length >= 4) ? SimpleConnectionPool.createDefaultPool(args[0],args[1], args[2], args[3]) : SimpleConnectionPool.createDefaultPool("org.hsqldb.jdbc.JDBCDriver", "jdbc:hsqldb:mem:power-test", "sa", ""); - Connection connection = pool.getConnection(); + Connection connection = pool.getConnection(); // do some stuff with the connection... doSomethingWithDatabase(connection); pool.releaseConnection(connection); // or, you can call connection.close(); pool.stop(); } }
true
true
public static void main(String[] args) throws ClassNotFoundException, SQLException { SimpleConnectionPool pool = (args != null && args.length >= 4) ? SimpleConnectionPool.createDefaultPool(args[0],args[1], args[2], args[3]) : SimpleConnectionPool.createDefaultPool("org.hsqldb.jdbc.JDBCDriver", "jdbc:hsqldb:mem:power-test", "sa", ""); Connection connection = pool.getConnection(); // do some stuff with the connection... doSomethingWithDatabase(connection); pool.releaseConnection(connection); // or, you can call connection.close(); pool.stop(); }
public static void main(String[] args) throws ClassNotFoundException, SQLException { SimpleConnectionPool pool = (args != null && args.length >= 4) ? SimpleConnectionPool.createDefaultPool(args[0],args[1], args[2], args[3]) : SimpleConnectionPool.createDefaultPool("org.hsqldb.jdbc.JDBCDriver", "jdbc:hsqldb:mem:power-test", "sa", ""); Connection connection = pool.getConnection(); // do some stuff with the connection... doSomethingWithDatabase(connection); pool.releaseConnection(connection); // or, you can call connection.close(); pool.stop(); }
diff --git a/core/src/main/java/hudson/model/AbstractBuild.java b/core/src/main/java/hudson/model/AbstractBuild.java index ba981eb00..006a02c3e 100644 --- a/core/src/main/java/hudson/model/AbstractBuild.java +++ b/core/src/main/java/hudson/model/AbstractBuild.java @@ -1,786 +1,786 @@ /* * The MIT License * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi * * 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 hudson.model; import hudson.EnvVars; import hudson.Functions; import hudson.Launcher; import hudson.Util; import hudson.matrix.MatrixConfiguration; import hudson.model.Fingerprint.BuildPtr; import hudson.model.Fingerprint.RangeSet; import hudson.model.listeners.SCMListener; import hudson.scm.CVSChangeLogParser; import hudson.scm.ChangeLogParser; import hudson.scm.ChangeLogSet; import hudson.scm.ChangeLogSet.Entry; import hudson.scm.SCM; import hudson.scm.NullChangeLogParser; import hudson.tasks.BuildStep; import hudson.tasks.BuildWrapper; import hudson.tasks.Builder; import hudson.tasks.Fingerprinter.FingerprintAction; import hudson.tasks.Publisher; import hudson.tasks.test.AbstractTestResultAction; import hudson.util.AdaptedIterator; import hudson.util.Iterators; import hudson.util.VariableResolver; import org.kohsuke.stapler.Stapler; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import org.kohsuke.stapler.export.Exported; import org.xml.sax.SAXException; import javax.servlet.ServletException; import java.io.File; import java.io.IOException; import java.util.AbstractSet; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; /** * Base implementation of {@link Run}s that build software. * * For now this is primarily the common part of {@link Build} and MavenBuild. * * @author Kohsuke Kawaguchi * @see AbstractProject */ public abstract class AbstractBuild<P extends AbstractProject<P,R>,R extends AbstractBuild<P,R>> extends Run<P,R> implements Queue.Executable { /** * Name of the slave this project was built on. * Null or "" if built by the master. (null happens when we read old record that didn't have this information.) */ private String builtOn; /** * Version of Hudson that built this. */ private String hudsonVersion; /** * SCM used for this build. * Maybe null, for historical reason, in which case CVS is assumed. */ private ChangeLogParser scm; /** * Changes in this build. */ private volatile transient ChangeLogSet<? extends Entry> changeSet; /** * Cumulative list of people who contributed to the build problem. * * <p> * This is a list of {@link User#getId() user ids} who made a change * since the last non-broken build. Can be null (which should be * treated like empty set), because of the compatibility. * * <p> * This field is semi-final --- once set the value will never be modified. * * @since 1.137 */ private volatile Set<String> culprits; /** * During the build this field remembers {@link BuildWrapper.Environment}s created by * {@link BuildWrapper}. This design is bit ugly but forced due to compatibility. */ protected transient List<Environment> buildEnvironments; protected AbstractBuild(P job) throws IOException { super(job); } protected AbstractBuild(P job, Calendar timestamp) { super(job, timestamp); } protected AbstractBuild(P project, File buildDir) throws IOException { super(project, buildDir); } public final P getProject() { return getParent(); } /** * Returns a {@link Slave} on which this build was done. * * @return * null, for example if the slave that this build run no longer exists. */ public Node getBuiltOn() { if(builtOn==null || builtOn.equals("")) return Hudson.getInstance(); else return Hudson.getInstance().getNode(builtOn); } /** * Returns the name of the slave it was built on; null or "" if built by the master. * (null happens when we read old record that didn't have this information.) */ @Exported(name="builtOn") public String getBuiltOnStr() { return builtOn; } /** * Used to render the side panel "Back to project" link. * * <p> * In a rare situation where a build can be reached from multiple paths, * returning different URLs from this method based on situations might * be desirable. * * <p> * If you override this method, you'll most likely also want to override * {@link #getDisplayName()}. */ public String getUpUrl() { return Functions.getNearestAncestorUrl(Stapler.getCurrentRequest(),getParent())+'/'; } /** * List of users who committed a change since the last non-broken build till now. * * <p> * This list at least always include people who made changes in this build, but * if the previous build was a failure it also includes the culprit list from there. * * @return * can be empty but never null. */ @Exported public Set<User> getCulprits() { if(culprits==null) { Set<User> r = new HashSet<User>(); R p = getPreviousBuild(); if(p !=null && isBuilding() && p.getResult().isWorseThan(Result.UNSTABLE)) { // we are still building, so this is just the current latest information, // but we seems to be failing so far, so inherit culprits from the previous build. // isBuilding() check is to avoid recursion when loading data from old Hudson, which doesn't record // this information r.addAll(p.getCulprits()); } for( Entry e : getChangeSet() ) r.add(e.getAuthor()); return r; } return new AbstractSet<User>() { public Iterator<User> iterator() { return new AdaptedIterator<String,User>(culprits.iterator()) { protected User adapt(String id) { return User.get(id); } }; } public int size() { return culprits.size(); } }; } /** * Returns true if this user has made a commit to this build. * * @since 1.191 */ public boolean hasParticipant(User user) { for (ChangeLogSet.Entry e : getChangeSet()) if(e.getAuthor()==user) return true; return false; } /** * Gets the version of Hudson that was used to build this job. * * @since 1.246 */ public String getHudsonVersion() { return hudsonVersion; } protected abstract class AbstractRunner implements Runner { /** * Since configuration can be changed while a build is in progress, * create a launcher once and stick to it for the entire build duration. */ protected Launcher launcher; /** * Returns the current {@link Node} on which we are buildling. */ protected final Node getCurrentNode() { return Executor.currentExecutor().getOwner().getNode(); } public Result run(BuildListener listener) throws Exception { Node node = getCurrentNode(); assert builtOn==null; builtOn = node.getNodeName(); hudsonVersion = Hudson.VERSION; launcher = createLauncher(listener); if(!Hudson.getInstance().getNodes().isEmpty()) - listener.getLogger().println(Messages.AbstractBuild_BuildingRemotely(node.getNodeName())); + listener.getLogger().println(node instanceof Hudson ? Messages.AbstractBuild_BuildingOnMaster() : Messages.AbstractBuild_BuildingRemotely(builtOn)); node.getFileSystemProvisioner().prepareWorkspace(AbstractBuild.this,project.getWorkspace(),listener); if(checkout(listener)) return Result.FAILURE; if(!preBuild(listener,project.getProperties())) return Result.FAILURE; Result result = doRun(listener); // kill run-away processes that are left // use multiple environment variables so that people can escape this massacre by overriding an environment // variable for some processes launcher.kill(getCharacteristicEnvVars()); // this is ugly, but for historical reason, if non-null value is returned // it should become the final result. if(result==null) result = getResult(); if(result==null) result = Result.SUCCESS; if(result.isBetterOrEqualTo(Result.UNSTABLE)) createSymLink(listener,"lastSuccessful"); if(result.isBetterOrEqualTo(Result.SUCCESS)) createSymLink(listener,"lastStable"); return result; } /** * Creates a {@link Launcher} that this build will use. This can be overridden by derived types * to decorate the resulting {@link Launcher}. * * @param listener * Always non-null. Connected to the main build output. */ protected Launcher createLauncher(BuildListener listener) throws IOException, InterruptedException { return getCurrentNode().createLauncher(listener); } private void createSymLink(BuildListener listener, String name) throws InterruptedException { Util.createSymlink(getProject().getBuildDir(),"builds/"+getId(),"../"+name,listener); } private boolean checkout(BuildListener listener) throws Exception { // for historical reasons, null in the scm field means CVS, so we need to explicitly set this to something // in case check out fails and leaves a broken changelog.xml behind. // see http://www.nabble.com/CVSChangeLogSet.parse-yields-SAXParseExceptions-when-parsing-bad-*AccuRev*-changelog.xml-files-td22213663.html AbstractBuild.this.scm = new NullChangeLogParser(); if(!project.checkout(AbstractBuild.this,launcher,listener,new File(getRootDir(),"changelog.xml"))) return true; SCM scm = project.getScm(); AbstractBuild.this.scm = scm.createChangeLogParser(); AbstractBuild.this.changeSet = AbstractBuild.this.calcChangeSet(); for (SCMListener l : Hudson.getInstance().getSCMListeners()) l.onChangeLogParsed(AbstractBuild.this,listener,changeSet); return false; } /** * The portion of a build that is specific to a subclass of {@link AbstractBuild} * goes here. * * @return * null to continue the build normally (that means the doRun method * itself run successfully) * Return a non-null value to abort the build right there with the specified result code. */ protected abstract Result doRun(BuildListener listener) throws Exception, RunnerAbortedException; /** * @see #post(BuildListener) */ protected abstract void post2(BuildListener listener) throws Exception; public final void post(BuildListener listener) throws Exception { try { post2(listener); } finally { // update the culprit list HashSet<String> r = new HashSet<String>(); for (User u : getCulprits()) r.add(u.getId()); culprits = r; } } public void cleanUp(BuildListener listener) throws Exception { // default is no-op } protected final void performAllBuildStep(BuildListener listener, Map<?,? extends BuildStep> buildSteps, boolean phase) throws InterruptedException, IOException { performAllBuildStep(listener,buildSteps.values(),phase); } /** * Runs all the given build steps, even if one of them fail. * * @param phase * true for the post build processing, and false for the final "run after finished" execution. */ protected final void performAllBuildStep(BuildListener listener, Iterable<? extends BuildStep> buildSteps, boolean phase) throws InterruptedException, IOException { for( BuildStep bs : buildSteps ) { if( (bs instanceof Publisher && ((Publisher)bs).needsToRunAfterFinalized()) ^ phase) bs.perform(AbstractBuild.this, launcher, listener); } } protected final boolean preBuild(BuildListener listener,Map<?,? extends BuildStep> steps) { return preBuild(listener,steps.values()); } protected final boolean preBuild(BuildListener listener,Collection<? extends BuildStep> steps) { return preBuild(listener,(Iterable<? extends BuildStep>)steps); } protected final boolean preBuild(BuildListener listener,Iterable<? extends BuildStep> steps) { for( BuildStep bs : steps ) if(!bs.prebuild(AbstractBuild.this,listener)) return false; return true; } } /** * Gets the changes incorporated into this build. * * @return never null. */ @Exported public ChangeLogSet<? extends Entry> getChangeSet() { if(scm==null) scm = new CVSChangeLogParser(); if(changeSet==null) // cached value try { changeSet = calcChangeSet(); } finally { // defensive check. if the calculation fails (such as through an exception), // set a dummy value so that it'll work the next time. the exception will // be still reported, giving the plugin developer an opportunity to fix it. if(changeSet==null) changeSet=ChangeLogSet.createEmpty(this); } return changeSet; } /** * Returns true if the changelog is already computed. */ public boolean hasChangeSetComputed() { File changelogFile = new File(getRootDir(), "changelog.xml"); return changelogFile.exists(); } private ChangeLogSet<? extends Entry> calcChangeSet() { File changelogFile = new File(getRootDir(), "changelog.xml"); if(!changelogFile.exists()) return ChangeLogSet.createEmpty(this); try { return scm.parse(this,changelogFile); } catch (IOException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } return ChangeLogSet.createEmpty(this); } @Override public EnvVars getEnvironment(TaskListener log) throws IOException, InterruptedException { EnvVars env = super.getEnvironment(log); env.put("WORKSPACE", getProject().getWorkspace().getRemote()); // servlet container may have set CLASSPATH in its launch script, // so don't let that inherit to the new child process. // see http://www.nabble.com/Run-Job-with-JDK-1.4.2-tf4468601.html env.put("CLASSPATH",""); JDK jdk = project.getJDK(); if(jdk != null) { Computer computer = Computer.currentComputer(); if (computer != null) { // just in case were not in a build jdk = jdk.forNode(computer.getNode(), log); } jdk.buildEnvVars(env); } project.getScm().buildEnvVars(this,env); if(buildEnvironments!=null) for (Environment e : buildEnvironments) e.buildEnvVars(env); ParametersAction parameters = getAction(ParametersAction.class); if (parameters != null) parameters.buildEnvVars(this,env); EnvVars.resolve(env); return env; } public Calendar due() { return getTimestamp(); } /** * Provides additional variables and their values to {@link Builder}s. * * <p> * This mechanism is used by {@link MatrixConfiguration} to pass * the configuration values to the current build. It is up to * {@link Builder}s to decide whether it wants to recognize the values * or how to use them. * * <p> * This also includes build parameters if a build is parameterized. * * @return * The returned map is mutable so that subtypes can put more values. */ public Map<String,String> getBuildVariables() { Map<String,String> r = new HashMap<String, String>(); ParametersAction parameters = getAction(ParametersAction.class); if(parameters!=null) { // this is a rather round about way of doing this... for (ParameterValue p : parameters) { String v = p.createVariableResolver(this).resolve(p.getName()); if(v!=null) r.put(p.getName(),v); } } return r; } /** * Creates {@link VariableResolver} backed by {@link #getBuildVariables()}. */ public final VariableResolver<String> getBuildVariableResolver() { return new VariableResolver.ByMap<String>(getBuildVariables()); } /** * Gets {@link AbstractTestResultAction} associated with this build if any. */ public AbstractTestResultAction getTestResultAction() { return getAction(AbstractTestResultAction.class); } /** * Invoked by {@link Executor} to performs a build. */ public abstract void run(); // // // fingerprint related stuff // // @Override public String getWhyKeepLog() { // if any of the downstream project is configured with 'keep dependency component', // we need to keep this log OUTER: for (AbstractProject<?,?> p : getParent().getDownstreamProjects()) { if(!p.isKeepDependencies()) continue; AbstractBuild<?,?> fb = p.getFirstBuild(); if(fb==null) continue; // no active record // is there any active build that depends on us? for(int i : getDownstreamRelationship(p).listNumbersReverse()) { // TODO: this is essentially a "find intersection between two sparse sequences" // and we should be able to do much better. if(i<fb.getNumber()) continue OUTER; // all the other records are younger than the first record, so pointless to search. AbstractBuild<?,?> b = p.getBuildByNumber(i); if(b!=null) return Messages.AbstractBuild_KeptBecause(b); } } return super.getWhyKeepLog(); } /** * Gets the dependency relationship from this build (as the source) * and that project (as the sink.) * * @return * range of build numbers that represent which downstream builds are using this build. * The range will be empty if no build of that project matches this, but it'll never be null. */ public RangeSet getDownstreamRelationship(AbstractProject that) { RangeSet rs = new RangeSet(); FingerprintAction f = getAction(FingerprintAction.class); if(f==null) return rs; // look for fingerprints that point to this build as the source, and merge them all for (Fingerprint e : f.getFingerprints().values()) { BuildPtr o = e.getOriginal(); if(o!=null && o.is(this)) rs.add(e.getRangeSet(that)); } return rs; } /** * Works like {@link #getDownstreamRelationship(AbstractProject)} but returns * the actual build objects, in ascending order. * @since 1.150 */ public Iterable<AbstractBuild<?,?>> getDownstreamBuilds(final AbstractProject<?,?> that) { final Iterable<Integer> nums = getDownstreamRelationship(that).listNumbers(); return new Iterable<AbstractBuild<?, ?>>() { public Iterator<AbstractBuild<?, ?>> iterator() { return new Iterators.FilterIterator<AbstractBuild<?,?>>( new AdaptedIterator<Integer,AbstractBuild<?,?>>(nums) { protected AbstractBuild<?, ?> adapt(Integer item) { return that.getBuildByNumber(item); } }) { protected boolean filter(AbstractBuild<?,?> build) { return build!=null; } }; } }; } /** * Gets the dependency relationship from this build (as the sink) * and that project (as the source.) * * @return * Build number of the upstream build that feed into this build, * or -1 if no record is available. */ public int getUpstreamRelationship(AbstractProject that) { FingerprintAction f = getAction(FingerprintAction.class); if(f==null) return -1; int n = -1; // look for fingerprints that point to the given project as the source, and merge them all for (Fingerprint e : f.getFingerprints().values()) { BuildPtr o = e.getOriginal(); if(o!=null && o.belongsTo(that)) n = Math.max(n,o.getNumber()); } return n; } /** * Works like {@link #getUpstreamRelationship(AbstractProject)} but returns the * actual build object. * * @return * null if no such upstream build was found, or it was found but the * build record is already lost. */ public AbstractBuild<?,?> getUpstreamRelationshipBuild(AbstractProject<?,?> that) { int n = getUpstreamRelationship(that); if(n==-1) return null; return that.getBuildByNumber(n); } /** * Gets the downstream builds of this build, which are the builds of the * downstream projects that use artifacts of this build. * * @return * For each project with fingerprinting enabled, returns the range * of builds (which can be empty if no build uses the artifact from this build.) */ public Map<AbstractProject,RangeSet> getDownstreamBuilds() { Map<AbstractProject,RangeSet> r = new HashMap<AbstractProject,RangeSet>(); for (AbstractProject p : getParent().getDownstreamProjects()) { if(p.isFingerprintConfigured()) r.put(p,getDownstreamRelationship(p)); } return r; } /** * Gets the upstream builds of this build, which are the builds of the * upstream projects whose artifacts feed into this build. * * @see #getTransitiveUpstreamBuilds() */ public Map<AbstractProject,Integer> getUpstreamBuilds() { return _getUpstreamBuilds(getParent().getUpstreamProjects()); } /** * Works like {@link #getUpstreamBuilds()} but also includes all the transitive * dependencies as well. */ public Map<AbstractProject,Integer> getTransitiveUpstreamBuilds() { return _getUpstreamBuilds(getParent().getTransitiveUpstreamProjects()); } private Map<AbstractProject, Integer> _getUpstreamBuilds(Collection<AbstractProject> projects) { Map<AbstractProject,Integer> r = new HashMap<AbstractProject,Integer>(); for (AbstractProject p : projects) { int n = getUpstreamRelationship(p); if(n>=0) r.put(p,n); } return r; } /** * Gets the changes in the dependency between the given build and this build. */ public Map<AbstractProject,DependencyChange> getDependencyChanges(AbstractBuild from) { if(from==null) return Collections.emptyMap(); // make it easy to call this from views FingerprintAction n = this.getAction(FingerprintAction.class); FingerprintAction o = from.getAction(FingerprintAction.class); if(n==null || o==null) return Collections.emptyMap(); Map<AbstractProject,Integer> ndep = n.getDependencies(); Map<AbstractProject,Integer> odep = o.getDependencies(); Map<AbstractProject,DependencyChange> r = new HashMap<AbstractProject,DependencyChange>(); for (Map.Entry<AbstractProject,Integer> entry : odep.entrySet()) { AbstractProject p = entry.getKey(); Integer oldNumber = entry.getValue(); Integer newNumber = ndep.get(p); if(newNumber!=null && oldNumber.compareTo(newNumber)<0) { r.put(p,new DependencyChange(p,oldNumber,newNumber)); } } return r; } /** * Represents a change in the dependency. */ public static final class DependencyChange { /** * The dependency project. */ public final AbstractProject project; /** * Version of the dependency project used in the previous build. */ public final int fromId; /** * {@link Build} object for {@link #fromId}. Can be null if the log is gone. */ public final AbstractBuild from; /** * Version of the dependency project used in this build. */ public final int toId; public final AbstractBuild to; public DependencyChange(AbstractProject<?,?> project, int fromId, int toId) { this.project = project; this.fromId = fromId; this.toId = toId; this.from = project.getBuildByNumber(fromId); this.to = project.getBuildByNumber(toId); } /** * Gets the {@link AbstractBuild} objects (fromId,toId]. * <p> * This method returns all such available builds in the ascending order * of IDs, but due to log rotations, some builds may be already unavailable. */ public List<AbstractBuild> getBuilds() { List<AbstractBuild> r = new ArrayList<AbstractBuild>(); AbstractBuild<?,?> b = (AbstractBuild)project.getNearestBuild(fromId); if(b!=null && b.getNumber()==fromId) b = b.getNextBuild(); // fromId exclusive while(b!=null && b.getNumber()<=toId) { r.add(b); b = b.getNextBuild(); } return r; } } // // // web methods // // /** * Stops this build if it's still going. * * If we use this/executor/stop URL, it causes 404 if the build is already killed, * as {@link #getExecutor()} returns null. */ public synchronized void doStop( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { Executor e = getExecutor(); if(e!=null) e.doStop(req,rsp); else // nothing is building rsp.forwardToPreviousPage(req); } }
true
true
public Result run(BuildListener listener) throws Exception { Node node = getCurrentNode(); assert builtOn==null; builtOn = node.getNodeName(); hudsonVersion = Hudson.VERSION; launcher = createLauncher(listener); if(!Hudson.getInstance().getNodes().isEmpty()) listener.getLogger().println(Messages.AbstractBuild_BuildingRemotely(node.getNodeName())); node.getFileSystemProvisioner().prepareWorkspace(AbstractBuild.this,project.getWorkspace(),listener); if(checkout(listener)) return Result.FAILURE; if(!preBuild(listener,project.getProperties())) return Result.FAILURE; Result result = doRun(listener); // kill run-away processes that are left // use multiple environment variables so that people can escape this massacre by overriding an environment // variable for some processes launcher.kill(getCharacteristicEnvVars()); // this is ugly, but for historical reason, if non-null value is returned // it should become the final result. if(result==null) result = getResult(); if(result==null) result = Result.SUCCESS; if(result.isBetterOrEqualTo(Result.UNSTABLE)) createSymLink(listener,"lastSuccessful"); if(result.isBetterOrEqualTo(Result.SUCCESS)) createSymLink(listener,"lastStable"); return result; }
public Result run(BuildListener listener) throws Exception { Node node = getCurrentNode(); assert builtOn==null; builtOn = node.getNodeName(); hudsonVersion = Hudson.VERSION; launcher = createLauncher(listener); if(!Hudson.getInstance().getNodes().isEmpty()) listener.getLogger().println(node instanceof Hudson ? Messages.AbstractBuild_BuildingOnMaster() : Messages.AbstractBuild_BuildingRemotely(builtOn)); node.getFileSystemProvisioner().prepareWorkspace(AbstractBuild.this,project.getWorkspace(),listener); if(checkout(listener)) return Result.FAILURE; if(!preBuild(listener,project.getProperties())) return Result.FAILURE; Result result = doRun(listener); // kill run-away processes that are left // use multiple environment variables so that people can escape this massacre by overriding an environment // variable for some processes launcher.kill(getCharacteristicEnvVars()); // this is ugly, but for historical reason, if non-null value is returned // it should become the final result. if(result==null) result = getResult(); if(result==null) result = Result.SUCCESS; if(result.isBetterOrEqualTo(Result.UNSTABLE)) createSymLink(listener,"lastSuccessful"); if(result.isBetterOrEqualTo(Result.SUCCESS)) createSymLink(listener,"lastStable"); return result; }
diff --git a/lucene/src/test/org/apache/lucene/search/TestWildcard.java b/lucene/src/test/org/apache/lucene/search/TestWildcard.java index 56e2825e6..22f4cc52c 100644 --- a/lucene/src/test/org/apache/lucene/search/TestWildcard.java +++ b/lucene/src/test/org/apache/lucene/search/TestWildcard.java @@ -1,358 +1,360 @@ package org.apache.lucene.search; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.apache.lucene.store.Directory; import org.apache.lucene.util.LuceneTestCase; import org.apache.lucene.analysis.MockAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.Field.Store; import org.apache.lucene.document.Field.Index; import org.apache.lucene.index.MultiFields; import org.apache.lucene.index.RandomIndexWriter; import org.apache.lucene.index.Term; import org.apache.lucene.index.Terms; import org.apache.lucene.queryParser.QueryParser; import java.io.IOException; /** * TestWildcard tests the '*' and '?' wildcard characters. */ public class TestWildcard extends LuceneTestCase { @Override public void setUp() throws Exception { super.setUp(); } public void testEquals() { WildcardQuery wq1 = new WildcardQuery(new Term("field", "b*a")); WildcardQuery wq2 = new WildcardQuery(new Term("field", "b*a")); WildcardQuery wq3 = new WildcardQuery(new Term("field", "b*a")); // reflexive? assertEquals(wq1, wq2); assertEquals(wq2, wq1); // transitive? assertEquals(wq2, wq3); assertEquals(wq1, wq3); assertFalse(wq1.equals(null)); FuzzyQuery fq = new FuzzyQuery(new Term("field", "b*a")); assertFalse(wq1.equals(fq)); assertFalse(fq.equals(wq1)); } /** * Tests if a WildcardQuery that has no wildcard in the term is rewritten to a single * TermQuery. The boost should be preserved, and the rewrite should return * a ConstantScoreQuery if the WildcardQuery had a ConstantScore rewriteMethod. */ public void testTermWithoutWildcard() throws IOException { Directory indexStore = getIndexStore("field", new String[]{"nowildcard", "nowildcardx"}); IndexSearcher searcher = new IndexSearcher(indexStore, true); MultiTermQuery wq = new WildcardQuery(new Term("field", "nowildcard")); assertMatches(searcher, wq, 1); wq.setRewriteMethod(MultiTermQuery.SCORING_BOOLEAN_QUERY_REWRITE); wq.setBoost(0.1F); Query q = searcher.rewrite(wq); assertTrue(q instanceof TermQuery); assertEquals(q.getBoost(), wq.getBoost()); wq.setRewriteMethod(MultiTermQuery.CONSTANT_SCORE_FILTER_REWRITE); wq.setBoost(0.2F); q = searcher.rewrite(wq); assertTrue(q instanceof ConstantScoreQuery); assertEquals(q.getBoost(), wq.getBoost()); wq.setRewriteMethod(MultiTermQuery.CONSTANT_SCORE_AUTO_REWRITE_DEFAULT); wq.setBoost(0.3F); q = searcher.rewrite(wq); assertTrue(q instanceof ConstantScoreQuery); assertEquals(q.getBoost(), wq.getBoost()); wq.setRewriteMethod(MultiTermQuery.CONSTANT_SCORE_BOOLEAN_QUERY_REWRITE); wq.setBoost(0.4F); q = searcher.rewrite(wq); assertTrue(q instanceof ConstantScoreQuery); assertEquals(q.getBoost(), wq.getBoost()); searcher.close(); indexStore.close(); } /** * Tests if a WildcardQuery with an empty term is rewritten to an empty BooleanQuery */ public void testEmptyTerm() throws IOException { Directory indexStore = getIndexStore("field", new String[]{"nowildcard", "nowildcardx"}); IndexSearcher searcher = new IndexSearcher(indexStore, true); MultiTermQuery wq = new WildcardQuery(new Term("field", "")); wq.setRewriteMethod(MultiTermQuery.SCORING_BOOLEAN_QUERY_REWRITE); assertMatches(searcher, wq, 0); Query q = searcher.rewrite(wq); assertTrue(q instanceof BooleanQuery); assertEquals(0, ((BooleanQuery) q).clauses().size()); searcher.close(); indexStore.close(); } /** * Tests if a WildcardQuery that has only a trailing * in the term is * rewritten to a single PrefixQuery. The boost and rewriteMethod should be * preserved. */ public void testPrefixTerm() throws IOException { Directory indexStore = getIndexStore("field", new String[]{"prefix", "prefixx"}); IndexSearcher searcher = new IndexSearcher(indexStore, true); MultiTermQuery wq = new WildcardQuery(new Term("field", "prefix*")); assertMatches(searcher, wq, 2); Terms terms = MultiFields.getTerms(searcher.getIndexReader(), "field"); assertTrue(wq.getTermsEnum(terms) instanceof PrefixTermsEnum); wq = new WildcardQuery(new Term("field", "*")); assertMatches(searcher, wq, 2); assertFalse(wq.getTermsEnum(terms) instanceof PrefixTermsEnum); assertFalse(wq.getTermsEnum(terms) instanceof AutomatonTermsEnum); searcher.close(); indexStore.close(); } /** * Tests Wildcard queries with an asterisk. */ public void testAsterisk() throws IOException { Directory indexStore = getIndexStore("body", new String[] {"metal", "metals"}); IndexSearcher searcher = new IndexSearcher(indexStore, true); Query query1 = new TermQuery(new Term("body", "metal")); Query query2 = new WildcardQuery(new Term("body", "metal*")); Query query3 = new WildcardQuery(new Term("body", "m*tal")); Query query4 = new WildcardQuery(new Term("body", "m*tal*")); Query query5 = new WildcardQuery(new Term("body", "m*tals")); BooleanQuery query6 = new BooleanQuery(); query6.add(query5, BooleanClause.Occur.SHOULD); BooleanQuery query7 = new BooleanQuery(); query7.add(query3, BooleanClause.Occur.SHOULD); query7.add(query5, BooleanClause.Occur.SHOULD); // Queries do not automatically lower-case search terms: Query query8 = new WildcardQuery(new Term("body", "M*tal*")); assertMatches(searcher, query1, 1); assertMatches(searcher, query2, 2); assertMatches(searcher, query3, 1); assertMatches(searcher, query4, 2); assertMatches(searcher, query5, 1); assertMatches(searcher, query6, 1); assertMatches(searcher, query7, 2); assertMatches(searcher, query8, 0); assertMatches(searcher, new WildcardQuery(new Term("body", "*tall")), 0); assertMatches(searcher, new WildcardQuery(new Term("body", "*tal")), 1); assertMatches(searcher, new WildcardQuery(new Term("body", "*tal*")), 2); searcher.close(); indexStore.close(); } /** * Tests Wildcard queries with a question mark. * * @throws IOException if an error occurs */ public void testQuestionmark() throws IOException { Directory indexStore = getIndexStore("body", new String[] {"metal", "metals", "mXtals", "mXtXls"}); IndexSearcher searcher = new IndexSearcher(indexStore, true); Query query1 = new WildcardQuery(new Term("body", "m?tal")); Query query2 = new WildcardQuery(new Term("body", "metal?")); Query query3 = new WildcardQuery(new Term("body", "metals?")); Query query4 = new WildcardQuery(new Term("body", "m?t?ls")); Query query5 = new WildcardQuery(new Term("body", "M?t?ls")); Query query6 = new WildcardQuery(new Term("body", "meta??")); assertMatches(searcher, query1, 1); assertMatches(searcher, query2, 1); assertMatches(searcher, query3, 0); assertMatches(searcher, query4, 3); assertMatches(searcher, query5, 0); assertMatches(searcher, query6, 1); // Query: 'meta??' matches 'metals' not 'metal' searcher.close(); indexStore.close(); } /** * Tests if wildcard escaping works */ public void testEscapes() throws Exception { Directory indexStore = getIndexStore("field", new String[]{"foo*bar", "foo??bar", "fooCDbar", "fooSOMETHINGbar", "foo\\"}); IndexSearcher searcher = new IndexSearcher(indexStore, true); // without escape: matches foo??bar, fooCDbar, foo*bar, and fooSOMETHINGbar WildcardQuery unescaped = new WildcardQuery(new Term("field", "foo*bar")); assertMatches(searcher, unescaped, 4); // with escape: only matches foo*bar WildcardQuery escaped = new WildcardQuery(new Term("field", "foo\\*bar")); assertMatches(searcher, escaped, 1); // without escape: matches foo??bar and fooCDbar unescaped = new WildcardQuery(new Term("field", "foo??bar")); assertMatches(searcher, unescaped, 2); // with escape: matches foo??bar only escaped = new WildcardQuery(new Term("field", "foo\\?\\?bar")); assertMatches(searcher, escaped, 1); // check escaping at end: lenient parse yields "foo\" WildcardQuery atEnd = new WildcardQuery(new Term("field", "foo\\")); assertMatches(searcher, atEnd, 1); searcher.close(); indexStore.close(); } private Directory getIndexStore(String field, String[] contents) throws IOException { Directory indexStore = newDirectory(); RandomIndexWriter writer = new RandomIndexWriter(random, indexStore); for (int i = 0; i < contents.length; ++i) { Document doc = new Document(); doc.add(newField(field, contents[i], Field.Store.YES, Field.Index.ANALYZED)); writer.addDocument(doc); } writer.close(); return indexStore; } private void assertMatches(IndexSearcher searcher, Query q, int expectedMatches) throws IOException { ScoreDoc[] result = searcher.search(q, null, 1000).scoreDocs; assertEquals(expectedMatches, result.length); } /** * Test that wild card queries are parsed to the correct type and are searched correctly. * This test looks at both parsing and execution of wildcard queries. * Although placed here, it also tests prefix queries, verifying that * prefix queries are not parsed into wild card queries, and viceversa. * @throws Exception */ public void testParsingAndSearching() throws Exception { String field = "content"; QueryParser qp = new QueryParser(TEST_VERSION_CURRENT, field, new MockAnalyzer()); qp.setAllowLeadingWildcard(true); String docs[] = { "\\ abcdefg1", "\\79 hijklmn1", "\\\\ opqrstu1", }; // queries that should find all docs String matchAll[] = { "*", "*1", "**1", "*?", "*?1", "?*1", "**", "***", "\\\\*" }; // queries that should find no docs String matchNone[] = { "a*h", "a?h", "*a*h", "?a", "a?", }; // queries that should be parsed to prefix queries String matchOneDocPrefix[][] = { {"a*", "ab*", "abc*", }, // these should find only doc 0 {"h*", "hi*", "hij*", "\\\\7*"}, // these should find only doc 1 {"o*", "op*", "opq*", "\\\\\\\\*"}, // these should find only doc 2 }; // queries that should be parsed to wildcard queries String matchOneDocWild[][] = { {"*a*", "*ab*", "*abc**", "ab*e*", "*g?", "*f?1", "abc**"}, // these should find only doc 0 {"*h*", "*hi*", "*hij**", "hi*k*", "*n?", "*m?1", "hij**"}, // these should find only doc 1 {"*o*", "*op*", "*opq**", "op*q*", "*u?", "*t?1", "opq**"}, // these should find only doc 2 }; // prepare the index Directory dir = newDirectory(); - RandomIndexWriter iw = new RandomIndexWriter(random, dir); + RandomIndexWriter iw = new RandomIndexWriter(random, dir, + newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()) + .setMergePolicy(newInOrderLogMergePolicy())); for (int i = 0; i < docs.length; i++) { Document doc = new Document(); doc.add(newField(field,docs[i],Store.NO,Index.ANALYZED)); iw.addDocument(doc); } iw.close(); IndexSearcher searcher = new IndexSearcher(dir, true); // test queries that must find all for (int i = 0; i < matchAll.length; i++) { String qtxt = matchAll[i]; Query q = qp.parse(qtxt); if (VERBOSE) System.out.println("matchAll: qtxt="+qtxt+" q="+q+" "+q.getClass().getName()); ScoreDoc[] hits = searcher.search(q, null, 1000).scoreDocs; assertEquals(docs.length,hits.length); } // test queries that must find none for (int i = 0; i < matchNone.length; i++) { String qtxt = matchNone[i]; Query q = qp.parse(qtxt); if (VERBOSE) System.out.println("matchNone: qtxt="+qtxt+" q="+q+" "+q.getClass().getName()); ScoreDoc[] hits = searcher.search(q, null, 1000).scoreDocs; assertEquals(0,hits.length); } // test queries that must be prefix queries and must find only one doc for (int i = 0; i < matchOneDocPrefix.length; i++) { for (int j = 0; j < matchOneDocPrefix[i].length; j++) { String qtxt = matchOneDocPrefix[i][j]; Query q = qp.parse(qtxt); if (VERBOSE) System.out.println("match 1 prefix: doc="+docs[i]+" qtxt="+qtxt+" q="+q+" "+q.getClass().getName()); assertEquals(PrefixQuery.class, q.getClass()); ScoreDoc[] hits = searcher.search(q, null, 1000).scoreDocs; assertEquals(1,hits.length); assertEquals(i,hits[0].doc); } } // test queries that must be wildcard queries and must find only one doc for (int i = 0; i < matchOneDocPrefix.length; i++) { for (int j = 0; j < matchOneDocWild[i].length; j++) { String qtxt = matchOneDocWild[i][j]; Query q = qp.parse(qtxt); if (VERBOSE) System.out.println("match 1 wild: doc="+docs[i]+" qtxt="+qtxt+" q="+q+" "+q.getClass().getName()); assertEquals(WildcardQuery.class, q.getClass()); ScoreDoc[] hits = searcher.search(q, null, 1000).scoreDocs; assertEquals(1,hits.length); assertEquals(i,hits[0].doc); } } searcher.close(); dir.close(); } }
true
true
public void testParsingAndSearching() throws Exception { String field = "content"; QueryParser qp = new QueryParser(TEST_VERSION_CURRENT, field, new MockAnalyzer()); qp.setAllowLeadingWildcard(true); String docs[] = { "\\ abcdefg1", "\\79 hijklmn1", "\\\\ opqrstu1", }; // queries that should find all docs String matchAll[] = { "*", "*1", "**1", "*?", "*?1", "?*1", "**", "***", "\\\\*" }; // queries that should find no docs String matchNone[] = { "a*h", "a?h", "*a*h", "?a", "a?", }; // queries that should be parsed to prefix queries String matchOneDocPrefix[][] = { {"a*", "ab*", "abc*", }, // these should find only doc 0 {"h*", "hi*", "hij*", "\\\\7*"}, // these should find only doc 1 {"o*", "op*", "opq*", "\\\\\\\\*"}, // these should find only doc 2 }; // queries that should be parsed to wildcard queries String matchOneDocWild[][] = { {"*a*", "*ab*", "*abc**", "ab*e*", "*g?", "*f?1", "abc**"}, // these should find only doc 0 {"*h*", "*hi*", "*hij**", "hi*k*", "*n?", "*m?1", "hij**"}, // these should find only doc 1 {"*o*", "*op*", "*opq**", "op*q*", "*u?", "*t?1", "opq**"}, // these should find only doc 2 }; // prepare the index Directory dir = newDirectory(); RandomIndexWriter iw = new RandomIndexWriter(random, dir); for (int i = 0; i < docs.length; i++) { Document doc = new Document(); doc.add(newField(field,docs[i],Store.NO,Index.ANALYZED)); iw.addDocument(doc); } iw.close(); IndexSearcher searcher = new IndexSearcher(dir, true); // test queries that must find all for (int i = 0; i < matchAll.length; i++) { String qtxt = matchAll[i]; Query q = qp.parse(qtxt); if (VERBOSE) System.out.println("matchAll: qtxt="+qtxt+" q="+q+" "+q.getClass().getName()); ScoreDoc[] hits = searcher.search(q, null, 1000).scoreDocs; assertEquals(docs.length,hits.length); } // test queries that must find none for (int i = 0; i < matchNone.length; i++) { String qtxt = matchNone[i]; Query q = qp.parse(qtxt); if (VERBOSE) System.out.println("matchNone: qtxt="+qtxt+" q="+q+" "+q.getClass().getName()); ScoreDoc[] hits = searcher.search(q, null, 1000).scoreDocs; assertEquals(0,hits.length); } // test queries that must be prefix queries and must find only one doc for (int i = 0; i < matchOneDocPrefix.length; i++) { for (int j = 0; j < matchOneDocPrefix[i].length; j++) { String qtxt = matchOneDocPrefix[i][j]; Query q = qp.parse(qtxt); if (VERBOSE) System.out.println("match 1 prefix: doc="+docs[i]+" qtxt="+qtxt+" q="+q+" "+q.getClass().getName()); assertEquals(PrefixQuery.class, q.getClass()); ScoreDoc[] hits = searcher.search(q, null, 1000).scoreDocs; assertEquals(1,hits.length); assertEquals(i,hits[0].doc); } } // test queries that must be wildcard queries and must find only one doc for (int i = 0; i < matchOneDocPrefix.length; i++) { for (int j = 0; j < matchOneDocWild[i].length; j++) { String qtxt = matchOneDocWild[i][j]; Query q = qp.parse(qtxt); if (VERBOSE) System.out.println("match 1 wild: doc="+docs[i]+" qtxt="+qtxt+" q="+q+" "+q.getClass().getName()); assertEquals(WildcardQuery.class, q.getClass()); ScoreDoc[] hits = searcher.search(q, null, 1000).scoreDocs; assertEquals(1,hits.length); assertEquals(i,hits[0].doc); } } searcher.close(); dir.close(); }
public void testParsingAndSearching() throws Exception { String field = "content"; QueryParser qp = new QueryParser(TEST_VERSION_CURRENT, field, new MockAnalyzer()); qp.setAllowLeadingWildcard(true); String docs[] = { "\\ abcdefg1", "\\79 hijklmn1", "\\\\ opqrstu1", }; // queries that should find all docs String matchAll[] = { "*", "*1", "**1", "*?", "*?1", "?*1", "**", "***", "\\\\*" }; // queries that should find no docs String matchNone[] = { "a*h", "a?h", "*a*h", "?a", "a?", }; // queries that should be parsed to prefix queries String matchOneDocPrefix[][] = { {"a*", "ab*", "abc*", }, // these should find only doc 0 {"h*", "hi*", "hij*", "\\\\7*"}, // these should find only doc 1 {"o*", "op*", "opq*", "\\\\\\\\*"}, // these should find only doc 2 }; // queries that should be parsed to wildcard queries String matchOneDocWild[][] = { {"*a*", "*ab*", "*abc**", "ab*e*", "*g?", "*f?1", "abc**"}, // these should find only doc 0 {"*h*", "*hi*", "*hij**", "hi*k*", "*n?", "*m?1", "hij**"}, // these should find only doc 1 {"*o*", "*op*", "*opq**", "op*q*", "*u?", "*t?1", "opq**"}, // these should find only doc 2 }; // prepare the index Directory dir = newDirectory(); RandomIndexWriter iw = new RandomIndexWriter(random, dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()) .setMergePolicy(newInOrderLogMergePolicy())); for (int i = 0; i < docs.length; i++) { Document doc = new Document(); doc.add(newField(field,docs[i],Store.NO,Index.ANALYZED)); iw.addDocument(doc); } iw.close(); IndexSearcher searcher = new IndexSearcher(dir, true); // test queries that must find all for (int i = 0; i < matchAll.length; i++) { String qtxt = matchAll[i]; Query q = qp.parse(qtxt); if (VERBOSE) System.out.println("matchAll: qtxt="+qtxt+" q="+q+" "+q.getClass().getName()); ScoreDoc[] hits = searcher.search(q, null, 1000).scoreDocs; assertEquals(docs.length,hits.length); } // test queries that must find none for (int i = 0; i < matchNone.length; i++) { String qtxt = matchNone[i]; Query q = qp.parse(qtxt); if (VERBOSE) System.out.println("matchNone: qtxt="+qtxt+" q="+q+" "+q.getClass().getName()); ScoreDoc[] hits = searcher.search(q, null, 1000).scoreDocs; assertEquals(0,hits.length); } // test queries that must be prefix queries and must find only one doc for (int i = 0; i < matchOneDocPrefix.length; i++) { for (int j = 0; j < matchOneDocPrefix[i].length; j++) { String qtxt = matchOneDocPrefix[i][j]; Query q = qp.parse(qtxt); if (VERBOSE) System.out.println("match 1 prefix: doc="+docs[i]+" qtxt="+qtxt+" q="+q+" "+q.getClass().getName()); assertEquals(PrefixQuery.class, q.getClass()); ScoreDoc[] hits = searcher.search(q, null, 1000).scoreDocs; assertEquals(1,hits.length); assertEquals(i,hits[0].doc); } } // test queries that must be wildcard queries and must find only one doc for (int i = 0; i < matchOneDocPrefix.length; i++) { for (int j = 0; j < matchOneDocWild[i].length; j++) { String qtxt = matchOneDocWild[i][j]; Query q = qp.parse(qtxt); if (VERBOSE) System.out.println("match 1 wild: doc="+docs[i]+" qtxt="+qtxt+" q="+q+" "+q.getClass().getName()); assertEquals(WildcardQuery.class, q.getClass()); ScoreDoc[] hits = searcher.search(q, null, 1000).scoreDocs; assertEquals(1,hits.length); assertEquals(i,hits[0].doc); } } searcher.close(); dir.close(); }
diff --git a/SimpleClans2/src/main/java/com/p000ison/dev/simpleclans2/util/GeneralHelper.java b/SimpleClans2/src/main/java/com/p000ison/dev/simpleclans2/util/GeneralHelper.java index a8d6712..869bc90 100644 --- a/SimpleClans2/src/main/java/com/p000ison/dev/simpleclans2/util/GeneralHelper.java +++ b/SimpleClans2/src/main/java/com/p000ison/dev/simpleclans2/util/GeneralHelper.java @@ -1,238 +1,238 @@ /* * This file is part of SimpleClans2 (2012). * * SimpleClans2 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. * * SimpleClans2 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 SimpleClans2. If not, see <http://www.gnu.org/licenses/>. * * Last modified: 10.10.12 21:57 */ package com.p000ison.dev.simpleclans2.util; import com.p000ison.dev.simpleclans2.api.clan.Clan; import com.p000ison.dev.simpleclans2.api.clanplayer.ClanPlayer; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.entity.Player; import java.io.File; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Represents a GeneralHelper */ public final class GeneralHelper { private GeneralHelper() { } public static String arrayToString(String... args) { return arrayToString(" ", args); } public static String arrayToString(String seperator, String... args) { if (args == null || args.length == 0) { return null; } StringBuilder out = new StringBuilder(); for (Object string : args) { out.append(string).append(seperator); } return out.substring(0, out.length() - seperator.length()); } public static String arrayToString(String seperator, Collection collection) { if (collection == null || collection.isEmpty()) { return null; } StringBuilder out = new StringBuilder(); for (Object string : collection) { out.append(string.toString()).append(seperator); } return out.substring(0, out.length() - seperator.length()); } public static boolean isValidEmailAddress(String emailAddress) { if (emailAddress == null) { return false; } String expression = "^[\\w\\-]([\\.\\w\\-])+[\\w]+@([\\w\\-]+\\.)+[A-Z]{2,4}$"; Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(emailAddress); return matcher.matches(); } public static boolean isOnline(Player player) { if (player == null) { return false; } for (Player players : Bukkit.getOnlinePlayers()) { if (!players.canSee(player)) { return false; } } return true; } public static String arrayToString(char... args) { return arrayToString(" ", args); } public static String arrayToString(String seperator, char... args) { StringBuilder string = new StringBuilder(); for (char color : args) { string.append(ChatColor.getByChar(color).name().toLowerCase(Locale.US)).append(seperator); } return string.substring(0, string.length() - seperator.length()); } public static Set<ClanPlayer> stripOfflinePlayers(Set<ClanPlayer> players) { Set<ClanPlayer> out = new HashSet<ClanPlayer>(); for (ClanPlayer clanPlayer : players) { if (clanPlayer.toPlayer() != null) { out.add(clanPlayer); } } return out; } public static String clansToString(Collection<Clan> collection, String separator) { if (collection == null || collection.isEmpty()) { return null; } StringBuilder string = new StringBuilder(); for (Clan clan : collection) { string.append(clan.getTag()).append(separator); } return string.substring(0, string.length() - separator.length()); } public static String clansPlayersToString(Collection<ClanPlayer> collection, String separator) { if (collection == null || collection.isEmpty()) { return null; } StringBuilder string = new StringBuilder(); for (ClanPlayer cp : collection) { string.append(cp.getName()).append(separator); } return string.substring(0, string.length() - separator.length()); } public static String arrayBoundsToString(int start, int end, String... args) { return arrayToString(Arrays.copyOfRange(args, start, end)); } public static String arrayBoundsToString(int start, String... args) { return arrayToString(Arrays.copyOfRange(args, start, args.length)); } public static boolean containsColor(String test, char alternateChar, Character color) { return test.contains(alternateChar + String.valueOf(color)); } public static boolean containsColor(String test, char alternateChar, char... colors) { for (char color : colors) { if (containsColor(test, alternateChar, color)) { return true; } } return false; } public static boolean containsColor(String test, char alternateChar, ChatColor... colors) { for (ChatColor color : colors) { if (!containsColor(test, alternateChar, color.getChar())) { return false; } } return true; } public static String locationToString(Location loc) { return loc.getBlockX() + " " + loc.getBlockY() + " " + loc.getBlockZ() + " " + loc.getWorld().getName(); } public static boolean checkConnection(String url) { try { URL Url = new URL(url); HttpURLConnection urlConn = (HttpURLConnection) Url.openConnection(); urlConn.connect(); if (urlConn.getResponseCode() != HttpURLConnection.HTTP_OK) { return false; } } catch (IOException e) { return false; } return true; } public static boolean deleteWorld(World world) { return Bukkit.unloadWorld(world, false) && deleteDir(world.getWorldFolder()); } public static boolean deleteDir(File path) { if (path == null || !path.isDirectory()) { return false; } File[] files = path.listFiles(); - for (File file : path.listFiles()) { + for (File file : files) { if (file.isDirectory()) { deleteDir(file); } if (!file.delete()) { return false; } } return path.delete(); } }
true
true
public static boolean deleteDir(File path) { if (path == null || !path.isDirectory()) { return false; } File[] files = path.listFiles(); for (File file : path.listFiles()) { if (file.isDirectory()) { deleteDir(file); } if (!file.delete()) { return false; } } return path.delete(); }
public static boolean deleteDir(File path) { if (path == null || !path.isDirectory()) { return false; } File[] files = path.listFiles(); for (File file : files) { if (file.isDirectory()) { deleteDir(file); } if (!file.delete()) { return false; } } return path.delete(); }
diff --git a/src/twosnakes/TitleScreen.java b/src/twosnakes/TitleScreen.java index 13735c4..91a62d5 100644 --- a/src/twosnakes/TitleScreen.java +++ b/src/twosnakes/TitleScreen.java @@ -1,91 +1,91 @@ package twosnakes; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.*; import java.awt.event.*; import java.awt.image.*; import java.io.*; import java.lang.Math; import javax.imageio.*; import javax.swing.*; import javax.swing.JFrame; import java.awt.geom.AffineTransform; public class TitleScreen { public final int SPACING = 65; public final int XSTEP = 15; public final String filenames[] = {"s", "n", "a", "K", "e", "s", "space", "o", "n", "space", "a", "space", "s", "c", "r", "e", "e", "n"}; private int x[]; private int actualX[]; private int y[]; BufferedImage[] images; BufferedImage backgroundImage; public TitleScreen() { images = new BufferedImage[filenames.length]; for (int i = 0; i < filenames.length; i++) { try { - images[i] = ImageIO.read(new File("Images\\" + filenames[i] + ".png")); + images[i] = ImageIO.read(new File("images/" + filenames[i] + ".png")); } catch (IOException e1) { e1.printStackTrace(); } } try { - backgroundImage = ImageIO.read(new File("Images\\T_background.png")); + backgroundImage = ImageIO.read(new File("images/T_background.png")); } catch (IOException e2) { e2.printStackTrace(); backgroundImage = null; } x = new int[filenames.length]; actualX = new int[filenames.length]; y = new int[filenames.length]; for (int i = 0; i < filenames.length; i++) { x[i] = (i * SPACING) - (filenames.length * SPACING); actualX[i] = (i * SPACING) - (filenames.length * SPACING); } int[] y = new int[filenames.length]; } public void step() { for (int i = 0; i < filenames.length; i++) { x[i] += XSTEP; if (actualX[filenames.length / 2] < 1280 / 2) { actualX[i] += XSTEP; } y[i] = (int)(Math.sin((double)x[i] / (double)60) * 33) + 150; } } public void draw(Graphics g) { Graphics2D g2d = (Graphics2D)g; g2d.drawImage(backgroundImage, 0, 0, null); for (int i = 0; i < filenames.length; i++) { AffineTransform trans = new AffineTransform(); trans.translate(actualX[i], y[i]); trans.rotate(Math.cos((double)x[i] / (double)60) / 1.75, images[i].getWidth() / 2, images[i].getHeight() / 2); g2d.drawImage(images[i], trans, null); } } }
false
true
public TitleScreen() { images = new BufferedImage[filenames.length]; for (int i = 0; i < filenames.length; i++) { try { images[i] = ImageIO.read(new File("Images\\" + filenames[i] + ".png")); } catch (IOException e1) { e1.printStackTrace(); } } try { backgroundImage = ImageIO.read(new File("Images\\T_background.png")); } catch (IOException e2) { e2.printStackTrace(); backgroundImage = null; } x = new int[filenames.length]; actualX = new int[filenames.length]; y = new int[filenames.length]; for (int i = 0; i < filenames.length; i++) { x[i] = (i * SPACING) - (filenames.length * SPACING); actualX[i] = (i * SPACING) - (filenames.length * SPACING); } int[] y = new int[filenames.length]; }
public TitleScreen() { images = new BufferedImage[filenames.length]; for (int i = 0; i < filenames.length; i++) { try { images[i] = ImageIO.read(new File("images/" + filenames[i] + ".png")); } catch (IOException e1) { e1.printStackTrace(); } } try { backgroundImage = ImageIO.read(new File("images/T_background.png")); } catch (IOException e2) { e2.printStackTrace(); backgroundImage = null; } x = new int[filenames.length]; actualX = new int[filenames.length]; y = new int[filenames.length]; for (int i = 0; i < filenames.length; i++) { x[i] = (i * SPACING) - (filenames.length * SPACING); actualX[i] = (i * SPACING) - (filenames.length * SPACING); } int[] y = new int[filenames.length]; }
diff --git a/src/bz/davide/dmxmljson/util/IntIntHashMap.java b/src/bz/davide/dmxmljson/util/IntIntHashMap.java index e326f1d..7982053 100644 --- a/src/bz/davide/dmxmljson/util/IntIntHashMap.java +++ b/src/bz/davide/dmxmljson/util/IntIntHashMap.java @@ -1,92 +1,93 @@ /* DMXmlJson - Java binding framework for xml and json - http://www.davide.bz/dmxj Copyright (C) 2013 Davide Montesin <[email protected]> - Bolzano/Bozen - Italy This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/> */ package bz.davide.dmxmljson.util; import java.util.HashMap; public class IntIntHashMap<T> { HashMap map; public IntIntHashMap() { map = new HashMap(); } public T put(int[] keys, T obj) { + HashMap nextMap; HashMap tmp = map; for (int i = 0; i < keys.length - 1; i++) { - tmp = (HashMap) tmp.get(keys[i]); - if (tmp == null) + nextMap = (HashMap) tmp.get(keys[i]); + if (nextMap == null) { - HashMap newmap = new HashMap(); - tmp.put(keys[i], newmap); - tmp = newmap; + nextMap = new HashMap(); + tmp.put(keys[i], nextMap); } + tmp = nextMap; } return (T) tmp.put(keys[keys.length - 1], obj); } public void put(int k1, int k2, T obj) { this.put(new int[] { k1, k2 }, obj); } public void put(int k1, int k2, int k3, T obj) { this.put(new int[] { k1, k2, k3 }, obj); } public void put(int k1, int k2, int k3, int k4, T obj) { this.put(new int[] { k1, k2, k3, k4 }, obj); } public T get(int[] keys) { HashMap tmp = map; for (int i = 0; i < keys.length - 1; i++) { tmp = (HashMap) tmp.get(keys[i]); if (tmp == null) { return null; } } return (T) tmp.get(keys[keys.length - 1]); } public T get(int k1, int k2) { return this.get(new int[] { k1, k2 }); } public T get(int k1, int k2, int k3) { return this.get(new int[] { k1, k2, k3 }); } public T get(int k1, int k2, int k3, int k4) { return this.get(new int[] { k1, k2, k3, k4 }); } }
false
true
public T put(int[] keys, T obj) { HashMap tmp = map; for (int i = 0; i < keys.length - 1; i++) { tmp = (HashMap) tmp.get(keys[i]); if (tmp == null) { HashMap newmap = new HashMap(); tmp.put(keys[i], newmap); tmp = newmap; } } return (T) tmp.put(keys[keys.length - 1], obj); }
public T put(int[] keys, T obj) { HashMap nextMap; HashMap tmp = map; for (int i = 0; i < keys.length - 1; i++) { nextMap = (HashMap) tmp.get(keys[i]); if (nextMap == null) { nextMap = new HashMap(); tmp.put(keys[i], nextMap); } tmp = nextMap; } return (T) tmp.put(keys[keys.length - 1], obj); }
diff --git a/gerrit-httpd/src/main/java/com/google/gerrit/httpd/rpc/changedetail/ChangeDetailFactory.java b/gerrit-httpd/src/main/java/com/google/gerrit/httpd/rpc/changedetail/ChangeDetailFactory.java index d641c86ca..2855e310a 100644 --- a/gerrit-httpd/src/main/java/com/google/gerrit/httpd/rpc/changedetail/ChangeDetailFactory.java +++ b/gerrit-httpd/src/main/java/com/google/gerrit/httpd/rpc/changedetail/ChangeDetailFactory.java @@ -1,238 +1,241 @@ // 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.google.gerrit.httpd.rpc.changedetail; import com.google.gerrit.common.data.ApprovalDetail; import com.google.gerrit.common.data.ApprovalType; import com.google.gerrit.common.data.ApprovalTypes; import com.google.gerrit.common.data.ChangeDetail; import com.google.gerrit.common.data.ChangeInfo; import com.google.gerrit.common.errors.NoSuchEntityException; import com.google.gerrit.httpd.rpc.Handler; import com.google.gerrit.reviewdb.Account; import com.google.gerrit.reviewdb.ApprovalCategory; import com.google.gerrit.reviewdb.Change; import com.google.gerrit.reviewdb.ChangeMessage; import com.google.gerrit.reviewdb.PatchSet; import com.google.gerrit.reviewdb.PatchSetAncestor; import com.google.gerrit.reviewdb.PatchSetApproval; import com.google.gerrit.reviewdb.RevId; import com.google.gerrit.reviewdb.ReviewDb; import com.google.gerrit.server.account.AccountInfoCacheFactory; import com.google.gerrit.server.patch.PatchSetInfoNotAvailableException; import com.google.gerrit.server.project.ChangeControl; import com.google.gerrit.server.project.NoSuchChangeException; import com.google.gerrit.server.workflow.CategoryFunction; import com.google.gerrit.server.workflow.FunctionState; import com.google.gwtorm.client.OrmException; import com.google.inject.Inject; import com.google.inject.assistedinject.Assisted; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; /** Creates a {@link ChangeDetail} from a {@link Change}. */ public class ChangeDetailFactory extends Handler<ChangeDetail> { public interface Factory { ChangeDetailFactory create(Change.Id id); } private final ApprovalTypes approvalTypes; private final ChangeControl.Factory changeControlFactory; private final FunctionState.Factory functionState; private final PatchSetDetailFactory.Factory patchSetDetail; private final AccountInfoCacheFactory aic; private final ReviewDb db; private final Change.Id changeId; private ChangeDetail detail; private ChangeControl control; @Inject ChangeDetailFactory(final ApprovalTypes approvalTypes, final FunctionState.Factory functionState, final PatchSetDetailFactory.Factory patchSetDetail, final ReviewDb db, final ChangeControl.Factory changeControlFactory, final AccountInfoCacheFactory.Factory accountInfoCacheFactory, @Assisted final Change.Id id) { this.approvalTypes = approvalTypes; this.functionState = functionState; this.patchSetDetail = patchSetDetail; this.db = db; this.changeControlFactory = changeControlFactory; this.aic = accountInfoCacheFactory.create(); this.changeId = id; } @Override public ChangeDetail call() throws OrmException, NoSuchEntityException, PatchSetInfoNotAvailableException, NoSuchChangeException { control = changeControlFactory.validateFor(changeId); final Change change = control.getChange(); final PatchSet patch = db.patchSets().get(change.currentPatchSetId()); if (patch == null) { throw new NoSuchEntityException(); } aic.want(change.getOwner()); detail = new ChangeDetail(); detail.setChange(change); detail.setAllowsAnonymous(control.forAnonymousUser().isVisible()); detail.setCanAbandon(change.getStatus().isOpen() && control.canAbandon()); detail.setStarred(control.getCurrentUser().getStarredChanges().contains( changeId)); loadPatchSets(); loadMessages(); if (change.currentPatchSetId() != null) { loadCurrentPatchSet(); } load(); detail.setAccounts(aic.create()); return detail; } private void loadPatchSets() throws OrmException { detail.setPatchSets(db.patchSets().byChange(changeId).toList()); } private void loadMessages() throws OrmException { detail.setMessages(db.changeMessages().byChange(changeId).toList()); for (final ChangeMessage m : detail.getMessages()) { aic.want(m.getAuthor()); } } private void load() throws OrmException { final PatchSet.Id psId = detail.getChange().currentPatchSetId(); final List<PatchSetApproval> allApprovals = db.patchSetApprovals().byChange(changeId).toList(); if (detail.getChange().getStatus().isOpen()) { final FunctionState fs = functionState.create(detail.getChange(), psId, allApprovals); final Set<ApprovalCategory.Id> missingApprovals = new HashSet<ApprovalCategory.Id>(); final Set<ApprovalCategory.Id> currentActions = new HashSet<ApprovalCategory.Id>(); for (final ApprovalType at : approvalTypes.getApprovalTypes()) { CategoryFunction.forCategory(at.getCategory()).run(at, fs); if (!fs.isValid(at)) { missingApprovals.add(at.getCategory().getId()); } } for (final ApprovalType at : approvalTypes.getActionTypes()) { if (CategoryFunction.forCategory(at.getCategory()).isValid( control.getCurrentUser(), at, fs)) { currentActions.add(at.getCategory().getId()); } } detail.setMissingApprovals(missingApprovals); detail.setCurrentActions(currentActions); } final HashMap<Account.Id, ApprovalDetail> ad = new HashMap<Account.Id, ApprovalDetail>(); for (PatchSetApproval ca : allApprovals) { ApprovalDetail d = ad.get(ca.getAccountId()); if (d == null) { d = new ApprovalDetail(ca.getAccountId()); ad.put(d.getAccount(), d); } if (ca.getPatchSetId().equals(psId)) { d.add(ca); } } final Account.Id owner = detail.getChange().getOwner(); if (ad.containsKey(owner)) { // Ensure the owner always sorts to the top of the table // ad.get(owner).sortFirst(); } aic.want(ad.keySet()); detail.setApprovals(ad.values()); } private void loadCurrentPatchSet() throws OrmException, NoSuchEntityException, PatchSetInfoNotAvailableException, NoSuchChangeException { final PatchSet.Id psId = detail.getChange().currentPatchSetId(); final PatchSetDetailFactory loader = patchSetDetail.create(psId); loader.patchSet = detail.getCurrentPatchSet(); loader.control = control; detail.setCurrentPatchSetDetail(loader.call()); final HashSet<Change.Id> changesToGet = new HashSet<Change.Id>(); final List<Change.Id> ancestorOrder = new ArrayList<Change.Id>(); for (PatchSetAncestor a : db.patchSetAncestors().ancestorsOf(psId)) { for (PatchSet p : db.patchSets().byRevision(a.getAncestorRevision())) { final Change.Id ck = p.getId().getParentKey(); if (changesToGet.add(ck)) { ancestorOrder.add(ck); } } } final RevId cprev = loader.patchSet.getRevision(); - final List<PatchSetAncestor> descendants = - cprev != null ? db.patchSetAncestors().descendantsOf(cprev).toList() - : Collections.<PatchSetAncestor> emptyList(); - for (final PatchSetAncestor a : descendants) { - changesToGet.add(a.getPatchSet().getParentKey()); + final Set<Change.Id> descendants = new HashSet<Change.Id>(); + if (cprev != null) { + for (PatchSetAncestor a : db.patchSetAncestors().descendantsOf(cprev)) { + final Change.Id ck = a.getPatchSet().getParentKey(); + if (descendants.add(ck)) { + changesToGet.add(a.getPatchSet().getParentKey()); + } + } } final Map<Change.Id, Change> m = db.changes().toMap(db.changes().get(changesToGet)); final ArrayList<ChangeInfo> dependsOn = new ArrayList<ChangeInfo>(); for (final Change.Id a : ancestorOrder) { final Change ac = m.get(a); if (ac != null) { aic.want(ac.getOwner()); dependsOn.add(new ChangeInfo(ac)); } } final ArrayList<ChangeInfo> neededBy = new ArrayList<ChangeInfo>(); - for (final PatchSetAncestor a : descendants) { - final Change ac = m.get(a.getPatchSet().getParentKey()); + for (final Change.Id a : descendants) { + final Change ac = m.get(a); if (ac != null) { aic.want(ac.getOwner()); neededBy.add(new ChangeInfo(ac)); } } Collections.sort(neededBy, new Comparator<ChangeInfo>() { public int compare(final ChangeInfo o1, final ChangeInfo o2) { return o1.getId().get() - o2.getId().get(); } }); detail.setDependsOn(dependsOn); detail.setNeededBy(neededBy); } }
false
true
private void loadCurrentPatchSet() throws OrmException, NoSuchEntityException, PatchSetInfoNotAvailableException, NoSuchChangeException { final PatchSet.Id psId = detail.getChange().currentPatchSetId(); final PatchSetDetailFactory loader = patchSetDetail.create(psId); loader.patchSet = detail.getCurrentPatchSet(); loader.control = control; detail.setCurrentPatchSetDetail(loader.call()); final HashSet<Change.Id> changesToGet = new HashSet<Change.Id>(); final List<Change.Id> ancestorOrder = new ArrayList<Change.Id>(); for (PatchSetAncestor a : db.patchSetAncestors().ancestorsOf(psId)) { for (PatchSet p : db.patchSets().byRevision(a.getAncestorRevision())) { final Change.Id ck = p.getId().getParentKey(); if (changesToGet.add(ck)) { ancestorOrder.add(ck); } } } final RevId cprev = loader.patchSet.getRevision(); final List<PatchSetAncestor> descendants = cprev != null ? db.patchSetAncestors().descendantsOf(cprev).toList() : Collections.<PatchSetAncestor> emptyList(); for (final PatchSetAncestor a : descendants) { changesToGet.add(a.getPatchSet().getParentKey()); } final Map<Change.Id, Change> m = db.changes().toMap(db.changes().get(changesToGet)); final ArrayList<ChangeInfo> dependsOn = new ArrayList<ChangeInfo>(); for (final Change.Id a : ancestorOrder) { final Change ac = m.get(a); if (ac != null) { aic.want(ac.getOwner()); dependsOn.add(new ChangeInfo(ac)); } } final ArrayList<ChangeInfo> neededBy = new ArrayList<ChangeInfo>(); for (final PatchSetAncestor a : descendants) { final Change ac = m.get(a.getPatchSet().getParentKey()); if (ac != null) { aic.want(ac.getOwner()); neededBy.add(new ChangeInfo(ac)); } } Collections.sort(neededBy, new Comparator<ChangeInfo>() { public int compare(final ChangeInfo o1, final ChangeInfo o2) { return o1.getId().get() - o2.getId().get(); } }); detail.setDependsOn(dependsOn); detail.setNeededBy(neededBy); }
private void loadCurrentPatchSet() throws OrmException, NoSuchEntityException, PatchSetInfoNotAvailableException, NoSuchChangeException { final PatchSet.Id psId = detail.getChange().currentPatchSetId(); final PatchSetDetailFactory loader = patchSetDetail.create(psId); loader.patchSet = detail.getCurrentPatchSet(); loader.control = control; detail.setCurrentPatchSetDetail(loader.call()); final HashSet<Change.Id> changesToGet = new HashSet<Change.Id>(); final List<Change.Id> ancestorOrder = new ArrayList<Change.Id>(); for (PatchSetAncestor a : db.patchSetAncestors().ancestorsOf(psId)) { for (PatchSet p : db.patchSets().byRevision(a.getAncestorRevision())) { final Change.Id ck = p.getId().getParentKey(); if (changesToGet.add(ck)) { ancestorOrder.add(ck); } } } final RevId cprev = loader.patchSet.getRevision(); final Set<Change.Id> descendants = new HashSet<Change.Id>(); if (cprev != null) { for (PatchSetAncestor a : db.patchSetAncestors().descendantsOf(cprev)) { final Change.Id ck = a.getPatchSet().getParentKey(); if (descendants.add(ck)) { changesToGet.add(a.getPatchSet().getParentKey()); } } } final Map<Change.Id, Change> m = db.changes().toMap(db.changes().get(changesToGet)); final ArrayList<ChangeInfo> dependsOn = new ArrayList<ChangeInfo>(); for (final Change.Id a : ancestorOrder) { final Change ac = m.get(a); if (ac != null) { aic.want(ac.getOwner()); dependsOn.add(new ChangeInfo(ac)); } } final ArrayList<ChangeInfo> neededBy = new ArrayList<ChangeInfo>(); for (final Change.Id a : descendants) { final Change ac = m.get(a); if (ac != null) { aic.want(ac.getOwner()); neededBy.add(new ChangeInfo(ac)); } } Collections.sort(neededBy, new Comparator<ChangeInfo>() { public int compare(final ChangeInfo o1, final ChangeInfo o2) { return o1.getId().get() - o2.getId().get(); } }); detail.setDependsOn(dependsOn); detail.setNeededBy(neededBy); }
diff --git a/editor/tools/plugins/com.google.dart.tools.core/src/com/google/dart/tools/core/generator/FileGenerator.java b/editor/tools/plugins/com.google.dart.tools.core/src/com/google/dart/tools/core/generator/FileGenerator.java index f04335408..04d670bac 100644 --- a/editor/tools/plugins/com.google.dart.tools.core/src/com/google/dart/tools/core/generator/FileGenerator.java +++ b/editor/tools/plugins/com.google.dart.tools.core/src/com/google/dart/tools/core/generator/FileGenerator.java @@ -1,313 +1,311 @@ /* * Copyright (c) 2011, the Dart project authors. * * Licensed under the Eclipse Public License v1.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/epl-v10.html * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.dart.tools.core.generator; import com.google.dart.tools.core.DartCore; import com.google.dart.tools.core.internal.model.DartLibraryImpl; import com.google.dart.tools.core.internal.model.HTMLFileImpl; import com.google.dart.tools.core.internal.model.info.DartLibraryInfo; import com.google.dart.tools.core.internal.util.Extensions; import com.google.dart.tools.core.internal.util.ResourceUtil; import com.google.dart.tools.core.internal.util.StatusUtil; import com.google.dart.tools.core.model.DartLibrary; import com.google.dart.tools.core.model.DartModelException; import com.google.dart.tools.core.utilities.general.SourceUtilities; import com.google.dart.tools.core.utilities.resource.IProjectUtilities; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.Assert; 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.SubMonitor; import java.io.File; import java.text.MessageFormat; import java.util.HashMap; /** * Instances of <code>FileGenerator</code> are used to create a new file in an existing Library * after validating the name of the new class. */ public class FileGenerator extends AbstractGenerator { private String fileName; private String fileLocation; private DartLibraryImpl library = null; private IFile iFile = null; public static final String DESCRIPTION = GeneratorMessages.FileGenerator_Description; public static String getStringLibraryPath(DartLibrary library) { try { return library.getCorrespondingResource().getLocation().makeAbsolute().removeLastSegments(1).toOSString(); } catch (DartModelException e) { DartCore.logError(e); } return null; } /** * Construct a new instance. */ public FileGenerator() { } /** * Generate the new file. * * @param monitor the progress monitor (not <code>null</code>) * @throws CoreException */ @Override public void execute(IProgressMonitor monitor) throws CoreException { // Sanity Checks // Fail fast for null elements Assert.isNotNull(fileName); Assert.isNotNull(fileLocation); IStatus status = validate(); if (status.getSeverity() == IStatus.ERROR) { throw new IllegalStateException(status.getMessage()); } // If the entered file name does not have a '.', then append ".dart" to the name, then this case // will fall through to the isDartLikeFileName case below SubMonitor subMonitor = SubMonitor.convert(monitor, GeneratorMessages.FileGenerator_message, 100); subMonitor.newChild(5); fileName = appendIfNoExtension(fileName, Extensions.DOT_DART); final File systemFile = getSystemFile(); // for non-library file creations, we need to compute which library configuration file we need // to modify (to include the resource which is about to be created) // if some library was selected, and fileLocation is pointing to the location of the selected library, // then we make the assumption that we want to add it to this specific library in this file location, // otherwise the current library shouldn't be used if (library != null) { String directoryOfLibrary = null; String temp = getStringLibraryPath(library); if (temp != null && !temp.isEmpty()) { directoryOfLibrary = temp; } // this is the check to see if the fileLocation is pointing to the location of the selected library, as mentioned above if (directoryOfLibrary != null && directoryOfLibrary.equals(fileLocation)) { // do nothing, current library is correct. - // Sanity Check - Assert.isTrue(library.getDefiningCompilationUnit().definesLibrary()); } else { library = null; } } // otherwise, we have the location of where the file will be written to, but we don't know which library we should modify // If we don't have a library yet, and the destination directory exists on disk, then find the // library in that directory, that is also loaded into the editor. File directory = new File(fileLocation); if (library == null && directory.exists()/* destination directory exists */) { library = (DartLibraryImpl) DartCore.findLibraryInDirectory(directory); } subMonitor.newChild(15); final HashMap<String, String> substitutions = new HashMap<String, String>(); String nameOfSrcTxt; boolean isNewLibrary = false; boolean isSrc = false; if (DartCore.isDartLikeFileName(fileName)) { // DART file String className = fileName.substring(0, fileName.indexOf('.')); substitutions.put("className", className); //$NON-NLS-1$ if (library != null) { substitutions.put("directives", ""); //$NON-NLS-1$ //$NON-NLS-2$ } else { // need the #library directive in the following, otherwise it isn't a defining compilation unit! substitutions.put("directives", "#library('" + className + "');" + SourceUtilities.LINE_SEPARATOR + SourceUtilities.LINE_SEPARATOR); //$NON-NLS-1$ //$NON-NLS-2$ isNewLibrary = true; } nameOfSrcTxt = "generated-dart-class-empty.txt"; isSrc = true; } else if (DartCore.isHTMLLikeFileName(fileName)) { // HTML file String name = fileName.substring(0, fileName.indexOf('.')); substitutions.put("title", name); //$NON-NLS-1$ String jsGeneratedFileName = name; if (library != null) { jsGeneratedFileName = library.getImplicitLibraryName(); } substitutions.put("dartPath", jsGeneratedFileName + ".dart.app.js"); //$NON-NLS-1$ //$NON-NLS-2$ nameOfSrcTxt = "generated-html.txt"; } else if (DartCore.isCSSLikeFileName(fileName)) { // CSS file- same as empty file case, for now nameOfSrcTxt = "generated-empty-file.txt"; } else { // empty file nameOfSrcTxt = "generated-empty-file.txt"; } subMonitor.newChild(40); // // Finally, write the content to the file. // execute(nameOfSrcTxt, systemFile, substitutions, monitor); //$NON-NLS-1$ if (isNewLibrary) { // // Call DartLibrary.openLibrary(..) to link the new file into the workspace. // DartCore.openLibrary(systemFile, monitor); } else if (library != null) { // // Call library.addSource(..) to append the additional #source tag onto the library // if (isSrc) { library.addSource(systemFile, monitor); } else { // else, add the #resource for all non-html resource files if (!DartCore.isHTMLLikeFileName(fileName)) { library.addResource(systemFile, monitor); } else { // Even though we aren't having the #resource(..) added for new HTML files, we do need the // new file linked into the project so that the resource change listener will be able to // trigger the DeltaProcessor. IFile iFile = IProjectUtilities.addLinkToProject(library.getDartProject().getProject(), systemFile, monitor); // Finally, create and add the new HTMLFile into the model HTMLFileImpl htmlFile = new HTMLFileImpl(library, iFile); DartLibraryInfo libraryInfo = (DartLibraryInfo) library.getElementInfo(); libraryInfo.addChild(htmlFile); } } library.setTopLevel(true); } else { // TODO The validator should be updated to ensure that this case is never reached. // should never get here, validator should be updated if it does. } // // Find and reference the IFile so that getFile() will return the correct resource // IFile[] files = ResourceUtil.getResources(systemFile); if (files.length > 0) { iFile = files[0]; } subMonitor.newChild(40); subMonitor.done(); } public IFile getFile() { return iFile; } public String getFileLocation() { return fileLocation; } public String getFileName() { return fileName; } public DartLibrary getLibrary() { return library; } public File getSystemFile() { // Sanity Check. Fail fast for null elements. Assert.isNotNull(fileName); Assert.isNotNull(fileLocation); return new File(fileLocation + File.separator + appendIfNoExtension(fileName, Extensions.DOT_DART)); } public void setFileLocation(String fileLocation) { this.fileLocation = fileLocation; } public void setFileName(String fileName) { this.fileName = fileName; } public void setLibrary(DartLibraryImpl library) { this.library = library; } @Override public IStatus validate() { IStatus status = StatusUtil.getMoreSevere(Status.OK_STATUS, validateFileLocation()); status = StatusUtil.getMoreSevere(status, validateFileName()); return status; } private IStatus validateFileLocation() { // Validate that: // 1) The file location is non-null and non-empty; // 2) The file location does not exist, and is a directory; // 3) The file location can be linked. if (fileLocation == null || fileLocation.isEmpty()) { return new Status(IStatus.ERROR, DartCore.PLUGIN_ID, DESCRIPTION); } // File file = new File(fileLocation); // if (!file.isDirectory()) { // return new Status(IStatus.ERROR, DartCore.PLUGIN_ID, MessageFormat.format( // GeneratorMessages.FileGenerator_locationDoesNotExist, new Object[] {fileLocation})); // } // if ((new Path(fileLocation)).isPrefixOf(ResourcesPlugin.getWorkspace().getRoot().getLocation().makeAbsolute())) { // return new Status(IStatus.ERROR, DartCore.PLUGIN_ID, MessageFormat.format( // GeneratorMessages.FileGenerator_filesCannotBeGenerated, new Object[] {fileLocation})); //$NON-NLS-2$ // } return Status.OK_STATUS; } private IStatus validateFileName() { // Validate that: // 1) The file is non-null and non-empty; // 2) The file does not contain any whitespace; // 3) The file exists already. // 4) Validation for Dart file type names, i.e. "-" not allowed in Dart type names if (fileName == null || fileName.isEmpty()) { return new Status(IStatus.ERROR, DartCore.PLUGIN_ID, DESCRIPTION); } else if (containsWhitespace(fileName)) { return new Status(IStatus.ERROR, DartCore.PLUGIN_ID, GeneratorMessages.FileGenerator_whiteSpaceNotAllowed); } else if (getSystemFile().exists()) { return new Status(IStatus.ERROR, DartCore.PLUGIN_ID, MessageFormat.format( GeneratorMessages.FileGenerator_fileExists, new Object[] {getSystemFile().getName()})); } String name = appendIfNoExtension(fileName, Extensions.DOT_DART); if (name.endsWith(Extensions.DOT_DART)) { String prefix = name.substring(0, name.lastIndexOf('.')); IStatus status = DartIdentifierUtil.validateIdentifier(prefix); if (status != Status.OK_STATUS) { return status; } } return Status.OK_STATUS; } }
true
true
public void execute(IProgressMonitor monitor) throws CoreException { // Sanity Checks // Fail fast for null elements Assert.isNotNull(fileName); Assert.isNotNull(fileLocation); IStatus status = validate(); if (status.getSeverity() == IStatus.ERROR) { throw new IllegalStateException(status.getMessage()); } // If the entered file name does not have a '.', then append ".dart" to the name, then this case // will fall through to the isDartLikeFileName case below SubMonitor subMonitor = SubMonitor.convert(monitor, GeneratorMessages.FileGenerator_message, 100); subMonitor.newChild(5); fileName = appendIfNoExtension(fileName, Extensions.DOT_DART); final File systemFile = getSystemFile(); // for non-library file creations, we need to compute which library configuration file we need // to modify (to include the resource which is about to be created) // if some library was selected, and fileLocation is pointing to the location of the selected library, // then we make the assumption that we want to add it to this specific library in this file location, // otherwise the current library shouldn't be used if (library != null) { String directoryOfLibrary = null; String temp = getStringLibraryPath(library); if (temp != null && !temp.isEmpty()) { directoryOfLibrary = temp; } // this is the check to see if the fileLocation is pointing to the location of the selected library, as mentioned above if (directoryOfLibrary != null && directoryOfLibrary.equals(fileLocation)) { // do nothing, current library is correct. // Sanity Check Assert.isTrue(library.getDefiningCompilationUnit().definesLibrary()); } else { library = null; } } // otherwise, we have the location of where the file will be written to, but we don't know which library we should modify // If we don't have a library yet, and the destination directory exists on disk, then find the // library in that directory, that is also loaded into the editor. File directory = new File(fileLocation); if (library == null && directory.exists()/* destination directory exists */) { library = (DartLibraryImpl) DartCore.findLibraryInDirectory(directory); } subMonitor.newChild(15); final HashMap<String, String> substitutions = new HashMap<String, String>(); String nameOfSrcTxt; boolean isNewLibrary = false; boolean isSrc = false; if (DartCore.isDartLikeFileName(fileName)) { // DART file String className = fileName.substring(0, fileName.indexOf('.')); substitutions.put("className", className); //$NON-NLS-1$ if (library != null) { substitutions.put("directives", ""); //$NON-NLS-1$ //$NON-NLS-2$ } else { // need the #library directive in the following, otherwise it isn't a defining compilation unit! substitutions.put("directives", "#library('" + className + "');" + SourceUtilities.LINE_SEPARATOR + SourceUtilities.LINE_SEPARATOR); //$NON-NLS-1$ //$NON-NLS-2$ isNewLibrary = true; } nameOfSrcTxt = "generated-dart-class-empty.txt"; isSrc = true; } else if (DartCore.isHTMLLikeFileName(fileName)) { // HTML file String name = fileName.substring(0, fileName.indexOf('.')); substitutions.put("title", name); //$NON-NLS-1$ String jsGeneratedFileName = name; if (library != null) { jsGeneratedFileName = library.getImplicitLibraryName(); } substitutions.put("dartPath", jsGeneratedFileName + ".dart.app.js"); //$NON-NLS-1$ //$NON-NLS-2$ nameOfSrcTxt = "generated-html.txt"; } else if (DartCore.isCSSLikeFileName(fileName)) { // CSS file- same as empty file case, for now nameOfSrcTxt = "generated-empty-file.txt"; } else { // empty file nameOfSrcTxt = "generated-empty-file.txt"; } subMonitor.newChild(40); // // Finally, write the content to the file. // execute(nameOfSrcTxt, systemFile, substitutions, monitor); //$NON-NLS-1$ if (isNewLibrary) { // // Call DartLibrary.openLibrary(..) to link the new file into the workspace. // DartCore.openLibrary(systemFile, monitor); } else if (library != null) { // // Call library.addSource(..) to append the additional #source tag onto the library // if (isSrc) { library.addSource(systemFile, monitor); } else { // else, add the #resource for all non-html resource files if (!DartCore.isHTMLLikeFileName(fileName)) { library.addResource(systemFile, monitor); } else { // Even though we aren't having the #resource(..) added for new HTML files, we do need the // new file linked into the project so that the resource change listener will be able to // trigger the DeltaProcessor. IFile iFile = IProjectUtilities.addLinkToProject(library.getDartProject().getProject(), systemFile, monitor); // Finally, create and add the new HTMLFile into the model HTMLFileImpl htmlFile = new HTMLFileImpl(library, iFile); DartLibraryInfo libraryInfo = (DartLibraryInfo) library.getElementInfo(); libraryInfo.addChild(htmlFile); } } library.setTopLevel(true); } else { // TODO The validator should be updated to ensure that this case is never reached. // should never get here, validator should be updated if it does. } // // Find and reference the IFile so that getFile() will return the correct resource // IFile[] files = ResourceUtil.getResources(systemFile); if (files.length > 0) { iFile = files[0]; } subMonitor.newChild(40); subMonitor.done(); }
public void execute(IProgressMonitor monitor) throws CoreException { // Sanity Checks // Fail fast for null elements Assert.isNotNull(fileName); Assert.isNotNull(fileLocation); IStatus status = validate(); if (status.getSeverity() == IStatus.ERROR) { throw new IllegalStateException(status.getMessage()); } // If the entered file name does not have a '.', then append ".dart" to the name, then this case // will fall through to the isDartLikeFileName case below SubMonitor subMonitor = SubMonitor.convert(monitor, GeneratorMessages.FileGenerator_message, 100); subMonitor.newChild(5); fileName = appendIfNoExtension(fileName, Extensions.DOT_DART); final File systemFile = getSystemFile(); // for non-library file creations, we need to compute which library configuration file we need // to modify (to include the resource which is about to be created) // if some library was selected, and fileLocation is pointing to the location of the selected library, // then we make the assumption that we want to add it to this specific library in this file location, // otherwise the current library shouldn't be used if (library != null) { String directoryOfLibrary = null; String temp = getStringLibraryPath(library); if (temp != null && !temp.isEmpty()) { directoryOfLibrary = temp; } // this is the check to see if the fileLocation is pointing to the location of the selected library, as mentioned above if (directoryOfLibrary != null && directoryOfLibrary.equals(fileLocation)) { // do nothing, current library is correct. } else { library = null; } } // otherwise, we have the location of where the file will be written to, but we don't know which library we should modify // If we don't have a library yet, and the destination directory exists on disk, then find the // library in that directory, that is also loaded into the editor. File directory = new File(fileLocation); if (library == null && directory.exists()/* destination directory exists */) { library = (DartLibraryImpl) DartCore.findLibraryInDirectory(directory); } subMonitor.newChild(15); final HashMap<String, String> substitutions = new HashMap<String, String>(); String nameOfSrcTxt; boolean isNewLibrary = false; boolean isSrc = false; if (DartCore.isDartLikeFileName(fileName)) { // DART file String className = fileName.substring(0, fileName.indexOf('.')); substitutions.put("className", className); //$NON-NLS-1$ if (library != null) { substitutions.put("directives", ""); //$NON-NLS-1$ //$NON-NLS-2$ } else { // need the #library directive in the following, otherwise it isn't a defining compilation unit! substitutions.put("directives", "#library('" + className + "');" + SourceUtilities.LINE_SEPARATOR + SourceUtilities.LINE_SEPARATOR); //$NON-NLS-1$ //$NON-NLS-2$ isNewLibrary = true; } nameOfSrcTxt = "generated-dart-class-empty.txt"; isSrc = true; } else if (DartCore.isHTMLLikeFileName(fileName)) { // HTML file String name = fileName.substring(0, fileName.indexOf('.')); substitutions.put("title", name); //$NON-NLS-1$ String jsGeneratedFileName = name; if (library != null) { jsGeneratedFileName = library.getImplicitLibraryName(); } substitutions.put("dartPath", jsGeneratedFileName + ".dart.app.js"); //$NON-NLS-1$ //$NON-NLS-2$ nameOfSrcTxt = "generated-html.txt"; } else if (DartCore.isCSSLikeFileName(fileName)) { // CSS file- same as empty file case, for now nameOfSrcTxt = "generated-empty-file.txt"; } else { // empty file nameOfSrcTxt = "generated-empty-file.txt"; } subMonitor.newChild(40); // // Finally, write the content to the file. // execute(nameOfSrcTxt, systemFile, substitutions, monitor); //$NON-NLS-1$ if (isNewLibrary) { // // Call DartLibrary.openLibrary(..) to link the new file into the workspace. // DartCore.openLibrary(systemFile, monitor); } else if (library != null) { // // Call library.addSource(..) to append the additional #source tag onto the library // if (isSrc) { library.addSource(systemFile, monitor); } else { // else, add the #resource for all non-html resource files if (!DartCore.isHTMLLikeFileName(fileName)) { library.addResource(systemFile, monitor); } else { // Even though we aren't having the #resource(..) added for new HTML files, we do need the // new file linked into the project so that the resource change listener will be able to // trigger the DeltaProcessor. IFile iFile = IProjectUtilities.addLinkToProject(library.getDartProject().getProject(), systemFile, monitor); // Finally, create and add the new HTMLFile into the model HTMLFileImpl htmlFile = new HTMLFileImpl(library, iFile); DartLibraryInfo libraryInfo = (DartLibraryInfo) library.getElementInfo(); libraryInfo.addChild(htmlFile); } } library.setTopLevel(true); } else { // TODO The validator should be updated to ensure that this case is never reached. // should never get here, validator should be updated if it does. } // // Find and reference the IFile so that getFile() will return the correct resource // IFile[] files = ResourceUtil.getResources(systemFile); if (files.length > 0) { iFile = files[0]; } subMonitor.newChild(40); subMonitor.done(); }
diff --git a/californium/src/main/java/ch/ethz/inf/vs/californium/network/connector/UDPConnector.java b/californium/src/main/java/ch/ethz/inf/vs/californium/network/connector/UDPConnector.java index cbbafbcb..b28b8b50 100644 --- a/californium/src/main/java/ch/ethz/inf/vs/californium/network/connector/UDPConnector.java +++ b/californium/src/main/java/ch/ethz/inf/vs/californium/network/connector/UDPConnector.java @@ -1,239 +1,239 @@ package ch.ethz.inf.vs.californium.network.connector; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.logging.Level; import java.util.logging.Logger; import ch.ethz.inf.vs.californium.CalifonriumLogger; import ch.ethz.inf.vs.californium.Server; import ch.ethz.inf.vs.californium.network.Endpoint; import ch.ethz.inf.vs.californium.network.EndpointAddress; import ch.ethz.inf.vs.californium.network.NetworkConfig; import ch.ethz.inf.vs.californium.network.NetworkConfigDefaults; import ch.ethz.inf.vs.californium.network.RawData; import ch.ethz.inf.vs.californium.network.RawDataChannel; /** * The UDPConnector connects a server to the network using the UDP protocol. The * <code>UDPConnector</code> is bound to an {@link Endpoint} by a * {@link RawDataChannel}. An <code>Endpoint</code> sends messages encapsulated * within a {@link RawData} by calling the method {@link #send(RawData)} on the * connector. When the connector receives a message, it invokes * {@link RawDataChannel#receiveData(RawData)}. UDP broadcast is allowed. * // TODO: describe that we can make many threads */ public class UDPConnector implements Connector { private final static Logger LOGGER = CalifonriumLogger.getLogger(UDPConnector.class); public static final int UNDEFINED = 0; private boolean running; private DatagramSocket socket; private final NetworkConfig config; private final EndpointAddress localAddr; private List<Thread> receiverThreads; private List<Thread> senderThreads; /** The queue of outgoing block (for sending). */ private final BlockingQueue<RawData> outgoing; // Messages to send /** The receiver of incoming messages */ private RawDataChannel receiver; // Receiver of messages public UDPConnector(EndpointAddress address, NetworkConfig config) { this.localAddr = address; this.config = config; this.running = false; int capacity = config.getInt(NetworkConfigDefaults.UDP_CONNECTOR_OUT_CAPACITY); this.outgoing = new LinkedBlockingQueue<RawData>(capacity); } @Override public synchronized void start() throws IOException { if (running) return; this.running = true; // if localAddr is null or port is 0, the system decides socket = new DatagramSocket(localAddr.getPort(), localAddr.getAddress()); int receiveBuffer = config.getInt( - NetworkConfigDefaults.UDP_CONNECTOR_RECEIVER_THREAD_COUNT); + NetworkConfigDefaults.UDP_CONNECTOR_RECEIVE_BUFFER); if (receiveBuffer != UNDEFINED) socket.setReceiveBufferSize(receiveBuffer); receiveBuffer = socket.getReceiveBufferSize(); int sendBuffer = config.getInt( - NetworkConfigDefaults.UDP_CONNECTOR_SENDER_THREAD_COUNT); + NetworkConfigDefaults.UDP_CONNECTOR_SEND_BUFFER); if (sendBuffer != UNDEFINED) socket.setSendBufferSize(sendBuffer); sendBuffer = socket.getSendBufferSize(); // if a wildcard in the address was used, we set the value that was // ultimately chosen by the system. if (localAddr.getAddress() == null) localAddr.setAddress(socket.getLocalAddress()); if (localAddr.getPort() == 0) localAddr.setPort(socket.getLocalPort()); // start receiver and sender threads int senderCount = config.getInt(NetworkConfigDefaults.UDP_CONNECTOR_SENDER_THREAD_COUNT); int receiverCount = config.getInt(NetworkConfigDefaults.UDP_CONNECTOR_RECEIVER_THREAD_COUNT); LOGGER.fine("UDP-connector starts "+senderCount+" sender threads and "+receiverCount+" receiver threads"); receiverThreads = new LinkedList<Thread>(); for (int i=0;i<receiverCount;i++) { receiverThreads.add(new Receiver("UDP-Receiver["+i+"]"+localAddr)); } senderThreads = new LinkedList<Thread>(); for (int i=0;i<senderCount;i++) { senderThreads.add(new Sender("UDP-Sender["+i+"]"+localAddr)); } for (Thread t:receiverThreads) t.start(); for (Thread t:senderThreads) t.start(); /* * Java bug: sometimes, socket.getReceiveBufferSize() and * socket.setSendBufferSize() block forever when called here. When * called up there, it seems to work. This issue occurred in Java * 1.7.0_09, Windows 7. */ LOGGER.info("UDP connector listening on "+socket.getLocalSocketAddress()+", recv buf = "+receiveBuffer+", send buf = "+sendBuffer); } @Override public synchronized void stop() { if (!running) return; this.running = false; // stop all threads for (Thread t:senderThreads) t.interrupt(); for (Thread t:receiverThreads) t.interrupt(); outgoing.clear(); if (socket != null) socket.close(); socket = null; } @Override public synchronized void destroy() { stop(); } @Override public void send(RawData msg) { if (msg == null) throw new NullPointerException(); outgoing.add(msg); } @Override public void setRawDataReceiver(RawDataChannel receiver) { this.receiver = receiver; } private abstract class Worker extends Thread { /** * Instantiates a new worker. * * @param name the name */ private Worker(String name) { super(name); setDaemon(false); // TODO: or rather true? } /* (non-Javadoc) * @see java.lang.Thread#run() */ public void run() { try { LOGGER.info("Start "+getName()+", (running = "+running+")"); while (running) { try { work(); } catch (Throwable t) { if (running) LOGGER.log(Level.WARNING, "Exception \""+t+"\" in thread " + getName()+": running="+running, t); else LOGGER.info("Exception \""+t+"\" in thread " + getName()+" has successfully stopped socket thread"); } } } finally { LOGGER.info(getName()+" has terminated (running = "+running+")"); } } /** * // TODO: describe * * @throws Exception the exception to be properly logged */ protected abstract void work() throws Exception; } private class Receiver extends Worker { private DatagramPacket datagram; private int size; private Receiver(String name) { super(name); this.size = config.getInt(NetworkConfigDefaults.UDP_CONNECTOR_DATAGRAM_SIZE); this.datagram = new DatagramPacket(new byte[size], size); } protected void work() throws IOException { datagram.setLength(size); socket.receive(datagram); if (Server.LOG_ENABLED) LOGGER.info("Connector ("+socket.getLocalSocketAddress()+") received "+datagram.getLength()+" bytes from "+datagram.getAddress()+":"+datagram.getPort()); byte[] bytes = Arrays.copyOfRange(datagram.getData(), datagram.getOffset(), datagram.getLength()); RawData msg = new RawData(bytes); msg.setAddress(datagram.getAddress()); msg.setPort(datagram.getPort()); receiver.receiveData(msg); } } private class Sender extends Worker { private DatagramPacket datagram; private Sender(String name) { super(name); this.datagram = new DatagramPacket(new byte[0], 0); } protected void work() throws InterruptedException, IOException { RawData raw = outgoing.take(); // Blocking datagram.setData(raw.getBytes()); datagram.setAddress(raw.getAddress()); datagram.setPort(raw.getPort()); if (Server.LOG_ENABLED) LOGGER.info("Connector ("+socket.getLocalSocketAddress()+") sends "+datagram.getLength()+" bytes to "+datagram.getSocketAddress()); socket.send(datagram); } } }
false
true
public synchronized void start() throws IOException { if (running) return; this.running = true; // if localAddr is null or port is 0, the system decides socket = new DatagramSocket(localAddr.getPort(), localAddr.getAddress()); int receiveBuffer = config.getInt( NetworkConfigDefaults.UDP_CONNECTOR_RECEIVER_THREAD_COUNT); if (receiveBuffer != UNDEFINED) socket.setReceiveBufferSize(receiveBuffer); receiveBuffer = socket.getReceiveBufferSize(); int sendBuffer = config.getInt( NetworkConfigDefaults.UDP_CONNECTOR_SENDER_THREAD_COUNT); if (sendBuffer != UNDEFINED) socket.setSendBufferSize(sendBuffer); sendBuffer = socket.getSendBufferSize(); // if a wildcard in the address was used, we set the value that was // ultimately chosen by the system. if (localAddr.getAddress() == null) localAddr.setAddress(socket.getLocalAddress()); if (localAddr.getPort() == 0) localAddr.setPort(socket.getLocalPort()); // start receiver and sender threads int senderCount = config.getInt(NetworkConfigDefaults.UDP_CONNECTOR_SENDER_THREAD_COUNT); int receiverCount = config.getInt(NetworkConfigDefaults.UDP_CONNECTOR_RECEIVER_THREAD_COUNT); LOGGER.fine("UDP-connector starts "+senderCount+" sender threads and "+receiverCount+" receiver threads"); receiverThreads = new LinkedList<Thread>(); for (int i=0;i<receiverCount;i++) { receiverThreads.add(new Receiver("UDP-Receiver["+i+"]"+localAddr)); } senderThreads = new LinkedList<Thread>(); for (int i=0;i<senderCount;i++) { senderThreads.add(new Sender("UDP-Sender["+i+"]"+localAddr)); } for (Thread t:receiverThreads) t.start(); for (Thread t:senderThreads) t.start(); /* * Java bug: sometimes, socket.getReceiveBufferSize() and * socket.setSendBufferSize() block forever when called here. When * called up there, it seems to work. This issue occurred in Java * 1.7.0_09, Windows 7. */ LOGGER.info("UDP connector listening on "+socket.getLocalSocketAddress()+", recv buf = "+receiveBuffer+", send buf = "+sendBuffer); }
public synchronized void start() throws IOException { if (running) return; this.running = true; // if localAddr is null or port is 0, the system decides socket = new DatagramSocket(localAddr.getPort(), localAddr.getAddress()); int receiveBuffer = config.getInt( NetworkConfigDefaults.UDP_CONNECTOR_RECEIVE_BUFFER); if (receiveBuffer != UNDEFINED) socket.setReceiveBufferSize(receiveBuffer); receiveBuffer = socket.getReceiveBufferSize(); int sendBuffer = config.getInt( NetworkConfigDefaults.UDP_CONNECTOR_SEND_BUFFER); if (sendBuffer != UNDEFINED) socket.setSendBufferSize(sendBuffer); sendBuffer = socket.getSendBufferSize(); // if a wildcard in the address was used, we set the value that was // ultimately chosen by the system. if (localAddr.getAddress() == null) localAddr.setAddress(socket.getLocalAddress()); if (localAddr.getPort() == 0) localAddr.setPort(socket.getLocalPort()); // start receiver and sender threads int senderCount = config.getInt(NetworkConfigDefaults.UDP_CONNECTOR_SENDER_THREAD_COUNT); int receiverCount = config.getInt(NetworkConfigDefaults.UDP_CONNECTOR_RECEIVER_THREAD_COUNT); LOGGER.fine("UDP-connector starts "+senderCount+" sender threads and "+receiverCount+" receiver threads"); receiverThreads = new LinkedList<Thread>(); for (int i=0;i<receiverCount;i++) { receiverThreads.add(new Receiver("UDP-Receiver["+i+"]"+localAddr)); } senderThreads = new LinkedList<Thread>(); for (int i=0;i<senderCount;i++) { senderThreads.add(new Sender("UDP-Sender["+i+"]"+localAddr)); } for (Thread t:receiverThreads) t.start(); for (Thread t:senderThreads) t.start(); /* * Java bug: sometimes, socket.getReceiveBufferSize() and * socket.setSendBufferSize() block forever when called here. When * called up there, it seems to work. This issue occurred in Java * 1.7.0_09, Windows 7. */ LOGGER.info("UDP connector listening on "+socket.getLocalSocketAddress()+", recv buf = "+receiveBuffer+", send buf = "+sendBuffer); }
diff --git a/lenskit-core/src/main/java/org/grouplens/lenskit/util/TaskTimer.java b/lenskit-core/src/main/java/org/grouplens/lenskit/util/TaskTimer.java index 5486f21b9..dc749c0e2 100644 --- a/lenskit-core/src/main/java/org/grouplens/lenskit/util/TaskTimer.java +++ b/lenskit-core/src/main/java/org/grouplens/lenskit/util/TaskTimer.java @@ -1,71 +1,71 @@ /* * LensKit, a reference implementation of recommender algorithms. * Copyright 2010-2011 Regents of the University of Minnesota * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., 51 * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.grouplens.lenskit.util; /** * @author Michael Ekstrand <[email protected]> * */ public class TaskTimer { private long startTime; private long stopTime; public TaskTimer() { start(); } public void start() { startTime = System.currentTimeMillis(); stopTime = -1; } public void stop() { stopTime = System.currentTimeMillis(); } public long elapsedMillis() { long stop = stopTime; if (stop < 0) stop = System.currentTimeMillis(); return stop - startTime; } public double elapsed() { return elapsedMillis() * 0.001; } public String elapsedPretty() { long elapsed = elapsedMillis(); double secs = (elapsed % 60000) / 1000.0; long mins = elapsed / 60000; long hrs = mins / 60; StringBuilder s = new StringBuilder(); if (hrs > 0) s.append(String.format("%dh", hrs)); if (mins > 0) s.append(String.format("%dm", mins % 60)); - s.append(String.format("%0.2fs", secs)); + s.append(String.format("%.2fs", secs)); return s.toString(); } @Override public String toString() { return elapsedPretty(); } }
true
true
public String elapsedPretty() { long elapsed = elapsedMillis(); double secs = (elapsed % 60000) / 1000.0; long mins = elapsed / 60000; long hrs = mins / 60; StringBuilder s = new StringBuilder(); if (hrs > 0) s.append(String.format("%dh", hrs)); if (mins > 0) s.append(String.format("%dm", mins % 60)); s.append(String.format("%0.2fs", secs)); return s.toString(); }
public String elapsedPretty() { long elapsed = elapsedMillis(); double secs = (elapsed % 60000) / 1000.0; long mins = elapsed / 60000; long hrs = mins / 60; StringBuilder s = new StringBuilder(); if (hrs > 0) s.append(String.format("%dh", hrs)); if (mins > 0) s.append(String.format("%dm", mins % 60)); s.append(String.format("%.2fs", secs)); return s.toString(); }
diff --git a/uk.ac.gda.client/src/uk/ac/gda/client/liveplot/LivePlotComposite.java b/uk.ac.gda.client/src/uk/ac/gda/client/liveplot/LivePlotComposite.java index c95761722..c73573d9d 100644 --- a/uk.ac.gda.client/src/uk/ac/gda/client/liveplot/LivePlotComposite.java +++ b/uk.ac.gda.client/src/uk/ac/gda/client/liveplot/LivePlotComposite.java @@ -1,1439 +1,1439 @@ /*- * Copyright © 2011 Diamond Light Source Ltd. * * This file is part of GDA. * * GDA is free software: you can redistribute it and/or modify it under the * terms of the GNU General Public License version 3 as published by the Free * Software Foundation. * * GDA 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 GDA. If not, see <http://www.gnu.org/licenses/>. */ package uk.ac.gda.client.liveplot; import gda.gui.scanplot.ScanDataPointPlotter; import gda.plots.Marker; import gda.plots.ScanLine; import gda.plots.ScanPair; import gda.plots.Type; import gda.plots.UpdatePlotQueue; import gda.plots.XYDataHandler; import gda.rcp.GDAClientActivator; import gda.scan.AxisSpec; import gda.scan.IScanDataPoint; import gda.util.FileUtil; import java.awt.Color; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.text.NumberFormat; import java.util.Arrays; import java.util.List; import java.util.Vector; import javax.swing.tree.TreePath; import org.dawb.common.ui.plot.AbstractPlottingSystem; import org.dawb.common.ui.plot.PlottingFactory; import org.dawnsci.plotting.api.PlotType; import org.dawnsci.plotting.api.axis.IAxis; import org.dawnsci.plotting.api.axis.IPositionListener; import org.dawnsci.plotting.api.axis.PositionEvent; import org.dawnsci.plotting.api.trace.ILineTrace; import org.dawnsci.plotting.api.trace.ILineTrace.PointStyle; import org.dawnsci.plotting.api.trace.ITrace; import org.dawnsci.plotting.jreality.impl.Plot1DAppearance; import org.dawnsci.plotting.jreality.impl.Plot1DGraphTable; import org.dawnsci.plotting.jreality.impl.Plot1DStyles; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Menu; import org.eclipse.ui.IActionBars; import org.eclipse.ui.IMemento; import org.eclipse.ui.IViewPart; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchPartSite; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.actions.ActionContext; import org.eclipse.ui.actions.ActionFactory; import org.eclipse.ui.actions.ActionGroup; import org.jfree.data.Range; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.StringUtils; import uk.ac.diamond.scisoft.analysis.axis.AxisValues; import uk.ac.diamond.scisoft.analysis.dataset.AbstractDataset; import uk.ac.diamond.scisoft.analysis.dataset.DoubleDataset; import uk.ac.diamond.scisoft.analysis.rcp.plotting.PlotAppearanceDialog; import uk.ac.gda.client.LineAppearanceProvider; import uk.ac.gda.common.rcp.util.GridUtils; import uk.ac.gda.preferences.PreferenceConstants; /** * Composite for displaying XY data from ScanDataPoints. * * Currently a copy of XYPlotView which uses the new plotting. * * TODO FIXME DO NOT COPY THIS CLASS. THIS IS A TEMPORARY MEASURE TO ALLOW * NEW PLOTTING TO WORK WITH VIEW SIMILAR TO XYPLOTVIEW. BECAUSE OF THE LIMITATIONS * OF THE OLD PLOTTING, THIS CLASS HAS DEPARTED FROM A GOOD DESIGN RELATIVE TO THE * NEW PLOTTING. PLANNED IS A SIMPLER ABSTRACT CLASS OR TOOL TO MONITOR SCANS */ public class LivePlotComposite extends Composite { /** * Strings used to reference values stored in memento */ public static final String MEMENTO_XY_DATA = "XYData"; public static final String MEMENTO_XYDATA_XAXISHEADER = "xydata_xAxisHeader"; public static final String MEMENTO_XTDATA_YAXISHEADER = "xydata_yAxisHeader"; public static final String MEMENTO_XYDATA_YAXISNAME = "xydata_yAxisName"; public static final String MEMENTO_XYDATA_VISIBLE = "xydata_visible"; public static final String MEMENTO_XYDATA_NAME = "xydata_name"; static public final String MEMENTO_ARCHIVEFILENAME = "xydata_archivefilename"; static public final String MEMENTO_XYDATA_DATAFILENAME = "xydata_datafilename"; static public final String MEMENTO_XYDATA_SCANNUMBER = "xydata_scannumber"; private static final Logger logger = LoggerFactory.getLogger(LivePlotComposite.class); private static final int[] WEIGHTS_NORMAL = new int[] { 80, 20 }; private static final int[] WEIGHTS_NO_LEGEND = new int[] { 100, 0 }; SubLivePlotView plotView; LiveLegend legend; ScanDataPointPlotter plotter = null; private SashForm sashForm; static LineAppearanceProvider lineAppearanceProvider = new LineAppearanceProvider(); static public Color getColour(int nr) { return lineAppearanceProvider.getColour(nr); } static public int getLineWidth() { return lineAppearanceProvider.getLineWidth(); } static public Plot1DStyles getStyle(int nr) { return lineAppearanceProvider.getStyle(nr); } /** * Returns the tree viewer which shows the resource hierarchy. * * @return the tree viewer * @since 2.0 */ TreeViewer getTreeViewer() { return legend.getTreeViewer(); } private ActionGroup actionGroup; /** * @param parent * @param actionBars * @param partName * @param toolbarActions */ void createAndRegisterPlotActions(@SuppressWarnings("unused") final Composite parent, IActionBars actionBars, @SuppressWarnings("unused") String partName, final List<IAction> toolbarActions) { for (IAction iAction : toolbarActions) { actionBars.getToolBarManager().add(iAction); } // TODO Get this working // @Override // public void plotActionPerformed(final PlotActionEvent event) { // if (event instanceof PlotActionComplexEvent) { // // if the event has come from right click then show the data table dialog. // parent.getDisplay().asyncExec(new Runnable() { // @Override // public void run() { // PlotDataTableDialog dataDialog = new PlotDataTableDialog(parent.getShell(), // (PlotActionComplexEvent) event); // dataDialog.open(); // } // }); // } // } } /* * Made final as the value is passed to members in constructors so a change at this level would be * invalid if not passed down to members as well. */ private final String archiveFolder; void initContextMenu(IWorkbenchPartSite site, IWorkbenchWindow window, final ActionGroup parentActions) { actionGroup = new XYLegendActionGroup(window, this); MenuManager menuMgr = new MenuManager("#PopupMenu"); //$NON-NLS-1$ menuMgr.setRemoveAllWhenShown(true); menuMgr.addMenuListener(new IMenuListener() { @Override public void menuAboutToShow(IMenuManager manager) { IStructuredSelection selection = (IStructuredSelection) getTreeViewer().getSelection(); ActionContext cntx = new ActionContext(selection); actionGroup.setContext(cntx); actionGroup.fillContextMenu(manager); if (parentActions != null) { parentActions.setContext(cntx); parentActions.fillContextMenu(manager); } } }); TreeViewer viewer = getTreeViewer(); Menu menu = menuMgr.createContextMenu(viewer.getTree()); viewer.getTree().setMenu(menu); site.registerContextMenu(menuMgr, viewer); } @Override public void dispose() { super.dispose(); plotView.dispose(); } /** * @param value * True if new scans are to be hidden automatically */ public void setAutoHideNewScan(Boolean value) { legend.setAutoHideNewScan(value); } /** * @param value * True if lasts scans are to be hidden automatically */ public void setAutoHideLastScan(Boolean value) { legend.setAutoHideLastScan(value); } /** * @return true if new scans are not made visible */ public Boolean getAutoHideNewScan() { return legend.getAutoHideNewScan(); } /** * @return true if last scans are made invisible */ public Boolean getAutoHideLastScan() { return legend.autoHideLastScan; } /** * Hide all scans */ public void hideAll() { legend.hideAll(); } /** * Clear the graph */ public void clearGraph() { plotView.deleteAllLines(); plotter.clearGraph(); legend.removeAllItems(); } /** * remove the item from the tree whose filename equals the one specified * * @param filename */ public void removeScanGroup(String filename) { legend.removeScanGroup(filename); // the actual XYData is removed in response to a change in the tree structure of the legend } public void removeScanTreeObjects(Object[] selectedItems) { legend.removeScanTreeObjects(selectedItems); } /** * @param point */ public void addData(IScanDataPoint point) { if (!isDisposed()) plotter.addData(point); } /** * @param parent * @param style * @param archiveFolder - folder into which data is to be archived during normal running of the composite */ public LivePlotComposite(IWorkbenchPart parentPart, Composite parent, int style, String archiveFolder) { super(parent, style); this.archiveFolder = archiveFolder; this.setLayout(new FillLayout()); sashForm = new SashForm(this, SWT.HORIZONTAL); sashForm.setLayout(new FillLayout()); plotView = new SubLivePlotView(parentPart, sashForm, SWT.NONE, archiveFolder); legend = new LiveLegend(sashForm, SWT.NONE, plotView); showLenged(true); sashForm.setWeights(WEIGHTS_NORMAL); plotter = new ScanDataPointPlotter(plotView, legend, archiveFolder); } private boolean showLegend; /** * @param showLegend */ public void showLenged(Boolean showLegend) { this.showLegend = showLegend; sashForm.setWeights(showLegend ? WEIGHTS_NORMAL : WEIGHTS_NO_LEGEND); } /** * @return true if legend is hidden */ public Boolean getShowLegend() { return showLegend; } /** * Add a scan line * @param scanIdentifier - scan id from scandatapoint * @param fileName - file into which data was written * @param label * @param xData * @param yData * @param visible * @param reload */ public void addData(String scanIdentifier, String fileName, String label, DoubleDataset xData, DoubleDataset yData, boolean visible, boolean reload, AxisSpec yAxisName) { if (!isDisposed()) plotter.addData(scanIdentifier, fileName, null, xData, yData, xData.getName(), label, visible, reload, yAxisName); } public void saveState(IMemento memento, String archiveFolder) { plotView.saveState(memento, archiveFolder); } public void initFromMemento(IMemento memento, String storeFolderPath) { //clear existing lines plotView.deleteAllLines(); /* * The auto setting of visibility needs to be disabled during the restoration as * the visibilities are saved in the memento */ Boolean autoHideLastScan = getAutoHideLastScan(); Boolean autoHideNewScan = getAutoHideNewScan(); setAutoHideLastScan(false); setAutoHideNewScan(false); try{ IMemento[] allScans = memento.getChildren(MEMENTO_XY_DATA); for (IMemento thisScan : allScans) { try { String archiveFileName = thisScan.getString(MEMENTO_ARCHIVEFILENAME); File file = new File(storeFolderPath + File.separator + archiveFileName); if (!file.exists()) { continue; } String uniquename = thisScan.getString(MEMENTO_XYDATA_NAME); String dataFileName = thisScan.getString(MEMENTO_XYDATA_DATAFILENAME); String scanIdentifier = thisScan.getString(MEMENTO_XYDATA_SCANNUMBER); boolean visible = thisScan.getBoolean(MEMENTO_XYDATA_VISIBLE); String xAxisHeader = thisScan.getString(MEMENTO_XYDATA_XAXISHEADER); String yAxisHeader = thisScan.getString(MEMENTO_XTDATA_YAXISHEADER); String yAxisName = thisScan.getString(MEMENTO_XYDATA_YAXISNAME); AxisSpec axisSpec = yAxisName != null ? new AxisSpec(yAxisName): null; LiveData scan = new LiveData(0, uniquename, xAxisHeader, yAxisHeader, archiveFileName, dataFileName, axisSpec); Vector<String> stepIds=new Vector<String>(); String [] parts = uniquename.split(","); for(int i=1; i< parts.length-1;i++){ stepIds.add(parts[i]); } if(visible ){ //if memento states visible then unarchive and simply add to the list of scans scan.unarchive(archiveFolder); DoubleDataset xdata = scan.archive.getxAxis().toDataset(); if(xdata == null || xdata.getSize()==0) continue; plotter.addData(scanIdentifier, dataFileName, stepIds, xdata, scan.archive.getyVals(), xAxisHeader, yAxisHeader, true, false, axisSpec); }else { /** * we do not want to unarchive the data is it is not visible so we make the system create a * dummy line and then change it to archive state by setting archivefilename */ int linenum = plotter.addData(scanIdentifier, dataFileName, stepIds, new DoubleDataset(1), new DoubleDataset(1), xAxisHeader, yAxisHeader, false, false, axisSpec); plotView.getXYData(linenum).archiveFilename = scan.archiveFilename;//we need to set to archiveFilename in scan as currently equal to null plotView.getXYData(linenum).archive=null; } } catch (Throwable e) { logger.warn("Error restoring previous state.", e); } } }finally{ setAutoHideLastScan(autoHideLastScan); setAutoHideNewScan(autoHideNewScan); } PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() { @Override public void run() { //whilst adding lines above we have force reload of the model off - by passing false to the addData methods //we need to run reload once to ensure the tree gets displayed legend.reload(); } }); //get the data plotter plotView.onUpdate(true); } String getArchiveFolder() { return archiveFolder; } public Object getPlottingSystem() { return this.plotView.plottingSystem; } } /** * TODO FIXME DO NOT COPY THIS CLASS. THIS IS A TEMPORARY MEASURE TO ALLOW * NEW PLOTTING TO WORK WITH VIEW SIMILAR TO XYPLOTVIEW. BECAUSE OF THE LIMITATIONS * OF THE OLD PLOTTING, THIS CLASS HAS DEPARTED FROM A GOOD DESIGN RELATIVE TO THE * NEW PLOTTING. PLANNED IS A SIMPLER ABSTRACT CLASS OR TOOL TO MONITOR SCANS */ class SubLivePlotView extends Composite implements XYDataHandler { private static final String UNKNOWN = "unknown"; private static final Logger logger = LoggerFactory.getLogger(SubLivePlotView.class); static public final String ID = "uk.ac.gda.client.xyplotview"; protected AbstractPlottingSystem plottingSystem; LiveData dummy; // used when all other lines are invisible private final String archiveFolder; private Label positionLabel; public SubLivePlotView(IWorkbenchPart parentPart, Composite parent, int style, String archiveFolder) { super(parent, style); this.archiveFolder = archiveFolder; dummy = new LiveData(1, "", "x", "y", null,null, null); dummy.addPointToLine(0., 0.); dummy.addPointToLine(1., 1.); dummy.setVisible(false, archiveFolder); GridLayout layout = new GridLayout(); layout.numColumns = 1; setLayout(layout); GridUtils.removeMargins(this); positionLabel = new Label(this, SWT.LEFT); positionLabel.setText(""); { GridData gridData = new GridData(); gridData.horizontalAlignment = SWT.FILL; gridData.grabExcessHorizontalSpace = true; positionLabel.setLayoutData(gridData); } Composite plotArea = new Composite(this, SWT.NONE); plotArea.setLayout(new FillLayout()); { GridData gridData = new GridData(); gridData.horizontalAlignment = SWT.FILL; gridData.grabExcessHorizontalSpace = true; gridData.grabExcessVerticalSpace = true; gridData.verticalAlignment = SWT.FILL; plotArea.setLayoutData(gridData); } try { // We always have a light weight one for this view as there is already // another using DatasetPlot. this.plottingSystem = PlottingFactory.getLightWeightPlottingSystem(); } catch (Exception ne) { logger.error("Cannot create a plotting system!", ne); return; } IActionBars bars = parentPart instanceof IViewPart ? ((IViewPart)parentPart).getViewSite().getActionBars() : null; plottingSystem.createPlotPart(plotArea, parentPart.getTitle(), bars, PlotType.XY, parentPart); plottingSystem.setShowLegend(false); plottingSystem.setXfirst(true); plottingSystemPositionListener = new IPositionListener() { @Override public void positionChanged(PositionEvent evt) { positionLabel.setText(String.format("X:%.7g Y:%.7g", evt.x, evt.y)); } }; plottingSystem.addPositionListener(plottingSystemPositionListener); IPreferenceStore preferenceStore = GDAClientActivator.getDefault().getPreferenceStore(); int plotPeriodMS = preferenceStore.getInt(PreferenceConstants.GDA_CLIENT_PLOT_PERIOD_MS); updateQueue.setPlotPeriodMS(plotPeriodMS); } void saveState(IMemento memento, String archiveFolder) { Vector<String> archivedFiles=new Vector<String>(); for (LiveData scan : scans){ if (scan != null) { try { archivedFiles.add(scan.saveState(memento, archiveFolder)); } catch (Exception e) { logger.warn("Error saving state of scan " + scan.name, e); } } } //The folder is only to contain files from XYData in this composite so //delete all other files to reduce disk usage File folder = new File(archiveFolder); for( File f : folder.listFiles()){ if( !archivedFiles.contains(f.getName())) if(!f.delete()) logger.warn("Unable to delete file " + f.getAbsolutePath()); } } /** * Entry in scans array that is to contain the next XYData */ int nextUnInitialisedLine = 0; LiveData scans[] = new LiveData[0]; private UpdatePlotQueue updateQueue = new UpdatePlotQueue(); private IPositionListener plottingSystemPositionListener; LiveData getXYData(int line) { if (line > scans.length - 1) throw new IllegalArgumentException("line > scans.length"); return scans[line]; } @Override public void addPointToLine(int which, double x, double y) { if (!isDisposed()) { getXYData(which).addPointToLine(x, y); updateQueue.update(this); } } @Override public void archive(boolean all, String archiveFolder) throws IOException { if (!isDisposed()) { for (LiveData data : scans) { if (data != null && !data.isVisible()) data.archive(archiveFolder); } updateQueue.update(this); } } @Override public void copySettings(XYDataHandler other) { } @Override public void deleteAllLines() { if (!isDisposed()) { plottingSystem.clear(); plottingSystem.reset(); scans = new LiveData[0]; nextUnInitialisedLine = 0; } } @Override public void dispose() { updateQueue.setKilled(true); if (plottingSystem != null) { if( plottingSystemPositionListener != null){ plottingSystem.removePositionListener(plottingSystemPositionListener); plottingSystemPositionListener = null; } plottingSystem.dispose(); plottingSystem = null; } } @Override public Range getLeftDomainBounds() { return null; } @Override public int getNextAvailableLine() { return nextUnInitialisedLine; } @Override public Double getStripWidth() { return null; } @Override public NumberFormat getXAxisNumberFormat() { return null; } @Override public NumberFormat getYAxisNumberFormat() { return null; } @Override public void initializeLine(int which, int axis, String name, String xAxisHeader, String yAxisHeader, String dataFileName, AxisSpec yAxisSpec) { checkScansArray(which); //name = TraceUtils.getUniqueTrace(name, plottingSystem); scans[which] = new LiveData(which, name, xAxisHeader, yAxisHeader, null, dataFileName, yAxisSpec); nextUnInitialisedLine = which + 1; } private void checkScansArray(int which) { if (scans.length - 1 < which) { scans = Arrays.copyOf(scans, (which + 10) * 2); } } @Override public void setDomainBounds(Range domainBounds) { // do nothing } @Override public void setLeftRangeBounds(Range leftRangeBounds) { // do nothing } @Override public void setLegendVisible(boolean newValue) { // do nothing } @Override public void setLineColor(int which, Color color) { if (!isDisposed()) { getXYData(which).setLineColor(color, archiveFolder); updateQueue.update(this); } } @Override public void deleteLine(int which) { if (!isDisposed()) { if (which > scans.length - 1) throw new IllegalArgumentException("which > scans.length"); LiveData line = scans[which]; if(line != null) line.deleteArchive(archiveFolder); scans[which] = null; updateQueue.update(this); } } @Override public void setLineMarker(int which, Marker marker) { } @Override public void setLineType(Type t) { // do nothing } @Override public void setLineVisibility(int which, boolean visibility) { if (!isDisposed()) { getXYData(which).setVisible(visibility, archiveFolder); updateQueue.update(this); } } @Override public void setRightRangeBounds(Range rightRangeBounds) { } @Override public void setScientificXAxis() { } @Override public void setScientificYAxis() { } @Override public void setTitle(String title) { plottingSystem.setTitle(title); } @Override public void setTurboMode(boolean turboMode) { } @Override public void setVerticalXAxisTicks(boolean value) { } @Override public void setXAxisLabel(String label) { } @Override public void setYAxisLabel(String label) { } @Override public void setZooming(boolean zooming) { } @Override public void unArchive() { } @Override public Color getLineColor(int which) { if (!isDisposed()) return getXYData(which).getLineColor(archiveFolder); return Color.BLACK; } protected Plot1DAppearance getAppearanceCopy(int which) { if (!isDisposed()) return getXYData(which).getAppearanceCopy(archiveFolder); return null; } @Override public Marker getLineMarker(int which) { return null; } /** * This method is the incorrect design. It is called to replot all data * whenever one data changes. Instead information about which data changed * should not be lost and then the correct plot only updated. */ @Override public void onUpdate(boolean force) { if (plottingSystem == null) return; try { /** * TODO FIXME This class taken from XYPlotComponent replots all the plots * if one point is added to the end of one plot. Instead it should just add the * data to the one plot that is changing. */ List<LineData> xys = new Vector<LineData>(); final List<String> invis = new Vector<String>(); String xAxisHeader = null; String yAxisHeader = null; boolean xAxisIsVarious = false; boolean yAxisIsVarious = false; boolean additionalYAxes = false; for (LiveData sd : scans) { if (sd != null && sd.number > 1 ) {//do not show lines with only 1 point as the datasetplotter throws exceptions if (sd.isVisible()) { xys.add( new LineData(sd.archive.getAppearance(), sd.archive.getxAxis().toDataset(),sd.archive.getyVals(), sd.yAxisSpec )); AbstractDataset y = sd.archive.getyVals(); if (y.getName()==null || "".equals(y.getName())) { y.setName(sd.name); } if (!xAxisIsVarious && StringUtils.hasLength(sd.xLabel)) { if (xAxisHeader == null) { xAxisHeader = sd.xLabel; } else if (!sd.xLabel.equals(xAxisHeader)) { xAxisHeader = "various"; xAxisIsVarious = true; } } if( sd.yAxisSpec==null){ if (!yAxisIsVarious && StringUtils.hasLength(sd.yLabel)) { if (yAxisHeader == null) { yAxisHeader = sd.yLabel; } else if (!sd.yLabel.equals(yAxisHeader)) { yAxisHeader = "various"; yAxisIsVarious = true; } } } else { additionalYAxes = true; } } else { try { invis.add(sd.archive.getyVals().getName()); } catch (NullPointerException npe) { continue; } } } } if (xys.isEmpty()) { plottingSystem.clear(); return; } createUpdatePlot(xAxisHeader, yAxisHeader, xys, invis, additionalYAxes); } catch (Throwable e) { logger.warn(e.getMessage(),e); } } /** * Updates the plot in the UI Thread, creates new traces where required. * This horrendous way of doing it, results from the fact that we reuse XYPlotComposite. A better way would be with updating and creating individual traces. TODO Convert to more logical design. * @param additionalYAxes */ private void createUpdatePlot(String xLabelIn, String yLabelIn, final List<LineData> xys, final List<String> invis, boolean additionalYAxes) { final String xLabel = xLabelIn != null ? xLabelIn : UNKNOWN; final String yLabel = yLabelIn != null ? yLabelIn : UNKNOWN; final String title = (additionalYAxes ? "various" : yLabel) + " / " + xLabel; Display.getDefault().syncExec(new Runnable() { @Override public void run() { plottingSystem.reset(); //remove all axes plottingSystem.setTitle(title); plottingSystem.getSelectedXAxis().setTitle(xLabel); plottingSystem.getSelectedYAxis().setTitle(yLabel); IAxis defaultYAxis = null; for(IAxis axis : plottingSystem.getAxes()){ if( axis.isPrimaryAxis() && axis.isYAxis()){ defaultYAxis = axis; defaultYAxis.setVisible(!yLabel.equals(UNKNOWN)); break; } } for(IAxis axis : plottingSystem.getAxes()){ if( !axis.isPrimaryAxis()) plottingSystem.removeAxis(axis); } for (final LineData ld : xys) { AbstractDataset y = ld.getY(); String name = y.getName(); if (name==null || "".equals(name)) { logger.error("y dataset is not named - it should be!"); } AxisSpec axisSpec = ld.getyAxisSpec(); String yAxisName = axisSpec != null ? axisSpec.getName(): null; if( yAxisName != null){ IAxis extraYAxis = null; for(IAxis axis : plottingSystem.getAxes()){ String title2 = axis.getTitle(); if( title2 != null && title2.equals(yAxisName)){ extraYAxis = axis; break; } } if( extraYAxis == null){ extraYAxis = plottingSystem.createAxis(yAxisName, true, SWT.LEFT); } plottingSystem.setSelectedYAxis( extraYAxis); } else { plottingSystem.setSelectedYAxis( defaultYAxis); } ILineTrace trace = plottingSystem.createLineTrace(name); trace.setLineWidth(ld.appearance.getLineWidth()); trace.setPointSize(3); switch(ld.getAppearance().getStyle()){ case DASHED: trace.setPointStyle(PointStyle.NONE); - trace.setTraceType(TraceType.DASH_LINE); + trace.setTraceType(ILineTrace.TraceType.DASH_LINE); break; case DASHED_POINT: trace.setPointStyle(PointStyle.DIAMOND); - trace.setTraceType(TraceType.DASH_LINE); + trace.setTraceType(ILineTrace.TraceType.DASH_LINE); break; case SOLID: trace.setPointStyle(PointStyle.NONE); - trace.setTraceType(TraceType.SOLID_LINE); + trace.setTraceType(ILineTrace.TraceType.SOLID_LINE); break; case SOLID_POINT: trace.setPointStyle(PointStyle.DIAMOND); - trace.setTraceType(TraceType.SOLID_LINE); + trace.setTraceType(ILineTrace.TraceType.SOLID_LINE); break; case POINT: trace.setPointStyle(PointStyle.DIAMOND); - trace.setTraceType(TraceType.POINT); + trace.setTraceType(ILineTrace.TraceType.POINT); } final Color color = ld.getAppearance().getColour(); trace.setTraceColor(new org.eclipse.swt.graphics.Color(null, color.getRed(), color.getGreen(), color.getBlue())); trace.setData(ld.getX(), ld.getY()); plottingSystem.addTrace(trace); plottingSystem.setSelectedYAxis( defaultYAxis); } /** * BODGE WARNING There is no clear start of scan or start of new plot in * XYDataHandler. Instead we deduce that anything not visible should be removed. */ for (String traceName : invis) { ITrace trace = plottingSystem.getTrace(traceName); if (trace!=null) plottingSystem.removeTrace(trace); } if (plottingSystem.isRescale()) { plottingSystem.autoscaleAxes(); } } }); } @Override public void setsPointsForLine(int which, DoubleDataset xData, DoubleDataset yData) { if (!isDisposed()) { getXYData(which).setsPointsForLine(xData, yData, archiveFolder); updateQueue.update(this); } } public void setLineWidth(int lineNumber, int lineWidth) { if (!isDisposed()) { getXYData(lineNumber).setLineWidth(lineWidth, archiveFolder); } } public void setPlot1DStyles(int lineNumber, Plot1DStyles style) { if (!isDisposed()) { getXYData(lineNumber).setPlot1DStyles(style, archiveFolder); } } } /** * Class to hold the data and state of a single XY line * The data can be archived to file, indicated by archiveFilename being non null * To allow mementos to be copied along with archive folders archiveFilename only holds the filename and not the * path. The unarchive, archive methods will need an archive folder. * * TODO FIXME DO NOT COPY THIS CLASS. THIS IS A TEMPORARY MEASURE TO ALLOW * NEW PLOTTING TO WORK WITH VIEW SIMILAR TO XYPLOTVIEW. BECAUSE OF THE LIMITATIONS * OF THE OLD PLOTTING, THIS CLASS HAS DEPARTED FROM A GOOD DESIGN RELATIVE TO THE * NEW PLOTTING. PLANNED IS A SIMPLER ABSTRACT CLASS OR TOOL TO MONITOR SCANS */ class LiveData { private static final Logger logger = LoggerFactory.getLogger(LiveData.class); int number = 0; LiveDataArchive archive; // data and appearance String name; // a mix of the name of the group of plots (scan number) and the name of the line (column header) String archiveFilename = null; // the file created by the archive() method and read by unarchive() int which = 0; String xLabel; String yLabel; AxisSpec yAxisSpec; /** * Scan file holding all the data of the scan */ private final String dataFileName; /** * * @param which - index in the array of xydata - used to get appearance and color * @param name - unique name, scanid: steps... ylabel * @param xLabel * @param yLabel * @param archiveFilename - archive holding the data, only filename, you need to combine with the archive folder * @param dataFileName - the name of the file holding the scan data */ LiveData(int which, String name, String xLabel, String yLabel, String archiveFilename, String dataFileName, AxisSpec axisSpec) { this.name = name; this.which = which; this.xLabel = xLabel; this.yLabel = yLabel; this.archiveFilename = archiveFilename; this.dataFileName = dataFileName; if( archiveFilename == null){ resetArchive(which); } this.yAxisSpec =axisSpec; } public void deleteArchive(String archiveFolder) { if(isArchived()){ File f= new File(getArchivePath(archiveFolder, archiveFilename)); if( !f.delete()) logger.warn("Unable to delete file " + f.getAbsolutePath()); archiveFilename = null; //ensure the archive daya exists in case it is referenced somewhere resetArchive(which); } } public boolean isArchived(){ return archiveFilename != null; } String getArchiveFilename(){ String archivedFilename = name.replaceAll(" +", "_"); return archivedFilename.replaceAll("[,;:]", "_"); } /** * Saves the state into the memento and into a file in the archive folder * @param memento * @param archiveFolder * @return The filename of the archive - not the full path * @throws IOException */ public String saveState(IMemento memento, String archiveFolder) throws IOException { //note that the data may be archived at this point so archive==null String archivedFilename = getArchiveFilename(); persistToFilePath(archiveFolder, archivedFilename); IMemento child = memento.createChild(LivePlotComposite.MEMENTO_XY_DATA); child.putString(LivePlotComposite.MEMENTO_XYDATA_NAME, name); child.putString(LivePlotComposite.MEMENTO_ARCHIVEFILENAME, archivedFilename);//archivedFilePath); child.putString(LivePlotComposite.MEMENTO_XYDATA_DATAFILENAME, dataFileName); child.putString(LivePlotComposite.MEMENTO_XYDATA_SCANNUMBER, deriveScanIdentifier(name)); child.putString(LivePlotComposite.MEMENTO_XYDATA_XAXISHEADER, xLabel); child.putString(LivePlotComposite.MEMENTO_XTDATA_YAXISHEADER, yLabel); child.putBoolean(LivePlotComposite.MEMENTO_XYDATA_VISIBLE, archive != null ? archive.getAppearance().isVisible() : false); if( yAxisSpec != null) child.putString(LivePlotComposite.MEMENTO_XYDATA_YAXISNAME, yAxisSpec.getName()); return archivedFilename; } private String deriveScanIdentifier(String name2) { //name is of type Scan:<number>_<name> if(name2.startsWith("Scan:")){ int spaceAfterScanName = name2.indexOf(" "); return name2.substring(5, spaceAfterScanName); } throw new IllegalArgumentException("Name of plot line is invalid " + name2); } public void setsPointsForLine(DoubleDataset xData, DoubleDataset yData, String archiveFolder) { unarchive(archiveFolder); // we need ensure AxisValues are all increasing double[] xdata = xData.getData().clone(); double[] ydata = yData.getData().clone(); if (xdata.length == ydata.length) { for (int i = xdata.length - 1; i > 1; i--) { for (int j = 0; j < i; j++) { if (xdata[j] > xdata[i]) { double tmp = xdata[i]; xdata[i] = xdata[j]; xdata[j] = tmp; tmp = ydata[i]; ydata[i] = ydata[j]; ydata[j] = tmp; } } } DoubleDataset dds = new DoubleDataset(ydata); dds.setName(name); archive.setData(new AxisValues(xdata), new DoubleDataset(ydata)); number = archive.getxAxis().size(); } } protected Plot1DAppearance getAppearanceCopy(String archiveFolder) { unarchive(archiveFolder); if (archive!=null) { Plot1DAppearance appearance = archive.getAppearance(); return new Plot1DAppearance(appearance.getColour(), appearance.getStyle(), appearance.getLineWidth(), appearance.getName()); } return null; } public void setVisible(boolean visibility, String archiveFolder) { if (visibility) { // if we are to maek visible then unarchive unarchive(archiveFolder); } if (archive != null) { archive.getAppearance().setVisible(visibility); } } void unarchive(String archiveFolder) { try { if (archiveFilename != null) { String archiveFilenameCopy = getArchivePath(archiveFolder, archiveFilename); logger.info("XYData.unarchive from " + archiveFilename); FileInputStream f_in = null; ObjectInputStream obj_in = null; try { f_in = new FileInputStream(archiveFilenameCopy); obj_in = new ObjectInputStream(f_in); Object obj = obj_in.readObject(); if (!(obj instanceof LiveDataArchive)) return; // From scan data view, cannot deal with archive = (LiveDataArchive) obj; number = archive.getxAxis().size(); archiveFilename = null; } finally { if (obj_in != null) obj_in.close(); if (f_in != null){ f_in.close(); if(archiveFilename==null){ File f = new File(archiveFilenameCopy); f.delete(); } } } } } catch (Exception e) { logger.warn("Error unarchiving plot data", e); archiveFilename = null; resetArchive(which); } } void archive(String archiveFolder) { try { if (archiveFilename == null) { persistToFilePath( archiveFolder, getArchiveFilename()); archiveFilename = getArchiveFilename();//archivedFilePath; archive = null; logger.info("XYData.archive to " + archiveFilename); } } catch (Exception ex) { logger.warn(ex.getMessage(), ex); } } private void resetArchive(int which) { Plot1DAppearance appearance = new Plot1DAppearance(LivePlotComposite.getColour(which), LivePlotComposite.getStyle(which), LivePlotComposite.getLineWidth(), name); archive = new LiveDataArchive(appearance, new DoubleDataset(1), new AxisValues()); archiveFilename=null; } private static String getArchivePath(String archiveFolder, String filename){ return archiveFolder + System.getProperty("file.separator") + filename; } private String persistToFilePath(String archiveFolder, String target_filename) throws IOException { // create a unique file in the workspace String archivedFilePath = getArchivePath(archiveFolder, target_filename); if( this.isArchived()){ FileUtil.copy(archiveFolder + File.separator + this.archiveFilename, archivedFilePath); } else { File file = new File(archivedFilePath); file.createNewFile(); persistToFile(new File(archivedFilePath)); } return archivedFilePath; } private void persistToFile(File tempFile) throws FileNotFoundException, IOException { //if already archived simply copy into new file FileOutputStream f_out = null; ObjectOutputStream obj_out = null; try { f_out = new FileOutputStream(tempFile); obj_out = new ObjectOutputStream(f_out); obj_out.writeObject(archive); obj_out.flush(); obj_out.reset(); // if not you get an OuOfMemoryException eventually } finally { if (obj_out != null) obj_out.close(); if (f_out != null) f_out.close(); } } void setLineColor(Color color, String archiveFolder) { unarchive(archiveFolder); archive.getAppearance().setColour(color); } void setPlot1DStyles(Plot1DStyles style, String archiveFolder) { unarchive(archiveFolder); archive.getAppearance().setStyle(style); } void setLineWidth(int width, String archiveFolder) { unarchive(archiveFolder); archive.getAppearance().setLineWidth(width); } Color getLineColor(String archiveFolder) { unarchive(archiveFolder); return archive.getAppearance().getColour(); } boolean isVisible() { return archive != null ? archive.getAppearance().isVisible() : false; } /* * Values in AxisValues must always go from min to max. */ void addPointToLine(double x, double y) { // get existing 'old' values DoubleDataset dataset = archive.getxAxis().toDataset(); double[] xvals_old = dataset != null ? dataset.getData() : new double[0]; double[] yvals_old = archive.getyVals().getData(); double[] yvals_new = null; double[] xvals_new = null; int old_length = xvals_old.length; if (old_length == 0) { // first point yvals_new = new double[] { y }; xvals_new = new double[] { x }; } else { // not first so copy old to new before adding to end or inserting yvals_new = Arrays.copyOf(yvals_old, old_length + 1); xvals_new = Arrays.copyOf(xvals_old, old_length + 1); if (x >= xvals_new[old_length - 1]) { // add to the end xvals_new[old_length] = x; yvals_new[old_length] = y; } else { // insert at correct point boolean added = false; for (int x_index = 0; x_index < old_length; x_index++) { if (x < xvals_old[x_index]) { // shift and insert // find position in x axis at which to insert the new value ( x values must increase through the // array) // shift existing values up by 1 to make space to insert the new value // if x_index = 1 and old_length = 10 this will shift items 1 to 2 for 9 elements and insert the // new val at 0 int length = old_length - x_index; System.arraycopy(xvals_new, x_index, xvals_new, x_index + 1, length); System.arraycopy(yvals_new, x_index, yvals_new, x_index + 1, length); yvals_new[x_index] = y; xvals_new[x_index] = x; added = true; break; } } if (!added) { logger.warn("Cannot find point to insert the new point - should not happen"); } } } // create new AxisValues and DataSet final DoubleDataset yds = new DoubleDataset(yvals_new); yds.setName(name); archive.setData(new AxisValues(xvals_new), yds); number = xvals_new.length; } @Override public String toString() { return name; } } /** * TODO FIXME DO NOT COPY THIS CLASS. THIS IS A TEMPORARY MEASURE TO ALLOW * NEW PLOTTING TO WORK WITH VIEW SIMILAR TO XYPLOTVIEW. BECAUSE OF THE LIMITATIONS * OF THE OLD PLOTTING, THIS CLASS HAS DEPARTED FROM A GOOD DESIGN RELATIVE TO THE * NEW PLOTTING. PLANNED IS A SIMPLER ABSTRACT CLASS OR TOOL TO MONITOR SCANS */ class LiveDataArchive implements Serializable { /** * Change the value of serialVersionUID is items in this class change */ static final long serialVersionUID = 42L; private Plot1DAppearance appearance; private DoubleDataset yVals; private AxisValues xAxis; public LiveDataArchive(Plot1DAppearance appearance, DoubleDataset yVals, AxisValues xAxis) { super(); if (appearance == null || yVals == null || xAxis == null ) throw new IllegalArgumentException("Invalid args"); this.appearance = appearance; this.yVals = yVals; this.xAxis = xAxis; } public void setData(AxisValues axisValues, DoubleDataset doubleDataset) { if (yVals == null || xAxis == null) throw new IllegalArgumentException("Invalid args"); xAxis = axisValues; yVals = doubleDataset; } public Plot1DAppearance getAppearance() { return appearance; } public DoubleDataset getyVals() { return yVals; } public AxisValues getxAxis() { return xAxis; } } class XYLegendActionGroup extends ActionGroup { private LivePlotComposite comp; IWorkbenchWindow window; XYLegendActionGroup(IWorkbenchWindow window, LivePlotComposite comp) { this.comp = comp; this.window = window; } @Override public void fillContextMenu(IMenuManager menu) { super.fillContextMenu(menu); IStructuredSelection selection = (IStructuredSelection) getContext().getSelection(); boolean anyResourceSelected = !selection.isEmpty(); if (anyResourceSelected) { addNewWindowAction(menu, selection); } } /** * Adds the Open in New Window action to the context menu. * * @param menu * the context menu * @param selection * the current selection */ private void addNewWindowAction(IMenuManager menu, IStructuredSelection selection) { // Only supported if exactly one container (i.e open project or folder) is selected. if (selection.size() != 1) { return; } Object element = selection.getFirstElement(); if (element instanceof ScanPair) { menu.add(new EditAppearanceAction(window, comp, (ScanPair) element)); } } } class EditAppearanceAction extends Action implements ActionFactory.IWorkbenchAction { /** * The workbench window; or <code>null</code> if this action has been <code>dispose</code>d. */ private IWorkbenchWindow workbenchWindow; private ScanPair pageInput; LivePlotComposite comp; public EditAppearanceAction(IWorkbenchWindow window, LivePlotComposite comp, ScanPair copy) { super("Modify Appearance"); if (window == null) { throw new IllegalArgumentException(); } this.workbenchWindow = window; setToolTipText("Modify Appearance"); this.comp = comp; pageInput = copy; // window.getWorkbench().getHelpSystem().setHelp(this, IWorkbenchHelpContextIds.OPEN_NEW_WINDOW_ACTION); } /** * The implementation of this <code>IAction</code> method opens a new window. The initial perspective for the new * window will be the same type as the active perspective in the window which this action is running in. */ @Override public void run() { if (workbenchWindow == null) { // action has been disposed return; } Plot1DGraphTable colourTable = new Plot1DGraphTable(); int lineNumber = pageInput.getLineNumber(); Plot1DAppearance copy = comp.plotView.getAppearanceCopy(lineNumber); colourTable.addEntryOnLegend(copy); PlotAppearanceDialog pad = new PlotAppearanceDialog(workbenchWindow.getShell(), colourTable); boolean success = pad.open(); if (success) { // set linewidth and style directly, set color via the legend which will cause a plot update comp.plotView.setLineWidth(lineNumber, copy.getLineWidth()); comp.plotView.setPlot1DStyles(lineNumber, copy.getStyle()); ScanLine line = pageInput.getScanLineCopy(); line.lineColor = copy.getColour(); comp.legend.valueForPathChanged(new TreePath(pageInput.getPath()), line); } } /* * (non-Javadoc) Method declared on ActionFactory.IWorkbenchAction. * @since 3.0 */ @Override public void dispose() { workbenchWindow = null; } }
false
true
private void createUpdatePlot(String xLabelIn, String yLabelIn, final List<LineData> xys, final List<String> invis, boolean additionalYAxes) { final String xLabel = xLabelIn != null ? xLabelIn : UNKNOWN; final String yLabel = yLabelIn != null ? yLabelIn : UNKNOWN; final String title = (additionalYAxes ? "various" : yLabel) + " / " + xLabel; Display.getDefault().syncExec(new Runnable() { @Override public void run() { plottingSystem.reset(); //remove all axes plottingSystem.setTitle(title); plottingSystem.getSelectedXAxis().setTitle(xLabel); plottingSystem.getSelectedYAxis().setTitle(yLabel); IAxis defaultYAxis = null; for(IAxis axis : plottingSystem.getAxes()){ if( axis.isPrimaryAxis() && axis.isYAxis()){ defaultYAxis = axis; defaultYAxis.setVisible(!yLabel.equals(UNKNOWN)); break; } } for(IAxis axis : plottingSystem.getAxes()){ if( !axis.isPrimaryAxis()) plottingSystem.removeAxis(axis); } for (final LineData ld : xys) { AbstractDataset y = ld.getY(); String name = y.getName(); if (name==null || "".equals(name)) { logger.error("y dataset is not named - it should be!"); } AxisSpec axisSpec = ld.getyAxisSpec(); String yAxisName = axisSpec != null ? axisSpec.getName(): null; if( yAxisName != null){ IAxis extraYAxis = null; for(IAxis axis : plottingSystem.getAxes()){ String title2 = axis.getTitle(); if( title2 != null && title2.equals(yAxisName)){ extraYAxis = axis; break; } } if( extraYAxis == null){ extraYAxis = plottingSystem.createAxis(yAxisName, true, SWT.LEFT); } plottingSystem.setSelectedYAxis( extraYAxis); } else { plottingSystem.setSelectedYAxis( defaultYAxis); } ILineTrace trace = plottingSystem.createLineTrace(name); trace.setLineWidth(ld.appearance.getLineWidth()); trace.setPointSize(3); switch(ld.getAppearance().getStyle()){ case DASHED: trace.setPointStyle(PointStyle.NONE); trace.setTraceType(TraceType.DASH_LINE); break; case DASHED_POINT: trace.setPointStyle(PointStyle.DIAMOND); trace.setTraceType(TraceType.DASH_LINE); break; case SOLID: trace.setPointStyle(PointStyle.NONE); trace.setTraceType(TraceType.SOLID_LINE); break; case SOLID_POINT: trace.setPointStyle(PointStyle.DIAMOND); trace.setTraceType(TraceType.SOLID_LINE); break; case POINT: trace.setPointStyle(PointStyle.DIAMOND); trace.setTraceType(TraceType.POINT); } final Color color = ld.getAppearance().getColour(); trace.setTraceColor(new org.eclipse.swt.graphics.Color(null, color.getRed(), color.getGreen(), color.getBlue())); trace.setData(ld.getX(), ld.getY()); plottingSystem.addTrace(trace); plottingSystem.setSelectedYAxis( defaultYAxis); } /** * BODGE WARNING There is no clear start of scan or start of new plot in * XYDataHandler. Instead we deduce that anything not visible should be removed. */ for (String traceName : invis) { ITrace trace = plottingSystem.getTrace(traceName); if (trace!=null) plottingSystem.removeTrace(trace); } if (plottingSystem.isRescale()) { plottingSystem.autoscaleAxes(); } } }); }
private void createUpdatePlot(String xLabelIn, String yLabelIn, final List<LineData> xys, final List<String> invis, boolean additionalYAxes) { final String xLabel = xLabelIn != null ? xLabelIn : UNKNOWN; final String yLabel = yLabelIn != null ? yLabelIn : UNKNOWN; final String title = (additionalYAxes ? "various" : yLabel) + " / " + xLabel; Display.getDefault().syncExec(new Runnable() { @Override public void run() { plottingSystem.reset(); //remove all axes plottingSystem.setTitle(title); plottingSystem.getSelectedXAxis().setTitle(xLabel); plottingSystem.getSelectedYAxis().setTitle(yLabel); IAxis defaultYAxis = null; for(IAxis axis : plottingSystem.getAxes()){ if( axis.isPrimaryAxis() && axis.isYAxis()){ defaultYAxis = axis; defaultYAxis.setVisible(!yLabel.equals(UNKNOWN)); break; } } for(IAxis axis : plottingSystem.getAxes()){ if( !axis.isPrimaryAxis()) plottingSystem.removeAxis(axis); } for (final LineData ld : xys) { AbstractDataset y = ld.getY(); String name = y.getName(); if (name==null || "".equals(name)) { logger.error("y dataset is not named - it should be!"); } AxisSpec axisSpec = ld.getyAxisSpec(); String yAxisName = axisSpec != null ? axisSpec.getName(): null; if( yAxisName != null){ IAxis extraYAxis = null; for(IAxis axis : plottingSystem.getAxes()){ String title2 = axis.getTitle(); if( title2 != null && title2.equals(yAxisName)){ extraYAxis = axis; break; } } if( extraYAxis == null){ extraYAxis = plottingSystem.createAxis(yAxisName, true, SWT.LEFT); } plottingSystem.setSelectedYAxis( extraYAxis); } else { plottingSystem.setSelectedYAxis( defaultYAxis); } ILineTrace trace = plottingSystem.createLineTrace(name); trace.setLineWidth(ld.appearance.getLineWidth()); trace.setPointSize(3); switch(ld.getAppearance().getStyle()){ case DASHED: trace.setPointStyle(PointStyle.NONE); trace.setTraceType(ILineTrace.TraceType.DASH_LINE); break; case DASHED_POINT: trace.setPointStyle(PointStyle.DIAMOND); trace.setTraceType(ILineTrace.TraceType.DASH_LINE); break; case SOLID: trace.setPointStyle(PointStyle.NONE); trace.setTraceType(ILineTrace.TraceType.SOLID_LINE); break; case SOLID_POINT: trace.setPointStyle(PointStyle.DIAMOND); trace.setTraceType(ILineTrace.TraceType.SOLID_LINE); break; case POINT: trace.setPointStyle(PointStyle.DIAMOND); trace.setTraceType(ILineTrace.TraceType.POINT); } final Color color = ld.getAppearance().getColour(); trace.setTraceColor(new org.eclipse.swt.graphics.Color(null, color.getRed(), color.getGreen(), color.getBlue())); trace.setData(ld.getX(), ld.getY()); plottingSystem.addTrace(trace); plottingSystem.setSelectedYAxis( defaultYAxis); } /** * BODGE WARNING There is no clear start of scan or start of new plot in * XYDataHandler. Instead we deduce that anything not visible should be removed. */ for (String traceName : invis) { ITrace trace = plottingSystem.getTrace(traceName); if (trace!=null) plottingSystem.removeTrace(trace); } if (plottingSystem.isRescale()) { plottingSystem.autoscaleAxes(); } } }); }
diff --git a/src/com/google/caliper/ConsoleReport.java b/src/com/google/caliper/ConsoleReport.java index 3bd8bb3..139ab92 100644 --- a/src/com/google/caliper/ConsoleReport.java +++ b/src/com/google/caliper/ConsoleReport.java @@ -1,232 +1,238 @@ /** * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.caliper; import com.google.common.collect.*; import java.util.*; /** * Prints a report containing the tested values and the corresponding * measurements. Measurements are grouped by variable using indentation. * Alongside numeric values, quick-glance ascii art bar charts are printed. * Sample output: * <pre> * benchmark d ns logarithmic runtime * ConcatenationBenchmark 3.141592653589793 4397 |||||||||||||||||||||||| * ConcatenationBenchmark -0.0 223 ||||||||||||||| * FormatterBenchmark 3.141592653589793 33999 |||||||||||||||||||||||||||||| * FormatterBenchmark -0.0 26399 ||||||||||||||||||||||||||||| * </pre> */ final class ConsoleReport { private static final int bargraphWidth = 30; private static final String benchmarkKey = "benchmark"; private final List<Parameter> parameters; private final Result result; private final List<Run> runs; private final double logMaxValue; private final int decimalDigits; private final double divideBy; private final String units; private final int measurementColumnLength; public ConsoleReport(Result result) { this.result = result; double minValue = Double.POSITIVE_INFINITY; double maxValue = 0; Multimap<String, String> nameToValues = LinkedHashMultimap.create(); List<Parameter> parametersBuilder = new ArrayList<Parameter>(); for (Map.Entry<Run, Double> entry : result.getMeasurements().entrySet()) { Run run = entry.getKey(); double d = entry.getValue(); minValue = minValue < d ? minValue : d; maxValue = maxValue > d ? maxValue : d; for (Map.Entry<String, String> parameter : run.getParameters().entrySet()) { String name = parameter.getKey(); nameToValues.put(name, parameter.getValue()); } nameToValues.put(benchmarkKey, run.getBenchmarkClass().getSimpleName()); } for (Map.Entry<String, Collection<String>> entry : nameToValues.asMap().entrySet()) { Parameter parameter = new Parameter(entry.getKey(), entry.getValue()); parametersBuilder.add(parameter); } for (Parameter parameter : parametersBuilder) { double[] measurements = new double[parameter.values.size()]; for (Map.Entry<Run, Double> entry : result.getMeasurements().entrySet()) { Run run = entry.getKey(); measurements[parameter.index(run)] += entry.getValue(); } + double total = 0; + for (double value : measurements) { + total += value; + } + double mean = total / measurements.length; double sum = 0; for (double value : measurements) { - sum += value; + double distance = value - mean; + sum += distance * distance; } parameter.stdDeviation = Math.sqrt(sum / measurements.length); } this.parameters = new StandardDeviationOrdering().reverse().sortedCopy(parametersBuilder); this.runs = new ByParametersOrdering().sortedCopy(result.getMeasurements().keySet()); this.logMaxValue = Math.log(maxValue); int numDigitsInMin = (int) Math.ceil(Math.log10(minValue)); if (numDigitsInMin > 9) { divideBy = 1000000000; decimalDigits = Math.max(0, 9 + 3 - numDigitsInMin); units = "s"; } else if (numDigitsInMin > 6) { divideBy = 1000000; decimalDigits = Math.max(0, 6 + 3 - numDigitsInMin); units = "ms"; } else if (numDigitsInMin > 3) { divideBy = 1000; decimalDigits = Math.max(0, 3 + 3 - numDigitsInMin); units = "us"; } else { divideBy = 1; decimalDigits = 0; units = "ns"; } measurementColumnLength = (int) Math.ceil(Math.log10(maxValue / divideBy)) + decimalDigits + 1; } /** * A parameter plus all of its values. */ static class Parameter { final String name; final ImmutableList<String> values; final int maxLength; double stdDeviation; public Parameter(String name, Collection<String> values) { this.name = name; this.values = ImmutableList.copyOf(values); int maxLength = name.length(); for (String value : values) { maxLength = Math.max(maxLength, value.length()); } this.maxLength = maxLength; } String get(Run run) { return benchmarkKey.equals(name) ? run.getBenchmarkClass().getSimpleName() : run.getParameters().get(name); } int index(Run run) { return values.indexOf(get(run)); } boolean isInteresting() { return values.size() > 1; } } /** * Orders the different parameters by their standard deviation. This results * in an appropriate grouping of output values. */ static class StandardDeviationOrdering extends Ordering<Parameter> { public int compare(Parameter a, Parameter b) { return Double.compare(a.stdDeviation, b.stdDeviation); } } /** * Orders runs by the parameters. */ class ByParametersOrdering extends Ordering<Run> { public int compare(Run a, Run b) { for (Parameter parameter : parameters) { int aValue = parameter.values.indexOf(parameter.get(a)); int bValue = parameter.values.indexOf(parameter.get(b)); int diff = aValue - bValue; if (diff != 0) { return diff; } } return 0; } } void displayResults() { printValues(); System.out.println(); printUninterestingParameters(); } /** * Prints a table of values. */ private void printValues() { for (Parameter parameter : parameters) { if (parameter.isInteresting()) { System.out.printf("%" + parameter.maxLength + "s ", parameter.name); } } System.out.printf("%" + measurementColumnLength + "s logarithmic runtime%n", units); String numbersFormat = "%" + measurementColumnLength + "." + decimalDigits + "f %s%n"; for (Run run : runs) { for (Parameter parameter : parameters) { if (parameter.isInteresting()) { System.out.printf("%" + parameter.maxLength + "s ", parameter.get(run)); } } double measurement = result.getMeasurements().get(run); System.out.printf(numbersFormat, measurement / divideBy, bargraph(measurement)); } } /** * Prints parameters with only one unique value. */ private void printUninterestingParameters() { for (Parameter parameter : parameters) { if (!parameter.isInteresting()) { System.out.println(parameter.name + ": " + Iterables.getOnlyElement(parameter.values)); } } } /** * Returns a string containing a bar of proportional width to the specified * value. */ private String bargraph(double value) { double logValue = Math.log(value); int numChars = (int) ((logValue / logMaxValue) * bargraphWidth); StringBuilder result = new StringBuilder(numChars); for (int i = 0; i < numChars; i++) { result.append("|"); } return result.toString(); } }
false
true
public ConsoleReport(Result result) { this.result = result; double minValue = Double.POSITIVE_INFINITY; double maxValue = 0; Multimap<String, String> nameToValues = LinkedHashMultimap.create(); List<Parameter> parametersBuilder = new ArrayList<Parameter>(); for (Map.Entry<Run, Double> entry : result.getMeasurements().entrySet()) { Run run = entry.getKey(); double d = entry.getValue(); minValue = minValue < d ? minValue : d; maxValue = maxValue > d ? maxValue : d; for (Map.Entry<String, String> parameter : run.getParameters().entrySet()) { String name = parameter.getKey(); nameToValues.put(name, parameter.getValue()); } nameToValues.put(benchmarkKey, run.getBenchmarkClass().getSimpleName()); } for (Map.Entry<String, Collection<String>> entry : nameToValues.asMap().entrySet()) { Parameter parameter = new Parameter(entry.getKey(), entry.getValue()); parametersBuilder.add(parameter); } for (Parameter parameter : parametersBuilder) { double[] measurements = new double[parameter.values.size()]; for (Map.Entry<Run, Double> entry : result.getMeasurements().entrySet()) { Run run = entry.getKey(); measurements[parameter.index(run)] += entry.getValue(); } double sum = 0; for (double value : measurements) { sum += value; } parameter.stdDeviation = Math.sqrt(sum / measurements.length); } this.parameters = new StandardDeviationOrdering().reverse().sortedCopy(parametersBuilder); this.runs = new ByParametersOrdering().sortedCopy(result.getMeasurements().keySet()); this.logMaxValue = Math.log(maxValue); int numDigitsInMin = (int) Math.ceil(Math.log10(minValue)); if (numDigitsInMin > 9) { divideBy = 1000000000; decimalDigits = Math.max(0, 9 + 3 - numDigitsInMin); units = "s"; } else if (numDigitsInMin > 6) { divideBy = 1000000; decimalDigits = Math.max(0, 6 + 3 - numDigitsInMin); units = "ms"; } else if (numDigitsInMin > 3) { divideBy = 1000; decimalDigits = Math.max(0, 3 + 3 - numDigitsInMin); units = "us"; } else { divideBy = 1; decimalDigits = 0; units = "ns"; } measurementColumnLength = (int) Math.ceil(Math.log10(maxValue / divideBy)) + decimalDigits + 1; }
public ConsoleReport(Result result) { this.result = result; double minValue = Double.POSITIVE_INFINITY; double maxValue = 0; Multimap<String, String> nameToValues = LinkedHashMultimap.create(); List<Parameter> parametersBuilder = new ArrayList<Parameter>(); for (Map.Entry<Run, Double> entry : result.getMeasurements().entrySet()) { Run run = entry.getKey(); double d = entry.getValue(); minValue = minValue < d ? minValue : d; maxValue = maxValue > d ? maxValue : d; for (Map.Entry<String, String> parameter : run.getParameters().entrySet()) { String name = parameter.getKey(); nameToValues.put(name, parameter.getValue()); } nameToValues.put(benchmarkKey, run.getBenchmarkClass().getSimpleName()); } for (Map.Entry<String, Collection<String>> entry : nameToValues.asMap().entrySet()) { Parameter parameter = new Parameter(entry.getKey(), entry.getValue()); parametersBuilder.add(parameter); } for (Parameter parameter : parametersBuilder) { double[] measurements = new double[parameter.values.size()]; for (Map.Entry<Run, Double> entry : result.getMeasurements().entrySet()) { Run run = entry.getKey(); measurements[parameter.index(run)] += entry.getValue(); } double total = 0; for (double value : measurements) { total += value; } double mean = total / measurements.length; double sum = 0; for (double value : measurements) { double distance = value - mean; sum += distance * distance; } parameter.stdDeviation = Math.sqrt(sum / measurements.length); } this.parameters = new StandardDeviationOrdering().reverse().sortedCopy(parametersBuilder); this.runs = new ByParametersOrdering().sortedCopy(result.getMeasurements().keySet()); this.logMaxValue = Math.log(maxValue); int numDigitsInMin = (int) Math.ceil(Math.log10(minValue)); if (numDigitsInMin > 9) { divideBy = 1000000000; decimalDigits = Math.max(0, 9 + 3 - numDigitsInMin); units = "s"; } else if (numDigitsInMin > 6) { divideBy = 1000000; decimalDigits = Math.max(0, 6 + 3 - numDigitsInMin); units = "ms"; } else if (numDigitsInMin > 3) { divideBy = 1000; decimalDigits = Math.max(0, 3 + 3 - numDigitsInMin); units = "us"; } else { divideBy = 1; decimalDigits = 0; units = "ns"; } measurementColumnLength = (int) Math.ceil(Math.log10(maxValue / divideBy)) + decimalDigits + 1; }
diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/Parallel.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/Parallel.java index 00cbeef16..959004ca4 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/Parallel.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/Parallel.java @@ -1,102 +1,105 @@ /******************************************************************************* * 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.actions; import com.badlogic.gdx.scenes.scene2d.Action; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.CompositeAction; public class Parallel extends CompositeAction { static final ActionResetingPool<Parallel> pool = new ActionResetingPool<Parallel>(4, 100) { @Override protected Parallel newObject () { return new Parallel(); } }; protected boolean[] finished; protected Actor target = null; public static Parallel $ (Action... actions) { Parallel parallel = pool.obtain(); parallel.actions.clear(); if (parallel.finished == null || parallel.finished.length < actions.length) parallel.finished = new boolean[actions.length]; int len = actions.length; for (int i = 0; i < len; i++) parallel.finished[i] = false; len = actions.length; for (int i = 0; i < len; i++) parallel.actions.add(actions[i]); return parallel; } @Override public void setTarget (Actor actor) { this.target = actor; int len = actions.size(); for (int i = 0; i < len; i++) actions.get(i).setTarget(actor); } @Override public void act (float delta) { int len = actions.size(); boolean allDone = true; + Action action; for (int i = 0; i < len; i++) { - if (!actions.get(i).isDone()) { - actions.get(i).act(delta); + action = actions.get(i); + if (!action.isDone()) { + action.act(delta); + allDone = false; } else { if (!finished[i]) { - actions.get(i).finish(); + action.finish(); finished[i] = true; + allDone &= finished[i]; } - allDone &= finished[i]; } } if(allDone) callActionCompletedListener(); } @Override public boolean isDone () { int len = actions.size(); for (int i = 0; i < len; i++) if (actions.get(i).isDone() == false) return false; return true; } @Override public void finish () { pool.free(this); int len = actions.size(); for (int i = 0; i < len; i++) { if (!finished[i]) actions.get(i).finish(); } super.finish(); } @Override public Action copy () { Parallel parallel = pool.obtain(); parallel.actions.clear(); if (parallel.finished == null || parallel.finished.length < actions.size()) parallel.finished = new boolean[actions.size()]; int len = actions.size(); for (int i = 0; i < len; i++) parallel.finished[i] = false; len = actions.size(); for (int i = 0; i < len; i++) parallel.actions.add(actions.get(i).copy()); return parallel; } @Override public Actor getTarget () { return target; } }
false
true
@Override public void act (float delta) { int len = actions.size(); boolean allDone = true; for (int i = 0; i < len; i++) { if (!actions.get(i).isDone()) { actions.get(i).act(delta); } else { if (!finished[i]) { actions.get(i).finish(); finished[i] = true; } allDone &= finished[i]; } } if(allDone) callActionCompletedListener(); }
@Override public void act (float delta) { int len = actions.size(); boolean allDone = true; Action action; for (int i = 0; i < len; i++) { action = actions.get(i); if (!action.isDone()) { action.act(delta); allDone = false; } else { if (!finished[i]) { action.finish(); finished[i] = true; allDone &= finished[i]; } } } if(allDone) callActionCompletedListener(); }
diff --git a/org.eclipse.mylyn.tests/src/org/eclipse/mylyn/tests/integration/LiveWebConnectorTemplatesTest.java b/org.eclipse.mylyn.tests/src/org/eclipse/mylyn/tests/integration/LiveWebConnectorTemplatesTest.java index c5965ea..eb94e43 100644 --- a/org.eclipse.mylyn.tests/src/org/eclipse/mylyn/tests/integration/LiveWebConnectorTemplatesTest.java +++ b/org.eclipse.mylyn.tests/src/org/eclipse/mylyn/tests/integration/LiveWebConnectorTemplatesTest.java @@ -1,130 +1,129 @@ /******************************************************************************* * Copyright (c) 2006 - 2006 Mylar eclipse.org project 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: * Mylar project committers - initial API and implementation *******************************************************************************/ package org.eclipse.mylyn.tests.integration; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import junit.extensions.ActiveTestSuite; import junit.framework.TestCase; import junit.framework.TestSuite; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.MultiStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.mylyn.internal.web.tasks.WebRepositoryConnector; import org.eclipse.mylyn.internal.web.tasks.WebTask; import org.eclipse.mylyn.tasks.core.AbstractRepositoryConnector; import org.eclipse.mylyn.tasks.core.AbstractTask; import org.eclipse.mylyn.tasks.core.ITaskFactory; import org.eclipse.mylyn.tasks.core.QueryHitCollector; import org.eclipse.mylyn.tasks.core.RepositoryTaskData; import org.eclipse.mylyn.tasks.core.RepositoryTemplate; import org.eclipse.mylyn.tasks.core.TaskRepository; import org.eclipse.mylyn.tasks.ui.TasksUiPlugin; /** * @author Eugene Kuleshov */ public class LiveWebConnectorTemplatesTest extends TestCase { private final RepositoryTemplate template; public LiveWebConnectorTemplatesTest(RepositoryTemplate template) { super("testRepositoryTemplate"); this.template = template; } public void testRepositoryTemplate() throws Throwable { IProgressMonitor monitor = new NullProgressMonitor(); MultiStatus queryStatus = new MultiStatus(TasksUiPlugin.PLUGIN_ID, IStatus.OK, "Query result", null); final List<AbstractTask> hits = new ArrayList<AbstractTask>(); QueryHitCollector collector = new QueryHitCollector(TasksUiPlugin.getTaskListManager().getTaskList(), new ITaskFactory() { - public AbstractTask createTask(RepositoryTaskData taskData, boolean synchData, - boolean forced, IProgressMonitor monitor) throws CoreException { + public AbstractTask createTask(RepositoryTaskData taskData, IProgressMonitor monitor) throws CoreException { // ignore return null; } }) { @Override public void accept(AbstractTask hit) { hits.add(hit); } }; Map<String, String> params = new HashMap<String, String>(); Map<String, String> attributes = new HashMap<String, String>(template.getAttributes()); for (Map.Entry<String, String> e : attributes.entrySet()) { String key = e.getKey(); // if(key.startsWith(WebRepositoryConnector.PARAM_PREFIX)) { params.put(key, e.getValue()); // } } TaskRepository repository = new TaskRepository(WebTask.REPOSITORY_TYPE, template.repositoryUrl, params); String url = repository.getUrl(); // HACK: repositories that require auth if ("http://demo.otrs.org".equals(url)) { repository.setAuthenticationCredentials("skywalker", "skywalker"); } else if ("http://changelogic.araneaframework.org".equals(url)) { repository.setAuthenticationCredentials("mylar2", "mylar123"); } String taskQueryUrl = WebRepositoryConnector.evaluateParams(template.taskQueryUrl, repository); String buffer = WebRepositoryConnector.fetchResource(taskQueryUrl, params, repository); assertTrue("Unable to fetch resource\n" + taskQueryUrl, buffer != null && buffer.length() > 0); String regexp = WebRepositoryConnector.evaluateParams(template .getAttribute(WebRepositoryConnector.PROPERTY_QUERY_REGEXP), repository); IStatus resultingStatus = WebRepositoryConnector.performQuery(buffer, regexp, null, monitor, collector, repository); assertTrue("Query failed\n" + taskQueryUrl + "\n" + regexp + "\n" + resultingStatus.toString(), queryStatus .isOK()); try { assertTrue("Expected non-empty query result\n" + taskQueryUrl + "\n" + regexp, hits.size() > 0); } catch (Throwable t) { System.err.println(taskQueryUrl); System.err.println(buffer); System.err.println("--------------------------------------------------------"); throw t; } } @Override public String getName() { return template.label; } private static final String excluded = "http://demo.otrs.org,"; public static TestSuite suite() { TestSuite suite = new ActiveTestSuite(LiveWebConnectorTemplatesTest.class.getName()); AbstractRepositoryConnector repositoryConnector = TasksUiPlugin.getRepositoryManager().getRepositoryConnector( WebTask.REPOSITORY_TYPE); for (RepositoryTemplate template : repositoryConnector.getTemplates()) { if (excluded.indexOf(template.repositoryUrl + ",") == -1) { suite.addTest(new LiveWebConnectorTemplatesTest(template)); } } return suite; } }
true
true
public void testRepositoryTemplate() throws Throwable { IProgressMonitor monitor = new NullProgressMonitor(); MultiStatus queryStatus = new MultiStatus(TasksUiPlugin.PLUGIN_ID, IStatus.OK, "Query result", null); final List<AbstractTask> hits = new ArrayList<AbstractTask>(); QueryHitCollector collector = new QueryHitCollector(TasksUiPlugin.getTaskListManager().getTaskList(), new ITaskFactory() { public AbstractTask createTask(RepositoryTaskData taskData, boolean synchData, boolean forced, IProgressMonitor monitor) throws CoreException { // ignore return null; } }) { @Override public void accept(AbstractTask hit) { hits.add(hit); } }; Map<String, String> params = new HashMap<String, String>(); Map<String, String> attributes = new HashMap<String, String>(template.getAttributes()); for (Map.Entry<String, String> e : attributes.entrySet()) { String key = e.getKey(); // if(key.startsWith(WebRepositoryConnector.PARAM_PREFIX)) { params.put(key, e.getValue()); // } } TaskRepository repository = new TaskRepository(WebTask.REPOSITORY_TYPE, template.repositoryUrl, params); String url = repository.getUrl(); // HACK: repositories that require auth if ("http://demo.otrs.org".equals(url)) { repository.setAuthenticationCredentials("skywalker", "skywalker"); } else if ("http://changelogic.araneaframework.org".equals(url)) { repository.setAuthenticationCredentials("mylar2", "mylar123"); } String taskQueryUrl = WebRepositoryConnector.evaluateParams(template.taskQueryUrl, repository); String buffer = WebRepositoryConnector.fetchResource(taskQueryUrl, params, repository); assertTrue("Unable to fetch resource\n" + taskQueryUrl, buffer != null && buffer.length() > 0); String regexp = WebRepositoryConnector.evaluateParams(template .getAttribute(WebRepositoryConnector.PROPERTY_QUERY_REGEXP), repository); IStatus resultingStatus = WebRepositoryConnector.performQuery(buffer, regexp, null, monitor, collector, repository); assertTrue("Query failed\n" + taskQueryUrl + "\n" + regexp + "\n" + resultingStatus.toString(), queryStatus .isOK()); try { assertTrue("Expected non-empty query result\n" + taskQueryUrl + "\n" + regexp, hits.size() > 0); } catch (Throwable t) { System.err.println(taskQueryUrl); System.err.println(buffer); System.err.println("--------------------------------------------------------"); throw t; } }
public void testRepositoryTemplate() throws Throwable { IProgressMonitor monitor = new NullProgressMonitor(); MultiStatus queryStatus = new MultiStatus(TasksUiPlugin.PLUGIN_ID, IStatus.OK, "Query result", null); final List<AbstractTask> hits = new ArrayList<AbstractTask>(); QueryHitCollector collector = new QueryHitCollector(TasksUiPlugin.getTaskListManager().getTaskList(), new ITaskFactory() { public AbstractTask createTask(RepositoryTaskData taskData, IProgressMonitor monitor) throws CoreException { // ignore return null; } }) { @Override public void accept(AbstractTask hit) { hits.add(hit); } }; Map<String, String> params = new HashMap<String, String>(); Map<String, String> attributes = new HashMap<String, String>(template.getAttributes()); for (Map.Entry<String, String> e : attributes.entrySet()) { String key = e.getKey(); // if(key.startsWith(WebRepositoryConnector.PARAM_PREFIX)) { params.put(key, e.getValue()); // } } TaskRepository repository = new TaskRepository(WebTask.REPOSITORY_TYPE, template.repositoryUrl, params); String url = repository.getUrl(); // HACK: repositories that require auth if ("http://demo.otrs.org".equals(url)) { repository.setAuthenticationCredentials("skywalker", "skywalker"); } else if ("http://changelogic.araneaframework.org".equals(url)) { repository.setAuthenticationCredentials("mylar2", "mylar123"); } String taskQueryUrl = WebRepositoryConnector.evaluateParams(template.taskQueryUrl, repository); String buffer = WebRepositoryConnector.fetchResource(taskQueryUrl, params, repository); assertTrue("Unable to fetch resource\n" + taskQueryUrl, buffer != null && buffer.length() > 0); String regexp = WebRepositoryConnector.evaluateParams(template .getAttribute(WebRepositoryConnector.PROPERTY_QUERY_REGEXP), repository); IStatus resultingStatus = WebRepositoryConnector.performQuery(buffer, regexp, null, monitor, collector, repository); assertTrue("Query failed\n" + taskQueryUrl + "\n" + regexp + "\n" + resultingStatus.toString(), queryStatus .isOK()); try { assertTrue("Expected non-empty query result\n" + taskQueryUrl + "\n" + regexp, hits.size() > 0); } catch (Throwable t) { System.err.println(taskQueryUrl); System.err.println(buffer); System.err.println("--------------------------------------------------------"); throw t; } }
diff --git a/src/main/java/org/exolab/castor/xml/schema/reader/ImportUnmarshaller.java b/src/main/java/org/exolab/castor/xml/schema/reader/ImportUnmarshaller.java index fd99f2fb..da33cead 100644 --- a/src/main/java/org/exolab/castor/xml/schema/reader/ImportUnmarshaller.java +++ b/src/main/java/org/exolab/castor/xml/schema/reader/ImportUnmarshaller.java @@ -1,227 +1,230 @@ /** * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided * that the following conditions are met: * * 1. Redistributions of source code must retain copyright * statements and notices. Redistributions must also contain a * copy of this document. * * 2. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other * materials provided with the distribution. * * 3. The name "Exolab" must not be used to endorse or promote * products derived from this Software without prior written * permission of Intalio, Inc. For written permission, * please contact [email protected]. * * 4. Products derived from this Software may not be called "Exolab" * nor may "Exolab" appear in their names without prior written * permission of Intalio, Inc. Exolab is a registered * trademark of Intalio, Inc. * * 5. Due credit should be given to the Exolab Project * (http://www.exolab.org/). * * THIS SOFTWARE IS PROVIDED BY INTALIO, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * INTALIO, INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * * Copyright 1999-2004 (C) Intalio, Inc. All Rights Reserved. * * $Id$ */ package org.exolab.castor.xml.schema.reader; //-- imported classes and packages import org.exolab.castor.net.*; import org.exolab.castor.xml.*; import org.exolab.castor.xml.schema.*; import org.xml.sax.*; public class ImportUnmarshaller extends ComponentReader { public ImportUnmarshaller (Schema schema, AttributeSet atts, Resolver resolver, URIResolver uriResolver, Locator locator, SchemaUnmarshallerState state) throws XMLException { super(); setResolver(resolver); setURIResolver(uriResolver); URILocation uri = null; //-- Get schemaLocation String schemaLocation = atts.getValue(SchemaNames.SCHEMALOCATION_ATTR); //-- Get namespace String namespace = atts.getValue("namespace"); if ((schemaLocation == null) && (namespace == null)) { //-- A legal <import/> element...just return return; } boolean hasLocation = (schemaLocation != null); if (schemaLocation != null) { if (schemaLocation.indexOf("\\") != -1) { String err = "'" + schemaLocation + "' is not a valid URI as defined by IETF RFC 2396."; err += "The URI mustn't contain '\\'."; throw new SchemaException(err); } if (namespace == null) namespace = ""; try { String documentBase = locator.getSystemId(); if (documentBase != null) { if (!documentBase.endsWith("/")) documentBase = documentBase.substring(0, documentBase.lastIndexOf('/') +1 ); } uri = getURIResolver().resolve(schemaLocation, documentBase); if (uri != null) { schemaLocation = uri.getAbsoluteURI(); } } catch (URIException urix) { throw new XMLException(urix); } } else { schemaLocation = namespace; try { uri = getURIResolver().resolveURN(namespace); } catch (URIException urix) { throw new XMLException(urix); } if (uri == null) { String err = "Unable to resolve Schema corresponding " + "to namespace '" + namespace + "'."; throw new SchemaException(err); } } //-- Make sure targetNamespace is not the same as the //-- importing schema, see section 4.2.3 in the //-- XML Schema Recommendation if (namespace.equals(schema.getTargetNamespace()) ) throw new SchemaException("the 'namespace' attribute in the <import> element cannot be the same of the targetNamespace of the global schema"); //-- Schema object to hold import schema boolean addSchema = false; Schema importedSchema = schema.getImportedSchema(namespace, true); //-- Have we already imported this XML Schema file? if (state.processed(schemaLocation)) { if (importedSchema == null) schema.addImportedSchema(state.getSchema(schemaLocation)); return; } boolean alreadyLoaded = false; if (importedSchema == null) { if (uri instanceof SchemaLocation) { importedSchema = ((SchemaLocation)uri).getSchema(); schema.addImportedSchema(importedSchema); alreadyLoaded = true; } else { importedSchema = new Schema(); addSchema = true; } } else { - //-- check schema location, if different, allow merge - if (hasLocation) { - String tmpLocation = importedSchema.getSchemaLocation(); - alreadyLoaded = schemaLocation.equals(tmpLocation); - } - else { + // check schema location, if different, allow merge + if (hasLocation) { + String tmpLocation = importedSchema.getSchemaLocation(); + alreadyLoaded = schemaLocation.equals(tmpLocation) || importedSchema.includeProcessed(schemaLocation); + //-- keep track of the original schemaLocation as an include + if(! alreadyLoaded) { + importedSchema.addInclude(tmpLocation); + } + } else { //-- only namespace can be used, no way to distinguish //-- multiple imports...mark as alreadyLoaded //-- see W3C XML Schema 1.0 Recommendation (part 1) //-- section 4.2.3... //-- <quote>... Given that the schemaLocation [attribute] is only //-- a hint, it is open to applications to ignore all but the //-- first <import> for a given namespace, regardless of the //-- <em>actual value</em> of schemaLocation, but such a strategy //-- risks missing useful information when new schemaLocations //-- are offered.</quote> alreadyLoaded = true; } } state.markAsProcessed(schemaLocation, importedSchema); if (alreadyLoaded) return; //-- Parser Schema Parser parser = null; try { parser = state.getConfiguration().getParser(); } catch(RuntimeException rte) {} if (parser == null) { throw new SchemaException("Error failed to create parser for import"); } //-- Create Schema object and setup unmarshaller SchemaUnmarshaller schemaUnmarshaller = new SchemaUnmarshaller(state); schemaUnmarshaller.setURIResolver(getURIResolver()); schemaUnmarshaller.setSchema(importedSchema); Sax2ComponentReader handler = new Sax2ComponentReader(schemaUnmarshaller); parser.setDocumentHandler(handler); parser.setErrorHandler(handler); try { InputSource source = new InputSource(uri.getReader()); source.setSystemId(uri.getAbsoluteURI()); parser.parse(source); } catch(java.io.IOException ioe) { throw new SchemaException("Error reading import file '"+schemaLocation+"': "+ ioe); } catch(org.xml.sax.SAXException sx) { throw new SchemaException(sx); } //-- Add schema to list of imported schemas (if not already present) if (addSchema) { importedSchema.setSchemaLocation(schemaLocation); schema.addImportedSchema(importedSchema); } } /** * Sets the name of the element that this UnknownUnmarshaller handles **/ public String elementName() { return SchemaNames.IMPORT; } //-- elementName /** * Returns the Object created by this ComponentReader * @return the Object created by this ComponentReader **/ public Object getObject() { return null; } //-- getObject }
true
true
public ImportUnmarshaller (Schema schema, AttributeSet atts, Resolver resolver, URIResolver uriResolver, Locator locator, SchemaUnmarshallerState state) throws XMLException { super(); setResolver(resolver); setURIResolver(uriResolver); URILocation uri = null; //-- Get schemaLocation String schemaLocation = atts.getValue(SchemaNames.SCHEMALOCATION_ATTR); //-- Get namespace String namespace = atts.getValue("namespace"); if ((schemaLocation == null) && (namespace == null)) { //-- A legal <import/> element...just return return; } boolean hasLocation = (schemaLocation != null); if (schemaLocation != null) { if (schemaLocation.indexOf("\\") != -1) { String err = "'" + schemaLocation + "' is not a valid URI as defined by IETF RFC 2396."; err += "The URI mustn't contain '\\'."; throw new SchemaException(err); } if (namespace == null) namespace = ""; try { String documentBase = locator.getSystemId(); if (documentBase != null) { if (!documentBase.endsWith("/")) documentBase = documentBase.substring(0, documentBase.lastIndexOf('/') +1 ); } uri = getURIResolver().resolve(schemaLocation, documentBase); if (uri != null) { schemaLocation = uri.getAbsoluteURI(); } } catch (URIException urix) { throw new XMLException(urix); } } else { schemaLocation = namespace; try { uri = getURIResolver().resolveURN(namespace); } catch (URIException urix) { throw new XMLException(urix); } if (uri == null) { String err = "Unable to resolve Schema corresponding " + "to namespace '" + namespace + "'."; throw new SchemaException(err); } } //-- Make sure targetNamespace is not the same as the //-- importing schema, see section 4.2.3 in the //-- XML Schema Recommendation if (namespace.equals(schema.getTargetNamespace()) ) throw new SchemaException("the 'namespace' attribute in the <import> element cannot be the same of the targetNamespace of the global schema"); //-- Schema object to hold import schema boolean addSchema = false; Schema importedSchema = schema.getImportedSchema(namespace, true); //-- Have we already imported this XML Schema file? if (state.processed(schemaLocation)) { if (importedSchema == null) schema.addImportedSchema(state.getSchema(schemaLocation)); return; } boolean alreadyLoaded = false; if (importedSchema == null) { if (uri instanceof SchemaLocation) { importedSchema = ((SchemaLocation)uri).getSchema(); schema.addImportedSchema(importedSchema); alreadyLoaded = true; } else { importedSchema = new Schema(); addSchema = true; } } else { //-- check schema location, if different, allow merge if (hasLocation) { String tmpLocation = importedSchema.getSchemaLocation(); alreadyLoaded = schemaLocation.equals(tmpLocation); } else { //-- only namespace can be used, no way to distinguish //-- multiple imports...mark as alreadyLoaded //-- see W3C XML Schema 1.0 Recommendation (part 1) //-- section 4.2.3... //-- <quote>... Given that the schemaLocation [attribute] is only //-- a hint, it is open to applications to ignore all but the //-- first <import> for a given namespace, regardless of the //-- <em>actual value</em> of schemaLocation, but such a strategy //-- risks missing useful information when new schemaLocations //-- are offered.</quote> alreadyLoaded = true; } } state.markAsProcessed(schemaLocation, importedSchema); if (alreadyLoaded) return; //-- Parser Schema Parser parser = null; try { parser = state.getConfiguration().getParser(); } catch(RuntimeException rte) {} if (parser == null) { throw new SchemaException("Error failed to create parser for import"); } //-- Create Schema object and setup unmarshaller SchemaUnmarshaller schemaUnmarshaller = new SchemaUnmarshaller(state); schemaUnmarshaller.setURIResolver(getURIResolver()); schemaUnmarshaller.setSchema(importedSchema); Sax2ComponentReader handler = new Sax2ComponentReader(schemaUnmarshaller); parser.setDocumentHandler(handler); parser.setErrorHandler(handler); try { InputSource source = new InputSource(uri.getReader()); source.setSystemId(uri.getAbsoluteURI()); parser.parse(source); } catch(java.io.IOException ioe) { throw new SchemaException("Error reading import file '"+schemaLocation+"': "+ ioe); } catch(org.xml.sax.SAXException sx) { throw new SchemaException(sx); } //-- Add schema to list of imported schemas (if not already present) if (addSchema) { importedSchema.setSchemaLocation(schemaLocation); schema.addImportedSchema(importedSchema); } }
public ImportUnmarshaller (Schema schema, AttributeSet atts, Resolver resolver, URIResolver uriResolver, Locator locator, SchemaUnmarshallerState state) throws XMLException { super(); setResolver(resolver); setURIResolver(uriResolver); URILocation uri = null; //-- Get schemaLocation String schemaLocation = atts.getValue(SchemaNames.SCHEMALOCATION_ATTR); //-- Get namespace String namespace = atts.getValue("namespace"); if ((schemaLocation == null) && (namespace == null)) { //-- A legal <import/> element...just return return; } boolean hasLocation = (schemaLocation != null); if (schemaLocation != null) { if (schemaLocation.indexOf("\\") != -1) { String err = "'" + schemaLocation + "' is not a valid URI as defined by IETF RFC 2396."; err += "The URI mustn't contain '\\'."; throw new SchemaException(err); } if (namespace == null) namespace = ""; try { String documentBase = locator.getSystemId(); if (documentBase != null) { if (!documentBase.endsWith("/")) documentBase = documentBase.substring(0, documentBase.lastIndexOf('/') +1 ); } uri = getURIResolver().resolve(schemaLocation, documentBase); if (uri != null) { schemaLocation = uri.getAbsoluteURI(); } } catch (URIException urix) { throw new XMLException(urix); } } else { schemaLocation = namespace; try { uri = getURIResolver().resolveURN(namespace); } catch (URIException urix) { throw new XMLException(urix); } if (uri == null) { String err = "Unable to resolve Schema corresponding " + "to namespace '" + namespace + "'."; throw new SchemaException(err); } } //-- Make sure targetNamespace is not the same as the //-- importing schema, see section 4.2.3 in the //-- XML Schema Recommendation if (namespace.equals(schema.getTargetNamespace()) ) throw new SchemaException("the 'namespace' attribute in the <import> element cannot be the same of the targetNamespace of the global schema"); //-- Schema object to hold import schema boolean addSchema = false; Schema importedSchema = schema.getImportedSchema(namespace, true); //-- Have we already imported this XML Schema file? if (state.processed(schemaLocation)) { if (importedSchema == null) schema.addImportedSchema(state.getSchema(schemaLocation)); return; } boolean alreadyLoaded = false; if (importedSchema == null) { if (uri instanceof SchemaLocation) { importedSchema = ((SchemaLocation)uri).getSchema(); schema.addImportedSchema(importedSchema); alreadyLoaded = true; } else { importedSchema = new Schema(); addSchema = true; } } else { // check schema location, if different, allow merge if (hasLocation) { String tmpLocation = importedSchema.getSchemaLocation(); alreadyLoaded = schemaLocation.equals(tmpLocation) || importedSchema.includeProcessed(schemaLocation); //-- keep track of the original schemaLocation as an include if(! alreadyLoaded) { importedSchema.addInclude(tmpLocation); } } else { //-- only namespace can be used, no way to distinguish //-- multiple imports...mark as alreadyLoaded //-- see W3C XML Schema 1.0 Recommendation (part 1) //-- section 4.2.3... //-- <quote>... Given that the schemaLocation [attribute] is only //-- a hint, it is open to applications to ignore all but the //-- first <import> for a given namespace, regardless of the //-- <em>actual value</em> of schemaLocation, but such a strategy //-- risks missing useful information when new schemaLocations //-- are offered.</quote> alreadyLoaded = true; } } state.markAsProcessed(schemaLocation, importedSchema); if (alreadyLoaded) return; //-- Parser Schema Parser parser = null; try { parser = state.getConfiguration().getParser(); } catch(RuntimeException rte) {} if (parser == null) { throw new SchemaException("Error failed to create parser for import"); } //-- Create Schema object and setup unmarshaller SchemaUnmarshaller schemaUnmarshaller = new SchemaUnmarshaller(state); schemaUnmarshaller.setURIResolver(getURIResolver()); schemaUnmarshaller.setSchema(importedSchema); Sax2ComponentReader handler = new Sax2ComponentReader(schemaUnmarshaller); parser.setDocumentHandler(handler); parser.setErrorHandler(handler); try { InputSource source = new InputSource(uri.getReader()); source.setSystemId(uri.getAbsoluteURI()); parser.parse(source); } catch(java.io.IOException ioe) { throw new SchemaException("Error reading import file '"+schemaLocation+"': "+ ioe); } catch(org.xml.sax.SAXException sx) { throw new SchemaException(sx); } //-- Add schema to list of imported schemas (if not already present) if (addSchema) { importedSchema.setSchemaLocation(schemaLocation); schema.addImportedSchema(importedSchema); } }
diff --git a/src/main/java/de/hydrox/bukkit/DroxPerms/data/flatfile/User.java b/src/main/java/de/hydrox/bukkit/DroxPerms/data/flatfile/User.java index 091522c..c4b191b 100644 --- a/src/main/java/de/hydrox/bukkit/DroxPerms/data/flatfile/User.java +++ b/src/main/java/de/hydrox/bukkit/DroxPerms/data/flatfile/User.java @@ -1,96 +1,97 @@ package de.hydrox.bukkit.DroxPerms.data.flatfile; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import org.bukkit.util.config.ConfigurationNode; public class User { private static HashMap<String, User> users = new HashMap<String, User>(); private String name; private String group; private ArrayList<String> subgroups; private ArrayList<String> globalPermissions; private HashMap<String, ArrayList<String>> permissions; public User() { this("mydrox"); } public User(String name) { this.name = name; this.group = "default"; this.subgroups = new ArrayList<String>(); this.globalPermissions = new ArrayList<String>(); this.permissions = new HashMap<String, ArrayList<String>>(); } public User(String name, ConfigurationNode node) { this.name = name; + this.group = node.getString("group"); System.out.println("users" + node.getKeys().toString()); System.out.println("users.subgroups" + node.getStringList("subgroups", new ArrayList<String>())); this.subgroups = (ArrayList<String>) node.getStringList("subgroups", new ArrayList<String>()); System.out.println("subgroups: " + subgroups.size()); this.globalPermissions = (ArrayList<String>) node.getStringList("globalpermissions", new ArrayList<String>()); System.out.println("globalpermissions: " + globalPermissions.size()); this.permissions = new HashMap<String, ArrayList<String>>(); ConfigurationNode tmp = node.getNode("permissions"); Iterator<String> iter = tmp.getKeys().iterator(); while (iter.hasNext()) { String world = iter.next(); permissions.put(world, (ArrayList<String>) tmp.getStringList(world, new ArrayList<String>())); System.out.println("permissions "+world+": " + permissions.get(world).size()); } } public String getName() { return name; } public HashMap<String, Object> toConfigurationNode() { LinkedHashMap<String, Object> output = new LinkedHashMap<String, Object>(); output.put("group", group); output.put("subgroups", subgroups); output.put("permissions", permissions); output.put("globalpermissions", globalPermissions); return output; } public static boolean addUser(User user) { if (existUser(user.name.toLowerCase())) { return false; } users.put(user.name.toLowerCase(), user); return true; } public static boolean removeUser(String name) { if (existUser(name.toLowerCase())) { users.remove(name.toLowerCase()); return true; } return false; } public static User getUser(String name) { return users.get(name.toLowerCase()); } public static boolean existUser(String name) { if (users.containsKey(name.toLowerCase())) { return true; } return false; } public static void clearUsers() { users.clear(); } public static Iterator<User> iter() { return users.values().iterator(); } }
true
true
public User(String name, ConfigurationNode node) { this.name = name; System.out.println("users" + node.getKeys().toString()); System.out.println("users.subgroups" + node.getStringList("subgroups", new ArrayList<String>())); this.subgroups = (ArrayList<String>) node.getStringList("subgroups", new ArrayList<String>()); System.out.println("subgroups: " + subgroups.size()); this.globalPermissions = (ArrayList<String>) node.getStringList("globalpermissions", new ArrayList<String>()); System.out.println("globalpermissions: " + globalPermissions.size()); this.permissions = new HashMap<String, ArrayList<String>>(); ConfigurationNode tmp = node.getNode("permissions"); Iterator<String> iter = tmp.getKeys().iterator(); while (iter.hasNext()) { String world = iter.next(); permissions.put(world, (ArrayList<String>) tmp.getStringList(world, new ArrayList<String>())); System.out.println("permissions "+world+": " + permissions.get(world).size()); } }
public User(String name, ConfigurationNode node) { this.name = name; this.group = node.getString("group"); System.out.println("users" + node.getKeys().toString()); System.out.println("users.subgroups" + node.getStringList("subgroups", new ArrayList<String>())); this.subgroups = (ArrayList<String>) node.getStringList("subgroups", new ArrayList<String>()); System.out.println("subgroups: " + subgroups.size()); this.globalPermissions = (ArrayList<String>) node.getStringList("globalpermissions", new ArrayList<String>()); System.out.println("globalpermissions: " + globalPermissions.size()); this.permissions = new HashMap<String, ArrayList<String>>(); ConfigurationNode tmp = node.getNode("permissions"); Iterator<String> iter = tmp.getKeys().iterator(); while (iter.hasNext()) { String world = iter.next(); permissions.put(world, (ArrayList<String>) tmp.getStringList(world, new ArrayList<String>())); System.out.println("permissions "+world+": " + permissions.get(world).size()); } }
diff --git a/framework/src/com/phonegap/DroidGap.java b/framework/src/com/phonegap/DroidGap.java index 5817c25c..956b4d61 100755 --- a/framework/src/com/phonegap/DroidGap.java +++ b/framework/src/com/phonegap/DroidGap.java @@ -1,1775 +1,1779 @@ /* * PhoneGap is available under *either* the terms of the modified BSD license *or* the * MIT License (2008). See http://opensource.org/licenses/alphabetical for full text. * * Copyright (c) 2005-2010, Nitobi Software Inc. * Copyright (c) 2010-2011, IBM Corporation */ package com.phonegap; import java.util.HashMap; import java.util.Map.Entry; import java.util.ArrayList; import java.util.Stack; import java.util.regex.Pattern; import java.util.regex.Matcher; import java.util.Iterator; import java.io.IOException; import org.json.JSONArray; import org.json.JSONException; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.Configuration; import android.content.res.XmlResourceParser; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.Rect; import android.media.AudioManager; import android.net.Uri; import android.net.http.SslError; import android.os.Bundle; import android.util.Log; import android.view.Display; import android.view.KeyEvent; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.webkit.ConsoleMessage; import android.webkit.GeolocationPermissions.Callback; import android.webkit.JsPromptResult; import android.webkit.JsResult; import android.webkit.SslErrorHandler; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebSettings.LayoutAlgorithm; import android.webkit.WebStorage; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.EditText; import android.widget.LinearLayout; import com.phonegap.api.LOG; import com.phonegap.api.PhonegapActivity; import com.phonegap.api.IPlugin; import com.phonegap.api.PluginManager; import org.xmlpull.v1.XmlPullParserException; /** * This class is the main Android activity that represents the PhoneGap * application. It should be extended by the user to load the specific * html file that contains the application. * * As an example: * * package com.phonegap.examples; * import android.app.Activity; * import android.os.Bundle; * import com.phonegap.*; * * public class Examples extends DroidGap { * @Override * public void onCreate(Bundle savedInstanceState) { * super.onCreate(savedInstanceState); * * // Set properties for activity * super.setStringProperty("loadingDialog", "Title,Message"); // show loading dialog * super.setStringProperty("errorUrl", "file:///android_asset/www/error.html"); // if error loading file in super.loadUrl(). * * // Initialize activity * super.init(); * * // Clear cache if you want * super.appView.clearCache(true); * * // Load your application * super.setIntegerProperty("splashscreen", R.drawable.splash); // load splash.jpg image from the resource drawable directory * super.loadUrl("file:///android_asset/www/index.html", 3000); // show splash screen 3 sec before loading app * } * } * * Properties: The application can be configured using the following properties: * * // Display a native loading dialog when loading app. Format for value = "Title,Message". * // (String - default=null) * super.setStringProperty("loadingDialog", "Wait,Loading Demo..."); * * // Display a native loading dialog when loading sub-pages. Format for value = "Title,Message". * // (String - default=null) * super.setStringProperty("loadingPageDialog", "Loading page..."); * * // Load a splash screen image from the resource drawable directory. * // (Integer - default=0) * super.setIntegerProperty("splashscreen", R.drawable.splash); * * // Set the background color. * // (Integer - default=0 or BLACK) * super.setIntegerProperty("backgroundColor", Color.WHITE); * * // Time in msec to wait before triggering a timeout error when loading * // with super.loadUrl(). (Integer - default=20000) * super.setIntegerProperty("loadUrlTimeoutValue", 60000); * * // URL to load if there's an error loading specified URL with loadUrl(). * // Should be a local URL starting with file://. (String - default=null) * super.setStringProperty("errorUrl", "file:///android_asset/www/error.html"); * * // Enable app to keep running in background. (Boolean - default=true) * super.setBooleanProperty("keepRunning", false); * * Phonegap.xml configuration: * PhoneGap uses a configuration file at res/xml/phonegap.xml to specify the following settings. * * Approved list of URLs that can be loaded into DroidGap * <access origin="http://server regexp" subdomains="true" /> * Log level: ERROR, WARN, INFO, DEBUG, VERBOSE (default=ERROR) * <log level="DEBUG" /> * * Phonegap plugins: * PhoneGap uses a file at res/xml/plugins.xml to list all plugins that are installed. * Before using a new plugin, a new element must be added to the file. * name attribute is the service name passed to PhoneGap.exec() in JavaScript * value attribute is the Java class name to call. * * <plugins> * <plugin name="App" value="com.phonegap.App"/> * ... * </plugins> */ public class DroidGap extends PhonegapActivity { public static String TAG = "DroidGap"; // The webview for our app protected WebView appView; protected WebViewClient webViewClient; private ArrayList<Pattern> whiteList = new ArrayList<Pattern>(); private HashMap<String, Boolean> whiteListCache = new HashMap<String,Boolean>(); protected LinearLayout root; public boolean bound = false; public CallbackServer callbackServer; protected PluginManager pluginManager; protected boolean cancelLoadUrl = false; protected ProgressDialog spinnerDialog = null; // The initial URL for our app // ie http://server/path/index.html#abc?query private String url = null; private Stack<String> urls = new Stack<String>(); // Url was specified from extras (activity was started programmatically) private String initUrl = null; private static int ACTIVITY_STARTING = 0; private static int ACTIVITY_RUNNING = 1; private static int ACTIVITY_EXITING = 2; private int activityState = 0; // 0=starting, 1=running (after 1st resume), 2=shutting down // The base of the initial URL for our app. // Does not include file name. Ends with / // ie http://server/path/ private String baseUrl = null; // Plugin to call when activity result is received protected IPlugin activityResultCallback = null; protected boolean activityResultKeepRunning; // Flag indicates that a loadUrl timeout occurred private int loadUrlTimeout = 0; // Default background color for activity // (this is not the color for the webview, which is set in HTML) private int backgroundColor = Color.BLACK; /* * The variables below are used to cache some of the activity properties. */ // Draw a splash screen using an image located in the drawable resource directory. // This is not the same as calling super.loadSplashscreen(url) protected int splashscreen = 0; // LoadUrl timeout value in msec (default of 20 sec) protected int loadUrlTimeoutValue = 20000; // Keep app running when pause is received. (default = true) // If true, then the JavaScript and native code continue to run in the background // when another application (activity) is started. protected boolean keepRunning = true; /** * Called when the activity is first created. * * @param savedInstanceState */ @Override public void onCreate(Bundle savedInstanceState) { LOG.d(TAG, "DroidGap.onCreate()"); super.onCreate(savedInstanceState); getWindow().requestFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN, WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN); // This builds the view. We could probably get away with NOT having a LinearLayout, but I like having a bucket! Display display = getWindowManager().getDefaultDisplay(); int width = display.getWidth(); int height = display.getHeight(); root = new LinearLayoutSoftKeyboardDetect(this, width, height); root.setOrientation(LinearLayout.VERTICAL); root.setBackgroundColor(this.backgroundColor); root.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT, 0.0F)); // Load PhoneGap configuration: // white list of allowed URLs // debug setting this.loadConfiguration(); // If url was passed in to intent, then init webview, which will load the url Bundle bundle = this.getIntent().getExtras(); if (bundle != null) { String url = bundle.getString("url"); if (url != null) { this.initUrl = url; } } // Setup the hardware volume controls to handle volume control setVolumeControlStream(AudioManager.STREAM_MUSIC); } /** * Create and initialize web container. */ public void init() { LOG.d(TAG, "DroidGap.init()"); // Create web container this.appView = new WebView(DroidGap.this); this.appView.setId(100); this.appView.setLayoutParams(new LinearLayout.LayoutParams( ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT, 1.0F)); WebViewReflect.checkCompatibility(); this.appView.setWebChromeClient(new GapClient(DroidGap.this)); this.setWebViewClient(this.appView, new GapViewClient(this)); this.appView.setInitialScale(100); this.appView.setVerticalScrollBarEnabled(false); this.appView.requestFocusFromTouch(); // Enable JavaScript WebSettings settings = this.appView.getSettings(); settings.setJavaScriptEnabled(true); settings.setJavaScriptCanOpenWindowsAutomatically(true); settings.setLayoutAlgorithm(LayoutAlgorithm.NORMAL); //Set the nav dump for HTC settings.setNavDump(true); // Enable database settings.setDatabaseEnabled(true); String databasePath = this.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath(); settings.setDatabasePath(databasePath); // Enable DOM storage WebViewReflect.setDomStorage(settings); // Enable built-in geolocation WebViewReflect.setGeolocationEnabled(settings, true); // Add web view but make it invisible while loading URL this.appView.setVisibility(View.INVISIBLE); root.addView(this.appView); setContentView(root); // Clear cancel flag this.cancelLoadUrl = false; } /** * Set the WebViewClient. * * @param appView * @param client */ protected void setWebViewClient(WebView appView, WebViewClient client) { this.webViewClient = client; appView.setWebViewClient(client); } /** * Look at activity parameters and process them. * This must be called from the main UI thread. */ private void handleActivityParameters() { // If backgroundColor this.backgroundColor = this.getIntegerProperty("backgroundColor", Color.BLACK); this.root.setBackgroundColor(this.backgroundColor); // If spashscreen this.splashscreen = this.getIntegerProperty("splashscreen", 0); if ((this.urls.size() == 0) && (this.splashscreen != 0)) { root.setBackgroundResource(this.splashscreen); } // If loadUrlTimeoutValue int timeout = this.getIntegerProperty("loadUrlTimeoutValue", 0); if (timeout > 0) { this.loadUrlTimeoutValue = timeout; } // If keepRunning this.keepRunning = this.getBooleanProperty("keepRunning", true); } /** * Load the url into the webview. * * @param url */ public void loadUrl(String url) { // If first page of app, then set URL to load to be the one passed in if (this.initUrl == null || (this.urls.size() > 0)) { this.loadUrlIntoView(url); } // Otherwise use the URL specified in the activity's extras bundle else { this.loadUrlIntoView(this.initUrl); } } /** * Load the url into the webview. * * @param url */ private void loadUrlIntoView(final String url) { if (!url.startsWith("javascript:")) { LOG.d(TAG, "DroidGap.loadUrl(%s)", url); } // Init web view if not already done if (this.appView == null) { this.init(); } this.url = url; if (this.baseUrl == null) { int i = url.lastIndexOf('/'); if (i > 0) { this.baseUrl = url.substring(0, i+1); } else { this.baseUrl = this.url + "/"; } } if (!url.startsWith("javascript:")) { LOG.d(TAG, "DroidGap: url=%s baseUrl=%s", url, baseUrl); } // Load URL on UI thread final DroidGap me = this; this.runOnUiThread(new Runnable() { public void run() { // Handle activity parameters me.handleActivityParameters(); // Track URLs loaded instead of using appView history me.urls.push(url); me.appView.clearHistory(); // Create callback server and plugin manager if (me.callbackServer == null) { me.callbackServer = new CallbackServer(); me.callbackServer.init(url); } else { me.callbackServer.reinit(url); } if (me.pluginManager == null) { me.pluginManager = new PluginManager(me.appView, me); } else { me.pluginManager.reinit(); } // If loadingDialog property, then show the App loading dialog for first page of app String loading = null; if (me.urls.size() == 0) { loading = me.getStringProperty("loadingDialog", null); } else { loading = me.getStringProperty("loadingPageDialog", null); } if (loading != null) { String title = ""; String message = "Loading Application..."; if (loading.length() > 0) { int comma = loading.indexOf(','); if (comma > 0) { title = loading.substring(0, comma); message = loading.substring(comma+1); } else { title = ""; message = loading; } } me.spinnerStart(title, message); } // Create a timeout timer for loadUrl final int currentLoadUrlTimeout = me.loadUrlTimeout; Runnable runnable = new Runnable() { public void run() { try { synchronized(this) { wait(me.loadUrlTimeoutValue); } } catch (InterruptedException e) { e.printStackTrace(); } // If timeout, then stop loading and handle error if (me.loadUrlTimeout == currentLoadUrlTimeout) { me.appView.stopLoading(); LOG.e(TAG, "DroidGap: TIMEOUT ERROR! - calling webViewClient"); me.webViewClient.onReceivedError(me.appView, -6, "The connection to the server was unsuccessful.", url); } } }; Thread thread = new Thread(runnable); thread.start(); me.appView.loadUrl(url); } }); } /** * Load the url into the webview after waiting for period of time. * This is used to display the splashscreen for certain amount of time. * * @param url * @param time The number of ms to wait before loading webview */ public void loadUrl(final String url, int time) { // If first page of app, then set URL to load to be the one passed in if (this.initUrl == null || (this.urls.size() > 0)) { this.loadUrlIntoView(url, time); } // Otherwise use the URL specified in the activity's extras bundle else { this.loadUrlIntoView(this.initUrl); } } /** * Load the url into the webview after waiting for period of time. * This is used to display the splashscreen for certain amount of time. * * @param url * @param time The number of ms to wait before loading webview */ private void loadUrlIntoView(final String url, final int time) { // Clear cancel flag this.cancelLoadUrl = false; // If not first page of app, then load immediately if (this.urls.size() > 0) { this.loadUrlIntoView(url); } if (!url.startsWith("javascript:")) { LOG.d(TAG, "DroidGap.loadUrl(%s, %d)", url, time); } final DroidGap me = this; // Handle activity parameters this.runOnUiThread(new Runnable() { public void run() { me.handleActivityParameters(); } }); Runnable runnable = new Runnable() { public void run() { try { synchronized(this) { this.wait(time); } } catch (InterruptedException e) { e.printStackTrace(); } if (!me.cancelLoadUrl) { me.loadUrlIntoView(url); } else{ me.cancelLoadUrl = false; LOG.d(TAG, "Aborting loadUrl(%s): Another URL was loaded before timer expired.", url); } } }; Thread thread = new Thread(runnable); thread.start(); } /** * Cancel loadUrl before it has been loaded. */ public void cancelLoadUrl() { this.cancelLoadUrl = true; } /** * Clear the resource cache. */ public void clearCache() { if (this.appView == null) { this.init(); } this.appView.clearCache(true); } /** * Clear web history in this web view. */ public void clearHistory() { this.urls.clear(); // Leave current url on history stack if (this.url != null) { this.urls.push(this.url); } } /** * Go to previous page in history. (We manage our own history) */ public void backHistory() { if (this.urls.size() > 1) { this.urls.pop(); // Pop current url String url = this.urls.pop(); // Pop prev url that we want to load this.loadUrl(url); } } @Override /** * Called by the system when the device configuration changes while your activity is running. * * @param Configuration newConfig */ public void onConfigurationChanged(Configuration newConfig) { //don't reload the current page when the orientation is changed super.onConfigurationChanged(newConfig); } /** * Get boolean property for activity. * * @param name * @param defaultValue * @return */ public boolean getBooleanProperty(String name, boolean defaultValue) { Bundle bundle = this.getIntent().getExtras(); if (bundle == null) { return defaultValue; } Boolean p = (Boolean)bundle.get(name); if (p == null) { return defaultValue; } return p.booleanValue(); } /** * Get int property for activity. * * @param name * @param defaultValue * @return */ public int getIntegerProperty(String name, int defaultValue) { Bundle bundle = this.getIntent().getExtras(); if (bundle == null) { return defaultValue; } Integer p = (Integer)bundle.get(name); if (p == null) { return defaultValue; } return p.intValue(); } /** * Get string property for activity. * * @param name * @param defaultValue * @return */ public String getStringProperty(String name, String defaultValue) { Bundle bundle = this.getIntent().getExtras(); if (bundle == null) { return defaultValue; } String p = bundle.getString(name); if (p == null) { return defaultValue; } return p; } /** * Get double property for activity. * * @param name * @param defaultValue * @return */ public double getDoubleProperty(String name, double defaultValue) { Bundle bundle = this.getIntent().getExtras(); if (bundle == null) { return defaultValue; } Double p = (Double)bundle.get(name); if (p == null) { return defaultValue; } return p.doubleValue(); } /** * Set boolean property on activity. * * @param name * @param value */ public void setBooleanProperty(String name, boolean value) { this.getIntent().putExtra(name, value); } /** * Set int property on activity. * * @param name * @param value */ public void setIntegerProperty(String name, int value) { this.getIntent().putExtra(name, value); } /** * Set string property on activity. * * @param name * @param value */ public void setStringProperty(String name, String value) { this.getIntent().putExtra(name, value); } /** * Set double property on activity. * * @param name * @param value */ public void setDoubleProperty(String name, double value) { this.getIntent().putExtra(name, value); } @Override /** * Called when the system is about to start resuming a previous activity. */ protected void onPause() { super.onPause(); // Don't process pause if shutting down, since onDestroy() will be called if (this.activityState == ACTIVITY_EXITING) { return; } if (this.appView == null) { return; } // Send pause event to JavaScript this.appView.loadUrl("javascript:try{PhoneGap.onPause.fire();}catch(e){};"); // Forward to plugins this.pluginManager.onPause(this.keepRunning); // If app doesn't want to run in background if (!this.keepRunning) { // Pause JavaScript timers (including setInterval) this.appView.pauseTimers(); } } @Override /** * Called when the activity receives a new intent **/ protected void onNewIntent(Intent intent) { super.onNewIntent(intent); //Forward to plugins this.pluginManager.onNewIntent(intent); } @Override /** * Called when the activity will start interacting with the user. */ protected void onResume() { super.onResume(); if (this.activityState == ACTIVITY_STARTING) { this.activityState = ACTIVITY_RUNNING; return; } if (this.appView == null) { return; } // Send resume event to JavaScript this.appView.loadUrl("javascript:try{PhoneGap.onResume.fire();}catch(e){};"); // Forward to plugins this.pluginManager.onResume(this.keepRunning || this.activityResultKeepRunning); // If app doesn't want to run in background if (!this.keepRunning || this.activityResultKeepRunning) { // Restore multitasking state if (this.activityResultKeepRunning) { this.keepRunning = this.activityResultKeepRunning; this.activityResultKeepRunning = false; } // Resume JavaScript timers (including setInterval) this.appView.resumeTimers(); } } @Override /** * The final call you receive before your activity is destroyed. */ public void onDestroy() { super.onDestroy(); if (this.appView != null) { // Send destroy event to JavaScript this.appView.loadUrl("javascript:try{PhoneGap.onDestroy.fire();}catch(e){};"); // Load blank page so that JavaScript onunload is called this.appView.loadUrl("about:blank"); // Forward to plugins this.pluginManager.onDestroy(); } else { this.endActivity(); } } /** * Add a class that implements a service. * * @param serviceType * @param className */ public void addService(String serviceType, String className) { this.pluginManager.addService(serviceType, className); } /** * Send JavaScript statement back to JavaScript. * (This is a convenience method) * * @param message */ public void sendJavascript(String statement) { this.callbackServer.sendJavascript(statement); } /** * Load the specified URL in the PhoneGap webview or a new browser instance. * * NOTE: If openExternal is false, only URLs listed in whitelist can be loaded. * * @param url The url to load. * @param openExternal Load url in browser instead of PhoneGap webview. * @param clearHistory Clear the history stack, so new page becomes top of history * @param params DroidGap parameters for new app */ public void showWebPage(String url, boolean openExternal, boolean clearHistory, HashMap<String, Object> params) { //throws android.content.ActivityNotFoundException { LOG.d(TAG, "showWebPage(%s, %b, %b, HashMap", url, openExternal, clearHistory); // If clearing history if (clearHistory) { this.clearHistory(); } // If loading into our webview if (!openExternal) { // Make sure url is in whitelist if (url.startsWith("file://") || url.indexOf(this.baseUrl) == 0 || isUrlWhiteListed(url)) { // TODO: What about params? // Clear out current url from history, since it will be replacing it if (clearHistory) { this.urls.clear(); } // Load new URL this.loadUrl(url); } // Load in default viewer if not else { LOG.w(TAG, "showWebPage: Cannot load URL into webview since it is not in white list. Loading into browser instead. (URL="+url+")"); try { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); this.startActivity(intent); } catch (android.content.ActivityNotFoundException e) { LOG.e(TAG, "Error loading url "+url, e); } } } // Load in default view intent else { try { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); this.startActivity(intent); } catch (android.content.ActivityNotFoundException e) { LOG.e(TAG, "Error loading url "+url, e); } } } /** * Show the spinner. Must be called from the UI thread. * * @param title Title of the dialog * @param message The message of the dialog */ public void spinnerStart(final String title, final String message) { if (this.spinnerDialog != null) { this.spinnerDialog.dismiss(); this.spinnerDialog = null; } final DroidGap me = this; this.spinnerDialog = ProgressDialog.show(DroidGap.this, title , message, true, true, new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { me.spinnerDialog = null; } }); } /** * Stop spinner. */ public void spinnerStop() { if (this.spinnerDialog != null) { this.spinnerDialog.dismiss(); this.spinnerDialog = null; } } /** * Set the chrome handler. */ public class GapClient extends WebChromeClient { private String TAG = "PhoneGapLog"; private long MAX_QUOTA = 100 * 1024 * 1024; private DroidGap ctx; /** * Constructor. * * @param ctx */ public GapClient(Context ctx) { this.ctx = (DroidGap)ctx; } /** * Tell the client to display a javascript alert dialog. * * @param view * @param url * @param message * @param result */ @Override public boolean onJsAlert(WebView view, String url, String message, final JsResult result) { AlertDialog.Builder dlg = new AlertDialog.Builder(this.ctx); dlg.setMessage(message); dlg.setTitle("Alert"); //Don't let alerts break the back button dlg.setCancelable(true); dlg.setPositiveButton(android.R.string.ok, new AlertDialog.OnClickListener() { public void onClick(DialogInterface dialog, int which) { result.confirm(); } }); dlg.setOnCancelListener( new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { result.confirm(); } }); dlg.setOnKeyListener(new DialogInterface.OnKeyListener() { //DO NOTHING public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_BACK) { result.confirm(); return false; } else return true; } }); dlg.create(); dlg.show(); return true; } /** * Tell the client to display a confirm dialog to the user. * * @param view * @param url * @param message * @param result */ @Override public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) { AlertDialog.Builder dlg = new AlertDialog.Builder(this.ctx); dlg.setMessage(message); dlg.setTitle("Confirm"); dlg.setCancelable(true); dlg.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { result.confirm(); } }); dlg.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { result.cancel(); } }); dlg.setOnCancelListener( new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { result.cancel(); } }); dlg.setOnKeyListener(new DialogInterface.OnKeyListener() { //DO NOTHING public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_BACK) { result.cancel(); return false; } else return true; } }); dlg.create(); dlg.show(); return true; } /** * Tell the client to display a prompt dialog to the user. * If the client returns true, WebView will assume that the client will * handle the prompt dialog and call the appropriate JsPromptResult method. * * @param view * @param url * @param message * @param defaultValue * @param result */ @Override public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) { // Security check to make sure any requests are coming from the page initially // loaded in webview and not another loaded in an iframe. boolean reqOk = false; if (url.indexOf(this.ctx.baseUrl) == 0 || isUrlWhiteListed(url)) { reqOk = true; } // Calling PluginManager.exec() to call a native service using // prompt(this.stringify(args), "gap:"+this.stringify([service, action, callbackId, true])); if (reqOk && defaultValue != null && defaultValue.length() > 3 && defaultValue.substring(0, 4).equals("gap:")) { JSONArray array; try { array = new JSONArray(defaultValue.substring(4)); String service = array.getString(0); String action = array.getString(1); String callbackId = array.getString(2); boolean async = array.getBoolean(3); String r = pluginManager.exec(service, action, callbackId, message, async); result.confirm(r); } catch (JSONException e) { e.printStackTrace(); } } // Polling for JavaScript messages else if (reqOk && defaultValue != null && defaultValue.equals("gap_poll:")) { String r = callbackServer.getJavascript(); result.confirm(r); } // Calling into CallbackServer else if (reqOk && defaultValue != null && defaultValue.equals("gap_callbackServer:")) { String r = ""; if (message.equals("usePolling")) { r = ""+callbackServer.usePolling(); } else if (message.equals("restartServer")) { callbackServer.restartServer(); } else if (message.equals("getPort")) { r = Integer.toString(callbackServer.getPort()); } else if (message.equals("getToken")) { r = callbackServer.getToken(); } result.confirm(r); } // PhoneGap JS has initialized, so show webview // (This solves white flash seen when rendering HTML) else if (reqOk && defaultValue != null && defaultValue.equals("gap_init:")) { appView.setVisibility(View.VISIBLE); ctx.spinnerStop(); result.confirm("OK"); } // Show dialog else { final JsPromptResult res = result; AlertDialog.Builder dlg = new AlertDialog.Builder(this.ctx); dlg.setMessage(message); final EditText input = new EditText(this.ctx); if (defaultValue != null) { input.setText(defaultValue); } dlg.setView(input); dlg.setCancelable(false); dlg.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { String usertext = input.getText().toString(); res.confirm(usertext); } }); dlg.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { res.cancel(); } }); dlg.create(); dlg.show(); } return true; } /** * Handle database quota exceeded notification. * * @param url * @param databaseIdentifier * @param currentQuota * @param estimatedSize * @param totalUsedQuota * @param quotaUpdater */ @Override public void onExceededDatabaseQuota(String url, String databaseIdentifier, long currentQuota, long estimatedSize, long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) { LOG.d(TAG, "DroidGap: onExceededDatabaseQuota estimatedSize: %d currentQuota: %d totalUsedQuota: %d", estimatedSize, currentQuota, totalUsedQuota); if( estimatedSize < MAX_QUOTA) { //increase for 1Mb long newQuota = estimatedSize; LOG.d(TAG, "calling quotaUpdater.updateQuota newQuota: %d", newQuota); quotaUpdater.updateQuota(newQuota); } else { // Set the quota to whatever it is and force an error // TODO: get docs on how to handle this properly quotaUpdater.updateQuota(currentQuota); } } // console.log in api level 7: http://developer.android.com/guide/developing/debug-tasks.html @Override public void onConsoleMessage(String message, int lineNumber, String sourceID) { LOG.d(TAG, "%s: Line %d : %s", sourceID, lineNumber, message); } @Override public boolean onConsoleMessage(ConsoleMessage consoleMessage) { LOG.d(TAG, consoleMessage.message()); return true; } @Override /** * Instructs the client to show a prompt to ask the user to set the Geolocation permission state for the specified origin. * * @param origin * @param callback */ public void onGeolocationPermissionsShowPrompt(String origin, Callback callback) { super.onGeolocationPermissionsShowPrompt(origin, callback); callback.invoke(origin, true, false); } } /** * The webview client receives notifications about appView */ public class GapViewClient extends WebViewClient { DroidGap ctx; /** * Constructor. * * @param ctx */ public GapViewClient(DroidGap ctx) { this.ctx = ctx; } /** * Give the host application a chance to take over the control when a new url * is about to be loaded in the current WebView. * * @param view The WebView that is initiating the callback. * @param url The url to be loaded. * @return true to override, false for default behavior */ @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { // First give any plugins the chance to handle the url themselves if (this.ctx.pluginManager.onOverrideUrlLoading(url)) { } // If dialing phone (tel:5551212) else if (url.startsWith(WebView.SCHEME_TEL)) { try { Intent intent = new Intent(Intent.ACTION_DIAL); intent.setData(Uri.parse(url)); startActivity(intent); } catch (android.content.ActivityNotFoundException e) { LOG.e(TAG, "Error dialing "+url+": "+ e.toString()); } } // If displaying map (geo:0,0?q=address) else if (url.startsWith("geo:")) { try { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); startActivity(intent); } catch (android.content.ActivityNotFoundException e) { LOG.e(TAG, "Error showing map "+url+": "+ e.toString()); } } // If sending email (mailto:[email protected]) else if (url.startsWith(WebView.SCHEME_MAILTO)) { try { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); startActivity(intent); } catch (android.content.ActivityNotFoundException e) { LOG.e(TAG, "Error sending email "+url+": "+ e.toString()); } } // If sms:5551212?body=This is the message else if (url.startsWith("sms:")) { try { Intent intent = new Intent(Intent.ACTION_VIEW); // Get address String address = null; int parmIndex = url.indexOf('?'); if (parmIndex == -1) { address = url.substring(4); } else { address = url.substring(4, parmIndex); // If body, then set sms body Uri uri = Uri.parse(url); String query = uri.getQuery(); if (query != null) { if (query.startsWith("body=")) { intent.putExtra("sms_body", query.substring(5)); } } } intent.setData(Uri.parse("sms:"+address)); intent.putExtra("address", address); intent.setType("vnd.android-dir/mms-sms"); startActivity(intent); } catch (android.content.ActivityNotFoundException e) { LOG.e(TAG, "Error sending sms "+url+":"+ e.toString()); } } // All else else { // If our app or file:, then load into a new phonegap webview container by starting a new instance of our activity. // Our app continues to run. When BACK is pressed, our app is redisplayed. if (url.startsWith("file://") || url.indexOf(this.ctx.baseUrl) == 0 || isUrlWhiteListed(url)) { this.ctx.loadUrl(url); } // If not our application, let default viewer handle else { try { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); startActivity(intent); } catch (android.content.ActivityNotFoundException e) { LOG.e(TAG, "Error loading url "+url, e); } } } return true; } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { // Clear history so history.back() doesn't do anything. // So we can reinit() native side CallbackServer & PluginManager. view.clearHistory(); } /** * Notify the host application that a page has finished loading. * * @param view The webview initiating the callback. * @param url The url of the page. */ @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); // Clear timeout flag this.ctx.loadUrlTimeout++; // Try firing the onNativeReady event in JS. If it fails because the JS is // not loaded yet then just set a flag so that the onNativeReady can be fired // from the JS side when the JS gets to that code. if (!url.equals("about:blank")) { appView.loadUrl("javascript:try{ PhoneGap.onNativeReady.fire();}catch(e){_nativeReady = true;}"); } // Make app visible after 2 sec in case there was a JS error and PhoneGap JS never initialized correctly if (appView.getVisibility() == View.INVISIBLE) { Thread t = new Thread(new Runnable() { public void run() { try { Thread.sleep(2000); ctx.runOnUiThread(new Runnable() { public void run() { appView.setVisibility(View.VISIBLE); ctx.spinnerStop(); } }); } catch (InterruptedException e) { } } }); t.start(); } // Shutdown if blank loaded if (url.equals("about:blank")) { if (this.ctx.callbackServer != null) { this.ctx.callbackServer.destroy(); } this.ctx.endActivity(); } } /** * Report an error to the host application. These errors are unrecoverable (i.e. the main resource is unavailable). * The errorCode parameter corresponds to one of the ERROR_* constants. * * @param view The WebView that is initiating the callback. * @param errorCode The error code corresponding to an ERROR_* value. * @param description A String describing the error. * @param failingUrl The url that failed to load. */ @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { LOG.d(TAG, "DroidGap: GapViewClient.onReceivedError: Error code=%s Description=%s URL=%s", errorCode, description, failingUrl); // Clear timeout flag this.ctx.loadUrlTimeout++; // Stop "app loading" spinner if showing this.ctx.spinnerStop(); // Handle error this.ctx.onReceivedError(errorCode, description, failingUrl); } public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { final String packageName = this.ctx.getPackageName(); final PackageManager pm = this.ctx.getPackageManager(); ApplicationInfo appInfo; try { appInfo = pm.getApplicationInfo(packageName, PackageManager.GET_META_DATA); if ((appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) { // debug = true handler.proceed(); return; } else { // debug = false super.onReceivedSslError(view, handler, error); } } catch (NameNotFoundException e) { // When it doubt, lock it out! super.onReceivedSslError(view, handler, error); } } } /** * End this activity by calling finish for activity */ public void endActivity() { this.activityState = ACTIVITY_EXITING; this.finish(); } /** * Called when a key is pressed. * * @param keyCode * @param event */ @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (this.appView == null) { return super.onKeyDown(keyCode, event); } // If back key if (keyCode == KeyEvent.KEYCODE_BACK) { // If back key is bound, then send event to JavaScript if (this.bound) { this.appView.loadUrl("javascript:PhoneGap.fireDocumentEvent('backbutton');"); return true; } // If not bound else { // Go to previous page in webview if it is possible to go back if (this.urls.size() > 1) { this.backHistory(); return true; } // If not, then invoke behavior of super class else { return super.onKeyDown(keyCode, event); } } } // If menu key else if (keyCode == KeyEvent.KEYCODE_MENU) { this.appView.loadUrl("javascript:PhoneGap.fireDocumentEvent('menubutton');"); return true; } // If search key else if (keyCode == KeyEvent.KEYCODE_SEARCH) { this.appView.loadUrl("javascript:PhoneGap.fireDocumentEvent('searchbutton');"); return true; } return false; } /** * Any calls to Activity.startActivityForResult must use method below, so * the result can be routed to them correctly. * * This is done to eliminate the need to modify DroidGap.java to receive activity results. * * @param intent The intent to start * @param requestCode Identifies who to send the result to * * @throws RuntimeException */ @Override public void startActivityForResult(Intent intent, int requestCode) throws RuntimeException { LOG.d(TAG, "DroidGap.startActivityForResult(intent,%d)", requestCode); super.startActivityForResult(intent, requestCode); } /** * Launch an activity for which you would like a result when it finished. When this activity exits, * your onActivityResult() method will be called. * * @param command The command object * @param intent The intent to start * @param requestCode The request code that is passed to callback to identify the activity */ public void startActivityForResult(IPlugin command, Intent intent, int requestCode) { this.activityResultCallback = command; this.activityResultKeepRunning = this.keepRunning; // If multitasking turned on, then disable it for activities that return results if (command != null) { this.keepRunning = false; } // Start activity super.startActivityForResult(intent, requestCode); } @Override /** * Called when an activity you launched exits, giving you the requestCode you started it with, * the resultCode it returned, and any additional data from it. * * @param requestCode The request code originally supplied to startActivityForResult(), * allowing you to identify who this result came from. * @param resultCode The integer result code returned by the child activity through its setResult(). * @param data An Intent, which can return result data to the caller (various data can be attached to Intent "extras"). */ protected void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); IPlugin callback = this.activityResultCallback; if (callback != null) { callback.onActivityResult(requestCode, resultCode, intent); } } @Override public void setActivityResultCallback(IPlugin plugin) { this.activityResultCallback = plugin; } /** * Report an error to the host application. These errors are unrecoverable (i.e. the main resource is unavailable). * The errorCode parameter corresponds to one of the ERROR_* constants. * * @param errorCode The error code corresponding to an ERROR_* value. * @param description A String describing the error. * @param failingUrl The url that failed to load. */ - public void onReceivedError(int errorCode, String description, String failingUrl) { + public void onReceivedError(final int errorCode, final String description, final String failingUrl) { final DroidGap me = this; // If errorUrl specified, then load it final String errorUrl = me.getStringProperty("errorUrl", null); if ((errorUrl != null) && (errorUrl.startsWith("file://") || errorUrl.indexOf(me.baseUrl) == 0 || isUrlWhiteListed(errorUrl)) && (!failingUrl.equals(errorUrl))) { // Load URL on UI thread me.runOnUiThread(new Runnable() { public void run() { me.showWebPage(errorUrl, true, true, null); } }); } // If not, then display error dialog else { - me.appView.setVisibility(View.GONE); - me.displayError("Application Error", description + " ("+failingUrl+")", "OK", true); + me.runOnUiThread(new Runnable() { + public void run() { + me.appView.setVisibility(View.GONE); + me.displayError("Application Error", description + " ("+failingUrl+")", "OK", true); + } + }); } } /** * Display an error dialog and optionally exit application. * * @param title * @param message * @param button * @param exit */ public void displayError(final String title, final String message, final String button, final boolean exit) { final DroidGap me = this; me.runOnUiThread(new Runnable() { public void run() { AlertDialog.Builder dlg = new AlertDialog.Builder(me); dlg.setMessage(message); dlg.setTitle(title); dlg.setCancelable(false); dlg.setPositiveButton(button, new AlertDialog.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); if (exit) { me.endActivity(); } } }); dlg.create(); dlg.show(); } }); } /** * We are providing this class to detect when the soft keyboard is shown * and hidden in the web view. */ class LinearLayoutSoftKeyboardDetect extends LinearLayout { private static final String TAG = "SoftKeyboardDetect"; private int oldHeight = 0; // Need to save the old height as not to send redundant events private int oldWidth = 0; // Need to save old width for orientation change private int screenWidth = 0; private int screenHeight = 0; public LinearLayoutSoftKeyboardDetect(Context context, int width, int height) { super(context); screenWidth = width; screenHeight = height; } @Override /** * Start listening to new measurement events. Fire events when the height * gets smaller fire a show keyboard event and when height gets bigger fire * a hide keyboard event. * * Note: We are using callbackServer.sendJavascript() instead of * this.appView.loadUrl() as changing the URL of the app would cause the * soft keyboard to go away. * * @param widthMeasureSpec * @param heightMeasureSpec */ protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); LOG.v(TAG, "We are in our onMeasure method"); // Get the current height of the visible part of the screen. // This height will not included the status bar. int height = MeasureSpec.getSize(heightMeasureSpec); int width = MeasureSpec.getSize(widthMeasureSpec); LOG.v(TAG, "Old Height = %d", oldHeight); LOG.v(TAG, "Height = %d", height); LOG.v(TAG, "Old Width = %d", oldWidth); LOG.v(TAG, "Width = %d", width); // If the oldHeight = 0 then this is the first measure event as the app starts up. // If oldHeight == height then we got a measurement change that doesn't affect us. if (oldHeight == 0 || oldHeight == height) { LOG.d(TAG, "Ignore this event"); } // Account for orientation change and ignore this event/Fire orientation change else if(screenHeight == width) { int tmp_var = screenHeight; screenHeight = screenWidth; screenWidth = tmp_var; LOG.v(TAG, "Orientation Change"); } // If the height as gotten bigger then we will assume the soft keyboard has // gone away. else if (height > oldHeight) { LOG.v(TAG, "Throw hide keyboard event"); callbackServer.sendJavascript("PhoneGap.fireDocumentEvent('hidekeyboard');"); } // If the height as gotten smaller then we will assume the soft keyboard has // been displayed. else if (height < oldHeight) { LOG.v(TAG, "Throw show keyboard event"); callbackServer.sendJavascript("PhoneGap.fireDocumentEvent('showkeyboard');"); } // Update the old height for the next event oldHeight = height; oldWidth = width; } } /** * Load PhoneGap configuration from res/xml/phonegap.xml. * Approved list of URLs that can be loaded into DroidGap * <access origin="http://server regexp" subdomains="true" /> * Log level: ERROR, WARN, INFO, DEBUG, VERBOSE (default=ERROR) * <log level="DEBUG" /> */ private void loadConfiguration() { int id = getResources().getIdentifier("phonegap", "xml", getPackageName()); if (id == 0) { LOG.i("PhoneGapLog", "phonegap.xml missing. Ignoring..."); return; } XmlResourceParser xml = getResources().getXml(id); int eventType = -1; while (eventType != XmlResourceParser.END_DOCUMENT) { if (eventType == XmlResourceParser.START_TAG) { String strNode = xml.getName(); if (strNode.equals("access")) { String origin = xml.getAttributeValue(null, "origin"); String subdomains = xml.getAttributeValue(null, "subdomains"); if (origin != null) { this.addWhiteListEntry(origin, (subdomains != null) && (subdomains.compareToIgnoreCase("true") == 0)); } } else if (strNode.equals("log")) { String level = xml.getAttributeValue(null, "level"); LOG.i("PhoneGapLog", "Found log level %s", level); if (level != null) { LOG.setLogLevel(level); } } } try { eventType = xml.next(); } catch (XmlPullParserException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } /** * Add entry to approved list of URLs (whitelist) * * @param origin URL regular expression to allow * @param subdomains T=include all subdomains under origin */ public void addWhiteListEntry(String origin, boolean subdomains) { try { // Unlimited access to network resources if(origin.compareTo("*") == 0) { LOG.d(TAG, "Unlimited access to network resources"); whiteList.add(Pattern.compile("*")); } else { // specific access // check if subdomains should be included // TODO: we should not add more domains if * has already been added if (subdomains) { // XXX making it stupid friendly for people who forget to include protocol/SSL if(origin.startsWith("http")) { whiteList.add(Pattern.compile(origin.replaceFirst("https{0,1}://", "^https{0,1}://.*"))); } else { whiteList.add(Pattern.compile("^https{0,1}://.*"+origin)); } LOG.d(TAG, "Origin to allow with subdomains: %s", origin); } else { // XXX making it stupid friendly for people who forget to include protocol/SSL if(origin.startsWith("http")) { whiteList.add(Pattern.compile(origin.replaceFirst("https{0,1}://", "^https{0,1}://"))); } else { whiteList.add(Pattern.compile("^https{0,1}://"+origin)); } LOG.d(TAG, "Origin to allow: %s", origin); } } } catch(Exception e) { LOG.d(TAG, "Failed to add origin %s", origin); } } /** * Determine if URL is in approved list of URLs to load. * * @param url * @return */ private boolean isUrlWhiteListed(String url) { // Check to see if we have matched url previously if (whiteListCache.get(url) != null) { return true; } // Look for match in white list Iterator<Pattern> pit = whiteList.iterator(); while (pit.hasNext()) { Pattern p = pit.next(); Matcher m = p.matcher(url); // If match found, then cache it to speed up subsequent comparisons if (m.find()) { whiteListCache.put(url, true); return true; } } return false; } }
false
true
public void showWebPage(String url, boolean openExternal, boolean clearHistory, HashMap<String, Object> params) { //throws android.content.ActivityNotFoundException { LOG.d(TAG, "showWebPage(%s, %b, %b, HashMap", url, openExternal, clearHistory); // If clearing history if (clearHistory) { this.clearHistory(); } // If loading into our webview if (!openExternal) { // Make sure url is in whitelist if (url.startsWith("file://") || url.indexOf(this.baseUrl) == 0 || isUrlWhiteListed(url)) { // TODO: What about params? // Clear out current url from history, since it will be replacing it if (clearHistory) { this.urls.clear(); } // Load new URL this.loadUrl(url); } // Load in default viewer if not else { LOG.w(TAG, "showWebPage: Cannot load URL into webview since it is not in white list. Loading into browser instead. (URL="+url+")"); try { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); this.startActivity(intent); } catch (android.content.ActivityNotFoundException e) { LOG.e(TAG, "Error loading url "+url, e); } } } // Load in default view intent else { try { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); this.startActivity(intent); } catch (android.content.ActivityNotFoundException e) { LOG.e(TAG, "Error loading url "+url, e); } } } /** * Show the spinner. Must be called from the UI thread. * * @param title Title of the dialog * @param message The message of the dialog */ public void spinnerStart(final String title, final String message) { if (this.spinnerDialog != null) { this.spinnerDialog.dismiss(); this.spinnerDialog = null; } final DroidGap me = this; this.spinnerDialog = ProgressDialog.show(DroidGap.this, title , message, true, true, new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { me.spinnerDialog = null; } }); } /** * Stop spinner. */ public void spinnerStop() { if (this.spinnerDialog != null) { this.spinnerDialog.dismiss(); this.spinnerDialog = null; } } /** * Set the chrome handler. */ public class GapClient extends WebChromeClient { private String TAG = "PhoneGapLog"; private long MAX_QUOTA = 100 * 1024 * 1024; private DroidGap ctx; /** * Constructor. * * @param ctx */ public GapClient(Context ctx) { this.ctx = (DroidGap)ctx; } /** * Tell the client to display a javascript alert dialog. * * @param view * @param url * @param message * @param result */ @Override public boolean onJsAlert(WebView view, String url, String message, final JsResult result) { AlertDialog.Builder dlg = new AlertDialog.Builder(this.ctx); dlg.setMessage(message); dlg.setTitle("Alert"); //Don't let alerts break the back button dlg.setCancelable(true); dlg.setPositiveButton(android.R.string.ok, new AlertDialog.OnClickListener() { public void onClick(DialogInterface dialog, int which) { result.confirm(); } }); dlg.setOnCancelListener( new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { result.confirm(); } }); dlg.setOnKeyListener(new DialogInterface.OnKeyListener() { //DO NOTHING public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_BACK) { result.confirm(); return false; } else return true; } }); dlg.create(); dlg.show(); return true; } /** * Tell the client to display a confirm dialog to the user. * * @param view * @param url * @param message * @param result */ @Override public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) { AlertDialog.Builder dlg = new AlertDialog.Builder(this.ctx); dlg.setMessage(message); dlg.setTitle("Confirm"); dlg.setCancelable(true); dlg.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { result.confirm(); } }); dlg.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { result.cancel(); } }); dlg.setOnCancelListener( new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { result.cancel(); } }); dlg.setOnKeyListener(new DialogInterface.OnKeyListener() { //DO NOTHING public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_BACK) { result.cancel(); return false; } else return true; } }); dlg.create(); dlg.show(); return true; } /** * Tell the client to display a prompt dialog to the user. * If the client returns true, WebView will assume that the client will * handle the prompt dialog and call the appropriate JsPromptResult method. * * @param view * @param url * @param message * @param defaultValue * @param result */ @Override public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) { // Security check to make sure any requests are coming from the page initially // loaded in webview and not another loaded in an iframe. boolean reqOk = false; if (url.indexOf(this.ctx.baseUrl) == 0 || isUrlWhiteListed(url)) { reqOk = true; } // Calling PluginManager.exec() to call a native service using // prompt(this.stringify(args), "gap:"+this.stringify([service, action, callbackId, true])); if (reqOk && defaultValue != null && defaultValue.length() > 3 && defaultValue.substring(0, 4).equals("gap:")) { JSONArray array; try { array = new JSONArray(defaultValue.substring(4)); String service = array.getString(0); String action = array.getString(1); String callbackId = array.getString(2); boolean async = array.getBoolean(3); String r = pluginManager.exec(service, action, callbackId, message, async); result.confirm(r); } catch (JSONException e) { e.printStackTrace(); } } // Polling for JavaScript messages else if (reqOk && defaultValue != null && defaultValue.equals("gap_poll:")) { String r = callbackServer.getJavascript(); result.confirm(r); } // Calling into CallbackServer else if (reqOk && defaultValue != null && defaultValue.equals("gap_callbackServer:")) { String r = ""; if (message.equals("usePolling")) { r = ""+callbackServer.usePolling(); } else if (message.equals("restartServer")) { callbackServer.restartServer(); } else if (message.equals("getPort")) { r = Integer.toString(callbackServer.getPort()); } else if (message.equals("getToken")) { r = callbackServer.getToken(); } result.confirm(r); } // PhoneGap JS has initialized, so show webview // (This solves white flash seen when rendering HTML) else if (reqOk && defaultValue != null && defaultValue.equals("gap_init:")) { appView.setVisibility(View.VISIBLE); ctx.spinnerStop(); result.confirm("OK"); } // Show dialog else { final JsPromptResult res = result; AlertDialog.Builder dlg = new AlertDialog.Builder(this.ctx); dlg.setMessage(message); final EditText input = new EditText(this.ctx); if (defaultValue != null) { input.setText(defaultValue); } dlg.setView(input); dlg.setCancelable(false); dlg.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { String usertext = input.getText().toString(); res.confirm(usertext); } }); dlg.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { res.cancel(); } }); dlg.create(); dlg.show(); } return true; } /** * Handle database quota exceeded notification. * * @param url * @param databaseIdentifier * @param currentQuota * @param estimatedSize * @param totalUsedQuota * @param quotaUpdater */ @Override public void onExceededDatabaseQuota(String url, String databaseIdentifier, long currentQuota, long estimatedSize, long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) { LOG.d(TAG, "DroidGap: onExceededDatabaseQuota estimatedSize: %d currentQuota: %d totalUsedQuota: %d", estimatedSize, currentQuota, totalUsedQuota); if( estimatedSize < MAX_QUOTA) { //increase for 1Mb long newQuota = estimatedSize; LOG.d(TAG, "calling quotaUpdater.updateQuota newQuota: %d", newQuota); quotaUpdater.updateQuota(newQuota); } else { // Set the quota to whatever it is and force an error // TODO: get docs on how to handle this properly quotaUpdater.updateQuota(currentQuota); } } // console.log in api level 7: http://developer.android.com/guide/developing/debug-tasks.html @Override public void onConsoleMessage(String message, int lineNumber, String sourceID) { LOG.d(TAG, "%s: Line %d : %s", sourceID, lineNumber, message); } @Override public boolean onConsoleMessage(ConsoleMessage consoleMessage) { LOG.d(TAG, consoleMessage.message()); return true; } @Override /** * Instructs the client to show a prompt to ask the user to set the Geolocation permission state for the specified origin. * * @param origin * @param callback */ public void onGeolocationPermissionsShowPrompt(String origin, Callback callback) { super.onGeolocationPermissionsShowPrompt(origin, callback); callback.invoke(origin, true, false); } } /** * The webview client receives notifications about appView */ public class GapViewClient extends WebViewClient { DroidGap ctx; /** * Constructor. * * @param ctx */ public GapViewClient(DroidGap ctx) { this.ctx = ctx; } /** * Give the host application a chance to take over the control when a new url * is about to be loaded in the current WebView. * * @param view The WebView that is initiating the callback. * @param url The url to be loaded. * @return true to override, false for default behavior */ @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { // First give any plugins the chance to handle the url themselves if (this.ctx.pluginManager.onOverrideUrlLoading(url)) { } // If dialing phone (tel:5551212) else if (url.startsWith(WebView.SCHEME_TEL)) { try { Intent intent = new Intent(Intent.ACTION_DIAL); intent.setData(Uri.parse(url)); startActivity(intent); } catch (android.content.ActivityNotFoundException e) { LOG.e(TAG, "Error dialing "+url+": "+ e.toString()); } } // If displaying map (geo:0,0?q=address) else if (url.startsWith("geo:")) { try { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); startActivity(intent); } catch (android.content.ActivityNotFoundException e) { LOG.e(TAG, "Error showing map "+url+": "+ e.toString()); } } // If sending email (mailto:[email protected]) else if (url.startsWith(WebView.SCHEME_MAILTO)) { try { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); startActivity(intent); } catch (android.content.ActivityNotFoundException e) { LOG.e(TAG, "Error sending email "+url+": "+ e.toString()); } } // If sms:5551212?body=This is the message else if (url.startsWith("sms:")) { try { Intent intent = new Intent(Intent.ACTION_VIEW); // Get address String address = null; int parmIndex = url.indexOf('?'); if (parmIndex == -1) { address = url.substring(4); } else { address = url.substring(4, parmIndex); // If body, then set sms body Uri uri = Uri.parse(url); String query = uri.getQuery(); if (query != null) { if (query.startsWith("body=")) { intent.putExtra("sms_body", query.substring(5)); } } } intent.setData(Uri.parse("sms:"+address)); intent.putExtra("address", address); intent.setType("vnd.android-dir/mms-sms"); startActivity(intent); } catch (android.content.ActivityNotFoundException e) { LOG.e(TAG, "Error sending sms "+url+":"+ e.toString()); } } // All else else { // If our app or file:, then load into a new phonegap webview container by starting a new instance of our activity. // Our app continues to run. When BACK is pressed, our app is redisplayed. if (url.startsWith("file://") || url.indexOf(this.ctx.baseUrl) == 0 || isUrlWhiteListed(url)) { this.ctx.loadUrl(url); } // If not our application, let default viewer handle else { try { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); startActivity(intent); } catch (android.content.ActivityNotFoundException e) { LOG.e(TAG, "Error loading url "+url, e); } } } return true; } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { // Clear history so history.back() doesn't do anything. // So we can reinit() native side CallbackServer & PluginManager. view.clearHistory(); } /** * Notify the host application that a page has finished loading. * * @param view The webview initiating the callback. * @param url The url of the page. */ @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); // Clear timeout flag this.ctx.loadUrlTimeout++; // Try firing the onNativeReady event in JS. If it fails because the JS is // not loaded yet then just set a flag so that the onNativeReady can be fired // from the JS side when the JS gets to that code. if (!url.equals("about:blank")) { appView.loadUrl("javascript:try{ PhoneGap.onNativeReady.fire();}catch(e){_nativeReady = true;}"); } // Make app visible after 2 sec in case there was a JS error and PhoneGap JS never initialized correctly if (appView.getVisibility() == View.INVISIBLE) { Thread t = new Thread(new Runnable() { public void run() { try { Thread.sleep(2000); ctx.runOnUiThread(new Runnable() { public void run() { appView.setVisibility(View.VISIBLE); ctx.spinnerStop(); } }); } catch (InterruptedException e) { } } }); t.start(); } // Shutdown if blank loaded if (url.equals("about:blank")) { if (this.ctx.callbackServer != null) { this.ctx.callbackServer.destroy(); } this.ctx.endActivity(); } } /** * Report an error to the host application. These errors are unrecoverable (i.e. the main resource is unavailable). * The errorCode parameter corresponds to one of the ERROR_* constants. * * @param view The WebView that is initiating the callback. * @param errorCode The error code corresponding to an ERROR_* value. * @param description A String describing the error. * @param failingUrl The url that failed to load. */ @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { LOG.d(TAG, "DroidGap: GapViewClient.onReceivedError: Error code=%s Description=%s URL=%s", errorCode, description, failingUrl); // Clear timeout flag this.ctx.loadUrlTimeout++; // Stop "app loading" spinner if showing this.ctx.spinnerStop(); // Handle error this.ctx.onReceivedError(errorCode, description, failingUrl); } public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { final String packageName = this.ctx.getPackageName(); final PackageManager pm = this.ctx.getPackageManager(); ApplicationInfo appInfo; try { appInfo = pm.getApplicationInfo(packageName, PackageManager.GET_META_DATA); if ((appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) { // debug = true handler.proceed(); return; } else { // debug = false super.onReceivedSslError(view, handler, error); } } catch (NameNotFoundException e) { // When it doubt, lock it out! super.onReceivedSslError(view, handler, error); } } } /** * End this activity by calling finish for activity */ public void endActivity() { this.activityState = ACTIVITY_EXITING; this.finish(); } /** * Called when a key is pressed. * * @param keyCode * @param event */ @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (this.appView == null) { return super.onKeyDown(keyCode, event); } // If back key if (keyCode == KeyEvent.KEYCODE_BACK) { // If back key is bound, then send event to JavaScript if (this.bound) { this.appView.loadUrl("javascript:PhoneGap.fireDocumentEvent('backbutton');"); return true; } // If not bound else { // Go to previous page in webview if it is possible to go back if (this.urls.size() > 1) { this.backHistory(); return true; } // If not, then invoke behavior of super class else { return super.onKeyDown(keyCode, event); } } } // If menu key else if (keyCode == KeyEvent.KEYCODE_MENU) { this.appView.loadUrl("javascript:PhoneGap.fireDocumentEvent('menubutton');"); return true; } // If search key else if (keyCode == KeyEvent.KEYCODE_SEARCH) { this.appView.loadUrl("javascript:PhoneGap.fireDocumentEvent('searchbutton');"); return true; } return false; } /** * Any calls to Activity.startActivityForResult must use method below, so * the result can be routed to them correctly. * * This is done to eliminate the need to modify DroidGap.java to receive activity results. * * @param intent The intent to start * @param requestCode Identifies who to send the result to * * @throws RuntimeException */ @Override public void startActivityForResult(Intent intent, int requestCode) throws RuntimeException { LOG.d(TAG, "DroidGap.startActivityForResult(intent,%d)", requestCode); super.startActivityForResult(intent, requestCode); } /** * Launch an activity for which you would like a result when it finished. When this activity exits, * your onActivityResult() method will be called. * * @param command The command object * @param intent The intent to start * @param requestCode The request code that is passed to callback to identify the activity */ public void startActivityForResult(IPlugin command, Intent intent, int requestCode) { this.activityResultCallback = command; this.activityResultKeepRunning = this.keepRunning; // If multitasking turned on, then disable it for activities that return results if (command != null) { this.keepRunning = false; } // Start activity super.startActivityForResult(intent, requestCode); } @Override /** * Called when an activity you launched exits, giving you the requestCode you started it with, * the resultCode it returned, and any additional data from it. * * @param requestCode The request code originally supplied to startActivityForResult(), * allowing you to identify who this result came from. * @param resultCode The integer result code returned by the child activity through its setResult(). * @param data An Intent, which can return result data to the caller (various data can be attached to Intent "extras"). */ protected void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); IPlugin callback = this.activityResultCallback; if (callback != null) { callback.onActivityResult(requestCode, resultCode, intent); } } @Override public void setActivityResultCallback(IPlugin plugin) { this.activityResultCallback = plugin; } /** * Report an error to the host application. These errors are unrecoverable (i.e. the main resource is unavailable). * The errorCode parameter corresponds to one of the ERROR_* constants. * * @param errorCode The error code corresponding to an ERROR_* value. * @param description A String describing the error. * @param failingUrl The url that failed to load. */ public void onReceivedError(int errorCode, String description, String failingUrl) { final DroidGap me = this; // If errorUrl specified, then load it final String errorUrl = me.getStringProperty("errorUrl", null); if ((errorUrl != null) && (errorUrl.startsWith("file://") || errorUrl.indexOf(me.baseUrl) == 0 || isUrlWhiteListed(errorUrl)) && (!failingUrl.equals(errorUrl))) { // Load URL on UI thread me.runOnUiThread(new Runnable() { public void run() { me.showWebPage(errorUrl, true, true, null); } }); } // If not, then display error dialog else { me.appView.setVisibility(View.GONE); me.displayError("Application Error", description + " ("+failingUrl+")", "OK", true); } } /** * Display an error dialog and optionally exit application. * * @param title * @param message * @param button * @param exit */ public void displayError(final String title, final String message, final String button, final boolean exit) { final DroidGap me = this; me.runOnUiThread(new Runnable() { public void run() { AlertDialog.Builder dlg = new AlertDialog.Builder(me); dlg.setMessage(message); dlg.setTitle(title); dlg.setCancelable(false); dlg.setPositiveButton(button, new AlertDialog.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); if (exit) { me.endActivity(); } } }); dlg.create(); dlg.show(); } }); } /** * We are providing this class to detect when the soft keyboard is shown * and hidden in the web view. */ class LinearLayoutSoftKeyboardDetect extends LinearLayout { private static final String TAG = "SoftKeyboardDetect"; private int oldHeight = 0; // Need to save the old height as not to send redundant events private int oldWidth = 0; // Need to save old width for orientation change private int screenWidth = 0; private int screenHeight = 0; public LinearLayoutSoftKeyboardDetect(Context context, int width, int height) { super(context); screenWidth = width; screenHeight = height; } @Override /** * Start listening to new measurement events. Fire events when the height * gets smaller fire a show keyboard event and when height gets bigger fire * a hide keyboard event. * * Note: We are using callbackServer.sendJavascript() instead of * this.appView.loadUrl() as changing the URL of the app would cause the * soft keyboard to go away. * * @param widthMeasureSpec * @param heightMeasureSpec */ protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); LOG.v(TAG, "We are in our onMeasure method"); // Get the current height of the visible part of the screen. // This height will not included the status bar. int height = MeasureSpec.getSize(heightMeasureSpec); int width = MeasureSpec.getSize(widthMeasureSpec); LOG.v(TAG, "Old Height = %d", oldHeight); LOG.v(TAG, "Height = %d", height); LOG.v(TAG, "Old Width = %d", oldWidth); LOG.v(TAG, "Width = %d", width); // If the oldHeight = 0 then this is the first measure event as the app starts up. // If oldHeight == height then we got a measurement change that doesn't affect us. if (oldHeight == 0 || oldHeight == height) { LOG.d(TAG, "Ignore this event"); } // Account for orientation change and ignore this event/Fire orientation change else if(screenHeight == width) { int tmp_var = screenHeight; screenHeight = screenWidth; screenWidth = tmp_var; LOG.v(TAG, "Orientation Change"); } // If the height as gotten bigger then we will assume the soft keyboard has // gone away. else if (height > oldHeight) { LOG.v(TAG, "Throw hide keyboard event"); callbackServer.sendJavascript("PhoneGap.fireDocumentEvent('hidekeyboard');"); } // If the height as gotten smaller then we will assume the soft keyboard has // been displayed. else if (height < oldHeight) { LOG.v(TAG, "Throw show keyboard event"); callbackServer.sendJavascript("PhoneGap.fireDocumentEvent('showkeyboard');"); } // Update the old height for the next event oldHeight = height; oldWidth = width; } } /** * Load PhoneGap configuration from res/xml/phonegap.xml. * Approved list of URLs that can be loaded into DroidGap * <access origin="http://server regexp" subdomains="true" /> * Log level: ERROR, WARN, INFO, DEBUG, VERBOSE (default=ERROR) * <log level="DEBUG" /> */ private void loadConfiguration() { int id = getResources().getIdentifier("phonegap", "xml", getPackageName()); if (id == 0) { LOG.i("PhoneGapLog", "phonegap.xml missing. Ignoring..."); return; } XmlResourceParser xml = getResources().getXml(id); int eventType = -1; while (eventType != XmlResourceParser.END_DOCUMENT) { if (eventType == XmlResourceParser.START_TAG) { String strNode = xml.getName(); if (strNode.equals("access")) { String origin = xml.getAttributeValue(null, "origin"); String subdomains = xml.getAttributeValue(null, "subdomains"); if (origin != null) { this.addWhiteListEntry(origin, (subdomains != null) && (subdomains.compareToIgnoreCase("true") == 0)); } } else if (strNode.equals("log")) { String level = xml.getAttributeValue(null, "level"); LOG.i("PhoneGapLog", "Found log level %s", level); if (level != null) { LOG.setLogLevel(level); } } } try { eventType = xml.next(); } catch (XmlPullParserException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } /** * Add entry to approved list of URLs (whitelist) * * @param origin URL regular expression to allow * @param subdomains T=include all subdomains under origin */ public void addWhiteListEntry(String origin, boolean subdomains) { try { // Unlimited access to network resources if(origin.compareTo("*") == 0) { LOG.d(TAG, "Unlimited access to network resources"); whiteList.add(Pattern.compile("*")); } else { // specific access // check if subdomains should be included // TODO: we should not add more domains if * has already been added if (subdomains) { // XXX making it stupid friendly for people who forget to include protocol/SSL if(origin.startsWith("http")) { whiteList.add(Pattern.compile(origin.replaceFirst("https{0,1}://", "^https{0,1}://.*"))); } else { whiteList.add(Pattern.compile("^https{0,1}://.*"+origin)); } LOG.d(TAG, "Origin to allow with subdomains: %s", origin); } else { // XXX making it stupid friendly for people who forget to include protocol/SSL if(origin.startsWith("http")) { whiteList.add(Pattern.compile(origin.replaceFirst("https{0,1}://", "^https{0,1}://"))); } else { whiteList.add(Pattern.compile("^https{0,1}://"+origin)); } LOG.d(TAG, "Origin to allow: %s", origin); } } } catch(Exception e) { LOG.d(TAG, "Failed to add origin %s", origin); } } /** * Determine if URL is in approved list of URLs to load. * * @param url * @return */ private boolean isUrlWhiteListed(String url) { // Check to see if we have matched url previously if (whiteListCache.get(url) != null) { return true; } // Look for match in white list Iterator<Pattern> pit = whiteList.iterator(); while (pit.hasNext()) { Pattern p = pit.next(); Matcher m = p.matcher(url); // If match found, then cache it to speed up subsequent comparisons if (m.find()) { whiteListCache.put(url, true); return true; } } return false; } }
public void showWebPage(String url, boolean openExternal, boolean clearHistory, HashMap<String, Object> params) { //throws android.content.ActivityNotFoundException { LOG.d(TAG, "showWebPage(%s, %b, %b, HashMap", url, openExternal, clearHistory); // If clearing history if (clearHistory) { this.clearHistory(); } // If loading into our webview if (!openExternal) { // Make sure url is in whitelist if (url.startsWith("file://") || url.indexOf(this.baseUrl) == 0 || isUrlWhiteListed(url)) { // TODO: What about params? // Clear out current url from history, since it will be replacing it if (clearHistory) { this.urls.clear(); } // Load new URL this.loadUrl(url); } // Load in default viewer if not else { LOG.w(TAG, "showWebPage: Cannot load URL into webview since it is not in white list. Loading into browser instead. (URL="+url+")"); try { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); this.startActivity(intent); } catch (android.content.ActivityNotFoundException e) { LOG.e(TAG, "Error loading url "+url, e); } } } // Load in default view intent else { try { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); this.startActivity(intent); } catch (android.content.ActivityNotFoundException e) { LOG.e(TAG, "Error loading url "+url, e); } } } /** * Show the spinner. Must be called from the UI thread. * * @param title Title of the dialog * @param message The message of the dialog */ public void spinnerStart(final String title, final String message) { if (this.spinnerDialog != null) { this.spinnerDialog.dismiss(); this.spinnerDialog = null; } final DroidGap me = this; this.spinnerDialog = ProgressDialog.show(DroidGap.this, title , message, true, true, new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { me.spinnerDialog = null; } }); } /** * Stop spinner. */ public void spinnerStop() { if (this.spinnerDialog != null) { this.spinnerDialog.dismiss(); this.spinnerDialog = null; } } /** * Set the chrome handler. */ public class GapClient extends WebChromeClient { private String TAG = "PhoneGapLog"; private long MAX_QUOTA = 100 * 1024 * 1024; private DroidGap ctx; /** * Constructor. * * @param ctx */ public GapClient(Context ctx) { this.ctx = (DroidGap)ctx; } /** * Tell the client to display a javascript alert dialog. * * @param view * @param url * @param message * @param result */ @Override public boolean onJsAlert(WebView view, String url, String message, final JsResult result) { AlertDialog.Builder dlg = new AlertDialog.Builder(this.ctx); dlg.setMessage(message); dlg.setTitle("Alert"); //Don't let alerts break the back button dlg.setCancelable(true); dlg.setPositiveButton(android.R.string.ok, new AlertDialog.OnClickListener() { public void onClick(DialogInterface dialog, int which) { result.confirm(); } }); dlg.setOnCancelListener( new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { result.confirm(); } }); dlg.setOnKeyListener(new DialogInterface.OnKeyListener() { //DO NOTHING public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_BACK) { result.confirm(); return false; } else return true; } }); dlg.create(); dlg.show(); return true; } /** * Tell the client to display a confirm dialog to the user. * * @param view * @param url * @param message * @param result */ @Override public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) { AlertDialog.Builder dlg = new AlertDialog.Builder(this.ctx); dlg.setMessage(message); dlg.setTitle("Confirm"); dlg.setCancelable(true); dlg.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { result.confirm(); } }); dlg.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { result.cancel(); } }); dlg.setOnCancelListener( new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { result.cancel(); } }); dlg.setOnKeyListener(new DialogInterface.OnKeyListener() { //DO NOTHING public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_BACK) { result.cancel(); return false; } else return true; } }); dlg.create(); dlg.show(); return true; } /** * Tell the client to display a prompt dialog to the user. * If the client returns true, WebView will assume that the client will * handle the prompt dialog and call the appropriate JsPromptResult method. * * @param view * @param url * @param message * @param defaultValue * @param result */ @Override public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) { // Security check to make sure any requests are coming from the page initially // loaded in webview and not another loaded in an iframe. boolean reqOk = false; if (url.indexOf(this.ctx.baseUrl) == 0 || isUrlWhiteListed(url)) { reqOk = true; } // Calling PluginManager.exec() to call a native service using // prompt(this.stringify(args), "gap:"+this.stringify([service, action, callbackId, true])); if (reqOk && defaultValue != null && defaultValue.length() > 3 && defaultValue.substring(0, 4).equals("gap:")) { JSONArray array; try { array = new JSONArray(defaultValue.substring(4)); String service = array.getString(0); String action = array.getString(1); String callbackId = array.getString(2); boolean async = array.getBoolean(3); String r = pluginManager.exec(service, action, callbackId, message, async); result.confirm(r); } catch (JSONException e) { e.printStackTrace(); } } // Polling for JavaScript messages else if (reqOk && defaultValue != null && defaultValue.equals("gap_poll:")) { String r = callbackServer.getJavascript(); result.confirm(r); } // Calling into CallbackServer else if (reqOk && defaultValue != null && defaultValue.equals("gap_callbackServer:")) { String r = ""; if (message.equals("usePolling")) { r = ""+callbackServer.usePolling(); } else if (message.equals("restartServer")) { callbackServer.restartServer(); } else if (message.equals("getPort")) { r = Integer.toString(callbackServer.getPort()); } else if (message.equals("getToken")) { r = callbackServer.getToken(); } result.confirm(r); } // PhoneGap JS has initialized, so show webview // (This solves white flash seen when rendering HTML) else if (reqOk && defaultValue != null && defaultValue.equals("gap_init:")) { appView.setVisibility(View.VISIBLE); ctx.spinnerStop(); result.confirm("OK"); } // Show dialog else { final JsPromptResult res = result; AlertDialog.Builder dlg = new AlertDialog.Builder(this.ctx); dlg.setMessage(message); final EditText input = new EditText(this.ctx); if (defaultValue != null) { input.setText(defaultValue); } dlg.setView(input); dlg.setCancelable(false); dlg.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { String usertext = input.getText().toString(); res.confirm(usertext); } }); dlg.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { res.cancel(); } }); dlg.create(); dlg.show(); } return true; } /** * Handle database quota exceeded notification. * * @param url * @param databaseIdentifier * @param currentQuota * @param estimatedSize * @param totalUsedQuota * @param quotaUpdater */ @Override public void onExceededDatabaseQuota(String url, String databaseIdentifier, long currentQuota, long estimatedSize, long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) { LOG.d(TAG, "DroidGap: onExceededDatabaseQuota estimatedSize: %d currentQuota: %d totalUsedQuota: %d", estimatedSize, currentQuota, totalUsedQuota); if( estimatedSize < MAX_QUOTA) { //increase for 1Mb long newQuota = estimatedSize; LOG.d(TAG, "calling quotaUpdater.updateQuota newQuota: %d", newQuota); quotaUpdater.updateQuota(newQuota); } else { // Set the quota to whatever it is and force an error // TODO: get docs on how to handle this properly quotaUpdater.updateQuota(currentQuota); } } // console.log in api level 7: http://developer.android.com/guide/developing/debug-tasks.html @Override public void onConsoleMessage(String message, int lineNumber, String sourceID) { LOG.d(TAG, "%s: Line %d : %s", sourceID, lineNumber, message); } @Override public boolean onConsoleMessage(ConsoleMessage consoleMessage) { LOG.d(TAG, consoleMessage.message()); return true; } @Override /** * Instructs the client to show a prompt to ask the user to set the Geolocation permission state for the specified origin. * * @param origin * @param callback */ public void onGeolocationPermissionsShowPrompt(String origin, Callback callback) { super.onGeolocationPermissionsShowPrompt(origin, callback); callback.invoke(origin, true, false); } } /** * The webview client receives notifications about appView */ public class GapViewClient extends WebViewClient { DroidGap ctx; /** * Constructor. * * @param ctx */ public GapViewClient(DroidGap ctx) { this.ctx = ctx; } /** * Give the host application a chance to take over the control when a new url * is about to be loaded in the current WebView. * * @param view The WebView that is initiating the callback. * @param url The url to be loaded. * @return true to override, false for default behavior */ @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { // First give any plugins the chance to handle the url themselves if (this.ctx.pluginManager.onOverrideUrlLoading(url)) { } // If dialing phone (tel:5551212) else if (url.startsWith(WebView.SCHEME_TEL)) { try { Intent intent = new Intent(Intent.ACTION_DIAL); intent.setData(Uri.parse(url)); startActivity(intent); } catch (android.content.ActivityNotFoundException e) { LOG.e(TAG, "Error dialing "+url+": "+ e.toString()); } } // If displaying map (geo:0,0?q=address) else if (url.startsWith("geo:")) { try { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); startActivity(intent); } catch (android.content.ActivityNotFoundException e) { LOG.e(TAG, "Error showing map "+url+": "+ e.toString()); } } // If sending email (mailto:[email protected]) else if (url.startsWith(WebView.SCHEME_MAILTO)) { try { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); startActivity(intent); } catch (android.content.ActivityNotFoundException e) { LOG.e(TAG, "Error sending email "+url+": "+ e.toString()); } } // If sms:5551212?body=This is the message else if (url.startsWith("sms:")) { try { Intent intent = new Intent(Intent.ACTION_VIEW); // Get address String address = null; int parmIndex = url.indexOf('?'); if (parmIndex == -1) { address = url.substring(4); } else { address = url.substring(4, parmIndex); // If body, then set sms body Uri uri = Uri.parse(url); String query = uri.getQuery(); if (query != null) { if (query.startsWith("body=")) { intent.putExtra("sms_body", query.substring(5)); } } } intent.setData(Uri.parse("sms:"+address)); intent.putExtra("address", address); intent.setType("vnd.android-dir/mms-sms"); startActivity(intent); } catch (android.content.ActivityNotFoundException e) { LOG.e(TAG, "Error sending sms "+url+":"+ e.toString()); } } // All else else { // If our app or file:, then load into a new phonegap webview container by starting a new instance of our activity. // Our app continues to run. When BACK is pressed, our app is redisplayed. if (url.startsWith("file://") || url.indexOf(this.ctx.baseUrl) == 0 || isUrlWhiteListed(url)) { this.ctx.loadUrl(url); } // If not our application, let default viewer handle else { try { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); startActivity(intent); } catch (android.content.ActivityNotFoundException e) { LOG.e(TAG, "Error loading url "+url, e); } } } return true; } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { // Clear history so history.back() doesn't do anything. // So we can reinit() native side CallbackServer & PluginManager. view.clearHistory(); } /** * Notify the host application that a page has finished loading. * * @param view The webview initiating the callback. * @param url The url of the page. */ @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); // Clear timeout flag this.ctx.loadUrlTimeout++; // Try firing the onNativeReady event in JS. If it fails because the JS is // not loaded yet then just set a flag so that the onNativeReady can be fired // from the JS side when the JS gets to that code. if (!url.equals("about:blank")) { appView.loadUrl("javascript:try{ PhoneGap.onNativeReady.fire();}catch(e){_nativeReady = true;}"); } // Make app visible after 2 sec in case there was a JS error and PhoneGap JS never initialized correctly if (appView.getVisibility() == View.INVISIBLE) { Thread t = new Thread(new Runnable() { public void run() { try { Thread.sleep(2000); ctx.runOnUiThread(new Runnable() { public void run() { appView.setVisibility(View.VISIBLE); ctx.spinnerStop(); } }); } catch (InterruptedException e) { } } }); t.start(); } // Shutdown if blank loaded if (url.equals("about:blank")) { if (this.ctx.callbackServer != null) { this.ctx.callbackServer.destroy(); } this.ctx.endActivity(); } } /** * Report an error to the host application. These errors are unrecoverable (i.e. the main resource is unavailable). * The errorCode parameter corresponds to one of the ERROR_* constants. * * @param view The WebView that is initiating the callback. * @param errorCode The error code corresponding to an ERROR_* value. * @param description A String describing the error. * @param failingUrl The url that failed to load. */ @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { LOG.d(TAG, "DroidGap: GapViewClient.onReceivedError: Error code=%s Description=%s URL=%s", errorCode, description, failingUrl); // Clear timeout flag this.ctx.loadUrlTimeout++; // Stop "app loading" spinner if showing this.ctx.spinnerStop(); // Handle error this.ctx.onReceivedError(errorCode, description, failingUrl); } public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { final String packageName = this.ctx.getPackageName(); final PackageManager pm = this.ctx.getPackageManager(); ApplicationInfo appInfo; try { appInfo = pm.getApplicationInfo(packageName, PackageManager.GET_META_DATA); if ((appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) { // debug = true handler.proceed(); return; } else { // debug = false super.onReceivedSslError(view, handler, error); } } catch (NameNotFoundException e) { // When it doubt, lock it out! super.onReceivedSslError(view, handler, error); } } } /** * End this activity by calling finish for activity */ public void endActivity() { this.activityState = ACTIVITY_EXITING; this.finish(); } /** * Called when a key is pressed. * * @param keyCode * @param event */ @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (this.appView == null) { return super.onKeyDown(keyCode, event); } // If back key if (keyCode == KeyEvent.KEYCODE_BACK) { // If back key is bound, then send event to JavaScript if (this.bound) { this.appView.loadUrl("javascript:PhoneGap.fireDocumentEvent('backbutton');"); return true; } // If not bound else { // Go to previous page in webview if it is possible to go back if (this.urls.size() > 1) { this.backHistory(); return true; } // If not, then invoke behavior of super class else { return super.onKeyDown(keyCode, event); } } } // If menu key else if (keyCode == KeyEvent.KEYCODE_MENU) { this.appView.loadUrl("javascript:PhoneGap.fireDocumentEvent('menubutton');"); return true; } // If search key else if (keyCode == KeyEvent.KEYCODE_SEARCH) { this.appView.loadUrl("javascript:PhoneGap.fireDocumentEvent('searchbutton');"); return true; } return false; } /** * Any calls to Activity.startActivityForResult must use method below, so * the result can be routed to them correctly. * * This is done to eliminate the need to modify DroidGap.java to receive activity results. * * @param intent The intent to start * @param requestCode Identifies who to send the result to * * @throws RuntimeException */ @Override public void startActivityForResult(Intent intent, int requestCode) throws RuntimeException { LOG.d(TAG, "DroidGap.startActivityForResult(intent,%d)", requestCode); super.startActivityForResult(intent, requestCode); } /** * Launch an activity for which you would like a result when it finished. When this activity exits, * your onActivityResult() method will be called. * * @param command The command object * @param intent The intent to start * @param requestCode The request code that is passed to callback to identify the activity */ public void startActivityForResult(IPlugin command, Intent intent, int requestCode) { this.activityResultCallback = command; this.activityResultKeepRunning = this.keepRunning; // If multitasking turned on, then disable it for activities that return results if (command != null) { this.keepRunning = false; } // Start activity super.startActivityForResult(intent, requestCode); } @Override /** * Called when an activity you launched exits, giving you the requestCode you started it with, * the resultCode it returned, and any additional data from it. * * @param requestCode The request code originally supplied to startActivityForResult(), * allowing you to identify who this result came from. * @param resultCode The integer result code returned by the child activity through its setResult(). * @param data An Intent, which can return result data to the caller (various data can be attached to Intent "extras"). */ protected void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); IPlugin callback = this.activityResultCallback; if (callback != null) { callback.onActivityResult(requestCode, resultCode, intent); } } @Override public void setActivityResultCallback(IPlugin plugin) { this.activityResultCallback = plugin; } /** * Report an error to the host application. These errors are unrecoverable (i.e. the main resource is unavailable). * The errorCode parameter corresponds to one of the ERROR_* constants. * * @param errorCode The error code corresponding to an ERROR_* value. * @param description A String describing the error. * @param failingUrl The url that failed to load. */ public void onReceivedError(final int errorCode, final String description, final String failingUrl) { final DroidGap me = this; // If errorUrl specified, then load it final String errorUrl = me.getStringProperty("errorUrl", null); if ((errorUrl != null) && (errorUrl.startsWith("file://") || errorUrl.indexOf(me.baseUrl) == 0 || isUrlWhiteListed(errorUrl)) && (!failingUrl.equals(errorUrl))) { // Load URL on UI thread me.runOnUiThread(new Runnable() { public void run() { me.showWebPage(errorUrl, true, true, null); } }); } // If not, then display error dialog else { me.runOnUiThread(new Runnable() { public void run() { me.appView.setVisibility(View.GONE); me.displayError("Application Error", description + " ("+failingUrl+")", "OK", true); } }); } } /** * Display an error dialog and optionally exit application. * * @param title * @param message * @param button * @param exit */ public void displayError(final String title, final String message, final String button, final boolean exit) { final DroidGap me = this; me.runOnUiThread(new Runnable() { public void run() { AlertDialog.Builder dlg = new AlertDialog.Builder(me); dlg.setMessage(message); dlg.setTitle(title); dlg.setCancelable(false); dlg.setPositiveButton(button, new AlertDialog.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); if (exit) { me.endActivity(); } } }); dlg.create(); dlg.show(); } }); } /** * We are providing this class to detect when the soft keyboard is shown * and hidden in the web view. */ class LinearLayoutSoftKeyboardDetect extends LinearLayout { private static final String TAG = "SoftKeyboardDetect"; private int oldHeight = 0; // Need to save the old height as not to send redundant events private int oldWidth = 0; // Need to save old width for orientation change private int screenWidth = 0; private int screenHeight = 0; public LinearLayoutSoftKeyboardDetect(Context context, int width, int height) { super(context); screenWidth = width; screenHeight = height; } @Override /** * Start listening to new measurement events. Fire events when the height * gets smaller fire a show keyboard event and when height gets bigger fire * a hide keyboard event. * * Note: We are using callbackServer.sendJavascript() instead of * this.appView.loadUrl() as changing the URL of the app would cause the * soft keyboard to go away. * * @param widthMeasureSpec * @param heightMeasureSpec */ protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); LOG.v(TAG, "We are in our onMeasure method"); // Get the current height of the visible part of the screen. // This height will not included the status bar. int height = MeasureSpec.getSize(heightMeasureSpec); int width = MeasureSpec.getSize(widthMeasureSpec); LOG.v(TAG, "Old Height = %d", oldHeight); LOG.v(TAG, "Height = %d", height); LOG.v(TAG, "Old Width = %d", oldWidth); LOG.v(TAG, "Width = %d", width); // If the oldHeight = 0 then this is the first measure event as the app starts up. // If oldHeight == height then we got a measurement change that doesn't affect us. if (oldHeight == 0 || oldHeight == height) { LOG.d(TAG, "Ignore this event"); } // Account for orientation change and ignore this event/Fire orientation change else if(screenHeight == width) { int tmp_var = screenHeight; screenHeight = screenWidth; screenWidth = tmp_var; LOG.v(TAG, "Orientation Change"); } // If the height as gotten bigger then we will assume the soft keyboard has // gone away. else if (height > oldHeight) { LOG.v(TAG, "Throw hide keyboard event"); callbackServer.sendJavascript("PhoneGap.fireDocumentEvent('hidekeyboard');"); } // If the height as gotten smaller then we will assume the soft keyboard has // been displayed. else if (height < oldHeight) { LOG.v(TAG, "Throw show keyboard event"); callbackServer.sendJavascript("PhoneGap.fireDocumentEvent('showkeyboard');"); } // Update the old height for the next event oldHeight = height; oldWidth = width; } } /** * Load PhoneGap configuration from res/xml/phonegap.xml. * Approved list of URLs that can be loaded into DroidGap * <access origin="http://server regexp" subdomains="true" /> * Log level: ERROR, WARN, INFO, DEBUG, VERBOSE (default=ERROR) * <log level="DEBUG" /> */ private void loadConfiguration() { int id = getResources().getIdentifier("phonegap", "xml", getPackageName()); if (id == 0) { LOG.i("PhoneGapLog", "phonegap.xml missing. Ignoring..."); return; } XmlResourceParser xml = getResources().getXml(id); int eventType = -1; while (eventType != XmlResourceParser.END_DOCUMENT) { if (eventType == XmlResourceParser.START_TAG) { String strNode = xml.getName(); if (strNode.equals("access")) { String origin = xml.getAttributeValue(null, "origin"); String subdomains = xml.getAttributeValue(null, "subdomains"); if (origin != null) { this.addWhiteListEntry(origin, (subdomains != null) && (subdomains.compareToIgnoreCase("true") == 0)); } } else if (strNode.equals("log")) { String level = xml.getAttributeValue(null, "level"); LOG.i("PhoneGapLog", "Found log level %s", level); if (level != null) { LOG.setLogLevel(level); } } } try { eventType = xml.next(); } catch (XmlPullParserException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } /** * Add entry to approved list of URLs (whitelist) * * @param origin URL regular expression to allow * @param subdomains T=include all subdomains under origin */ public void addWhiteListEntry(String origin, boolean subdomains) { try { // Unlimited access to network resources if(origin.compareTo("*") == 0) { LOG.d(TAG, "Unlimited access to network resources"); whiteList.add(Pattern.compile("*")); } else { // specific access // check if subdomains should be included // TODO: we should not add more domains if * has already been added if (subdomains) { // XXX making it stupid friendly for people who forget to include protocol/SSL if(origin.startsWith("http")) { whiteList.add(Pattern.compile(origin.replaceFirst("https{0,1}://", "^https{0,1}://.*"))); } else { whiteList.add(Pattern.compile("^https{0,1}://.*"+origin)); } LOG.d(TAG, "Origin to allow with subdomains: %s", origin); } else { // XXX making it stupid friendly for people who forget to include protocol/SSL if(origin.startsWith("http")) { whiteList.add(Pattern.compile(origin.replaceFirst("https{0,1}://", "^https{0,1}://"))); } else { whiteList.add(Pattern.compile("^https{0,1}://"+origin)); } LOG.d(TAG, "Origin to allow: %s", origin); } } } catch(Exception e) { LOG.d(TAG, "Failed to add origin %s", origin); } } /** * Determine if URL is in approved list of URLs to load. * * @param url * @return */ private boolean isUrlWhiteListed(String url) { // Check to see if we have matched url previously if (whiteListCache.get(url) != null) { return true; } // Look for match in white list Iterator<Pattern> pit = whiteList.iterator(); while (pit.hasNext()) { Pattern p = pit.next(); Matcher m = p.matcher(url); // If match found, then cache it to speed up subsequent comparisons if (m.find()) { whiteListCache.put(url, true); return true; } } return false; } }
diff --git a/src/main/java/hudson/plugins/promoted_builds/conditions/DownstreamPassCondition.java b/src/main/java/hudson/plugins/promoted_builds/conditions/DownstreamPassCondition.java index c94eb06..9da94b8 100644 --- a/src/main/java/hudson/plugins/promoted_builds/conditions/DownstreamPassCondition.java +++ b/src/main/java/hudson/plugins/promoted_builds/conditions/DownstreamPassCondition.java @@ -1,170 +1,177 @@ package hudson.plugins.promoted_builds.conditions; import hudson.CopyOnWrite; import hudson.Util; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.Hudson; import hudson.model.Result; import hudson.model.TaskListener; import hudson.model.listeners.RunListener; import hudson.plugins.promoted_builds.JobPropertyImpl; import hudson.plugins.promoted_builds.PromotionCondition; import hudson.plugins.promoted_builds.PromotionConditionDescriptor; import hudson.plugins.promoted_builds.PromotionCriterion; import net.sf.json.JSONObject; import org.kohsuke.stapler.StaplerRequest; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; /** * @author Kohsuke Kawaguchi */ public class DownstreamPassCondition extends PromotionCondition { /** * List of downstream jobs that are used as the promotion criteria. * * Every job has to have at least one successful build for us to promote a build. */ private final String jobs; public DownstreamPassCondition(String jobs) { this.jobs = jobs; } public String getJobs() { return jobs; } @Override public boolean isMet(AbstractBuild<?,?> build) { for (AbstractProject<?,?> j : getJobList()) { boolean passed = false; for( AbstractBuild<?,?> b : build.getDownstreamBuilds(j) ) { if(b.getResult()== Result.SUCCESS) { passed = true; break; } } if(!passed) // none of the builds of this job passed. return false; } return true; } public PromotionConditionDescriptor getDescriptor() { return DescriptorImpl.INSTANCE; } /** * List of downstream jobs that we need to monitor. * * @return never null. */ public List<AbstractProject<?,?>> getJobList() { List<AbstractProject<?,?>> r = new ArrayList<AbstractProject<?,?>>(); for (String name : Util.tokenize(jobs,",")) { AbstractProject job = Hudson.getInstance().getItemByFullName(name.trim(),AbstractProject.class); if(job!=null) r.add(job); } return r; } /** * Short-cut for {@code getJobList().contains(job)}. */ public boolean contains(AbstractProject<?,?> job) { if(!jobs.contains(job.getFullName())) return false; // quick rejection test for (String name : Util.tokenize(jobs,",")) { if(name.trim().equals(job.getFullName())) return true; } return false; } public static final class DescriptorImpl extends PromotionConditionDescriptor { public DescriptorImpl() { super(DownstreamPassCondition.class); new RunListenerImpl().register(); } public boolean isApplicable(AbstractProject<?,?> item) { return true; } public String getDisplayName() { return "When the following downstream projects build successfully"; } public PromotionCondition newInstance(StaplerRequest req, JSONObject formData) throws FormException { return new DownstreamPassCondition(formData.getString("jobs")); } public static final DescriptorImpl INSTANCE = new DescriptorImpl(); } /** * {@link RunListener} to pick up completions of downstream builds. * * <p> * This is a single instance that receives all the events everywhere in the system. * @author Kohsuke Kawaguchi */ private static final class RunListenerImpl extends RunListener<AbstractBuild<?,?>> { public RunListenerImpl() { super((Class)AbstractBuild.class); } @Override public void onCompleted(AbstractBuild<?,?> build, TaskListener listener) { // this is not terribly efficient, for(AbstractProject<?,?> j : Hudson.getInstance().getAllItems(AbstractProject.class)) { JobPropertyImpl p = j.getProperty(JobPropertyImpl.class); if(p!=null) { for (PromotionCriterion c : p.getCriteria()) { boolean considerPromotion = false; for (PromotionCondition cond : c.getConditions()) { if (cond instanceof DownstreamPassCondition) { DownstreamPassCondition dpcond = (DownstreamPassCondition) cond; - if(dpcond.contains(build.getParent())) + if(dpcond.contains(build.getParent())) { considerPromotion = true; + break; + } } } if(considerPromotion) { try { AbstractBuild<?,?> u = build.getUpstreamRelationshipBuild(j); - if(u!=null && c.considerPromotion(u)) + if(u==null) { + // no upstream build. perhaps a configuration problem? + if(build.getResult()==Result.SUCCESS) + listener.getLogger().println("WARNING: "+j.getFullDisplayName()+" appears to use this job as a promotion criteria, but no fingerprint is recorded."); + } else + if(c.considerPromotion(u)) listener.getLogger().println("Promoted "+u); } catch (IOException e) { e.printStackTrace(listener.error("Failed to promote a build")); } } } } } } /** * List of downstream jobs that we are interested in. */ @CopyOnWrite private static volatile Set<AbstractProject> DOWNSTREAM_JOBS = Collections.emptySet(); /** * Called whenever some {@link JobPropertyImpl} changes to update {@link #DOWNSTREAM_JOBS}. */ public static void rebuildCache() { Set<AbstractProject> downstreams = new HashSet<AbstractProject>(); DOWNSTREAM_JOBS = downstreams; } } }
false
true
public void onCompleted(AbstractBuild<?,?> build, TaskListener listener) { // this is not terribly efficient, for(AbstractProject<?,?> j : Hudson.getInstance().getAllItems(AbstractProject.class)) { JobPropertyImpl p = j.getProperty(JobPropertyImpl.class); if(p!=null) { for (PromotionCriterion c : p.getCriteria()) { boolean considerPromotion = false; for (PromotionCondition cond : c.getConditions()) { if (cond instanceof DownstreamPassCondition) { DownstreamPassCondition dpcond = (DownstreamPassCondition) cond; if(dpcond.contains(build.getParent())) considerPromotion = true; } } if(considerPromotion) { try { AbstractBuild<?,?> u = build.getUpstreamRelationshipBuild(j); if(u!=null && c.considerPromotion(u)) listener.getLogger().println("Promoted "+u); } catch (IOException e) { e.printStackTrace(listener.error("Failed to promote a build")); } } } } } }
public void onCompleted(AbstractBuild<?,?> build, TaskListener listener) { // this is not terribly efficient, for(AbstractProject<?,?> j : Hudson.getInstance().getAllItems(AbstractProject.class)) { JobPropertyImpl p = j.getProperty(JobPropertyImpl.class); if(p!=null) { for (PromotionCriterion c : p.getCriteria()) { boolean considerPromotion = false; for (PromotionCondition cond : c.getConditions()) { if (cond instanceof DownstreamPassCondition) { DownstreamPassCondition dpcond = (DownstreamPassCondition) cond; if(dpcond.contains(build.getParent())) { considerPromotion = true; break; } } } if(considerPromotion) { try { AbstractBuild<?,?> u = build.getUpstreamRelationshipBuild(j); if(u==null) { // no upstream build. perhaps a configuration problem? if(build.getResult()==Result.SUCCESS) listener.getLogger().println("WARNING: "+j.getFullDisplayName()+" appears to use this job as a promotion criteria, but no fingerprint is recorded."); } else if(c.considerPromotion(u)) listener.getLogger().println("Promoted "+u); } catch (IOException e) { e.printStackTrace(listener.error("Failed to promote a build")); } } } } } }
diff --git a/src/com/app/getconnected/activities/RateRideActivity.java b/src/com/app/getconnected/activities/RateRideActivity.java index 15222de..1b8b81f 100644 --- a/src/com/app/getconnected/activities/RateRideActivity.java +++ b/src/com/app/getconnected/activities/RateRideActivity.java @@ -1,60 +1,60 @@ package com.app.getconnected.activities; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.View; import android.widget.EditText; import android.widget.RadioButton; import android.widget.RadioGroup; import com.app.getconnected.R; public class RateRideActivity extends BaseActivity { String rideId; RadioGroup rideRatingField; EditText rideCommentField; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_rate_ride); // TODO find out why initLayout crashes - // initLayout(R.string.title_activity_rate_ride, true, false, false, - // false); + initLayout(R.string.title_activity_rate_ride, true, true, true, + false); rideId = getIntent().getStringExtra("rideId"); rideRatingField = (RadioGroup) findViewById(R.id.ride_rating); rideRatingField.check(R.id.good); rideCommentField = (EditText) findViewById(R.id.ride_comment); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.rate_ride, menu); return true; } /** * Finishes this activity without sending any rating * * @param view */ public void cancelRating(View view) { finish(); } /** * Sends the rating to the API and finishes this activity * * @param view */ public void sendRating(View view) { String rating = ((RadioButton) findViewById(rideRatingField .getCheckedRadioButtonId())).getTag().toString(); String comment = rideCommentField.getText().toString(); Log.d("DEBUG", "ride ID:" + rideId + ", Rating: " + rating + ", Comment: " + comment); finish(); } }
true
true
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_rate_ride); // TODO find out why initLayout crashes // initLayout(R.string.title_activity_rate_ride, true, false, false, // false); rideId = getIntent().getStringExtra("rideId"); rideRatingField = (RadioGroup) findViewById(R.id.ride_rating); rideRatingField.check(R.id.good); rideCommentField = (EditText) findViewById(R.id.ride_comment); }
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_rate_ride); // TODO find out why initLayout crashes initLayout(R.string.title_activity_rate_ride, true, true, true, false); rideId = getIntent().getStringExtra("rideId"); rideRatingField = (RadioGroup) findViewById(R.id.ride_rating); rideRatingField.check(R.id.good); rideCommentField = (EditText) findViewById(R.id.ride_comment); }